0

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 enter image description here I can't understand how Java automatically called the toString method (brackets and commas), can you please explain?

rafc
  • 78
  • 11

2 Answers2

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Since java.lang.Object is an implicit base class of MioPunto (because it is a base class of all Java objects), method MioPunto.toString() is an override of Object.toString() method.

Since all objects have an implementation of toString(), Java compiler can freely add an invocation of toString() on any object in a chain of string concatenations performed with the + operator:

The string concatenation operator + (§15.18.1), which, when given a String operand and a reference, will convert the reference to a String by invoking the toString method of the referenced object (using "null" if either the reference or the result of toString is a null reference), and then will produce a newly created String that is the concatenation of the two strings.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523