+ 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?
10 Respuestas
+ 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.
+ 6
so the method toString exists at Object class that all classes are inherited from it that why I have to override this method
+ 6
thanks master Denise Roßberg
+ 2
but where is the invocation of toString method
+ 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);
+ 2
You can also read this:
https://www.baeldung.com/java-tostring
+ 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.
+ 2
Your welcome :)
+ 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
+ 1
or
public String toString() {
return String.valueOf(x);
}