I am new to Java and I am trying to solve an exercise given by my professor. He has given this class
public class MioPunto {
public int x;
public int y;
public String toString() {
return ("[" + x + "," + y + "]");
}
}
and I am supposed to write another class with a main method. Into the main I have to print the coordinates without explicitly calling the "toString" method. I unconsciously solved it in this way
public class TestMioPunto{
public static void main(String[] args){
MioPunto inizio = new MioPunto();
MioPunto fine = new MioPunto();
inizio.x=10;
inizio.y=10;
fine.x=20;
fine.y=30;
System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
}
}
and the output is
I can't understand how Java automatically called the toString method (brackets and commas), can you please explain?
Java calls toString
when you use +
on a String
and an object.
So your
System.out.println("Inizio: " + inizio + "\n" + "Fine: " + fine);
is the same as
System.out.println("Inizio: " + inizio.toString() + "\n" + "Fine: " + fine.toString());
except that if inizio
or fine
is null
, the first won't give you an error (you'll see null
in the string instead) but the second will.
From the JLS's section on the String Concatenation operator:
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
which refers to the String Conversion section, which says (after discussing converting primitives to string):
...
Now only reference values need to be considered:
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.