I have some mistakes | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

I have some mistakes

What is the output of this code? class A { int x; public A(int y) { x=y; } public String toString() { return "x"; } } public class B { public static void main(String[] args) { System.out.print(new A(10)); } } why the output is x where is the call of toString?

5th May 2019, 8:49 PM
ABADA S
ABADA S - avatar
10 Answers
+ 4
A bit more about toString(); A test = new A(10); Implicit calling of toString(): System.out.println(test); --> if you don't override the toString() method you get something like this: className + [a hashcode] A[@4828] --> not useful You want 10 as output or maybe [10] or what ever you want. That's why you write your own toString() method (which overrides the default toString()) Explicit calling: System.out.println(test.toString()); But you don't need to do this.
5th May 2019, 9:27 PM
Denise Roßberg
Denise Roßberg - avatar
+ 6
so the method toString exists at Object class that all classes are inherited from it that why I have to override this method
5th May 2019, 9:29 PM
ABADA S
ABADA S - avatar
+ 6
thanks master Denise Roßberg
5th May 2019, 9:31 PM
ABADA S
ABADA S - avatar
+ 2
but where is the invocation of toString method
5th May 2019, 9:00 PM
ABADA S
ABADA S - avatar
+ 2
Output is an x, because the toString() returns "x". It would be the same as String str = "x"; return str; You can do this: return "" + x; or this: return Integer.toString(x);
5th May 2019, 9:16 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
5th May 2019, 9:29 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
The method is part of java.lang.Object. https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html Edit: Try to print an array (without using Arrays.toString()) then you see it why it is better to override it.
5th May 2019, 9:34 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Your welcome :)
5th May 2019, 9:36 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
The invocation of the toString is implicit. When you write System.out.print (test); the compiler reads it as System.out.print (test.toString()); Also as said above your toString will always return x as a string as opposed to x as a variable
5th May 2019, 9:51 PM
Hothouseinwar Polik
Hothouseinwar Polik - avatar
+ 1
or public String toString() { return String.valueOf(x); }
5th May 2019, 11:33 PM
zemiak