Java. getClass() returns a class, how come I can get a string too

java

When I use System.out.println(obj.getClass()) it doesn't give me any error. From what I understand getClass() returns a Class type.
Since println() will print only strings, how come instead of a class, println is getting a String?

Best Answer

System.out.println(someobj) is always equivalent to:

System.out.println(String.valueOf(someobj));

And, for non-null values of someobj, that prints someobj.toString();

In your case, you are doing println(obj.getClass()) so you are really doing:

System.out.println(String.valueOf(obj.getClass()));

which is calling the toString method on the class.