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

后端 未结 4 1425
广开言路
广开言路 2021-01-02 00:58

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

4条回答
  •  無奈伤痛
    2021-01-02 01:39

    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 :)

提交回复
热议问题