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 p
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.
All objects in Java inherit from the class Object. If you look at that document, you'll see that Object
specifies a toString
method which converts the object into a String. Since all non-primitive types (including Class
es) are Object
s, anything can be converted into a string using its toString
method.
Classes can override this method to provide their own way of being turned into a string. For example, the String
class overrides Object.toString
to return itself. Class
overrides it to return the name of the class. This lets you specify how you want your object to be output.
As you probably know, every class in Java inherits from the Object
class. This means that every class automatically has the method toString()
, which returns a representation of the object as a String
. When you concatenate a string with an object, or if you pass an Object
into an argument where there should be a String
, Java automatically calls the toString()
method to convert it into a String
. In your case, the toString()
method has been overridden to return the name of the class.
You can see this happen with other objects, too:
Set s = new Set();
s.add(1);
s.add(3);
s.add(5);
System.out.println(s);
will output "[1, 3, 5]".
See the code:
787 public void println(Object x) {
788 String s = String.valueOf(x);
789 synchronized (this) {
790 print(s);
791 newLine();
792 }
793 }
Note the String.valueOf(x)
.
Bonus for asking a good question:
632 public void print(String s) {
633 if (s == null) {
634 s = "null";
635 }
636 write(s);
637 }
That's why it prints null
when the object is null :)