If you look inside these objects, you will find a magic method like toString .
This method serves to represent an object as a string.
Each class has its own implementation of the method. For example, Integer following code:
public static String toString(int i, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; /* Use the faster version */ if (radix == 10) { return toString(i); } char buf[] = new char[33]; boolean negative = (i < 0); int charPos = 32; if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = digits[-(i % radix)]; i = i / radix; } buf[charPos] = digits[-i]; if (negative) { buf[--charPos] = '-'; } return new String(buf, charPos, (33 - charPos)); }
As you can see, the method returns a string (roughly) return new String(buf, charPos, (33 - charPos));
Other classes have the same thing. In any class, you can also implement it.
You can write anything there, even return "hello, world";
And this very System.out.println implicitly calls this same toString method on an object.
Perhaps add an example:
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { Test test = new Test(); System.out.print(test); } public static class Test { public String toString() { return "Hello, world!"; } } }
https://ideone.com/jLvbDM