How does System.out.print() work?

后端 未结 9 2219
鱼传尺愫
鱼传尺愫 2020-11-27 03:40

I have worked with Java for a quite a long time, and I was wondering how the function System.out.print() works.

Here is my doubt:

Being a functi

9条回答
  •  抹茶落季
    2020-11-27 04:22

    @ikis, firstly as @Devolus said these are not multiple aruements passed to print(). Indeed all these arguments passed get concatenated to form a single String. So print() does not teakes multiple arguements (a. k. a. var-args). Now the concept that remains to discuss is how print() prints any type of the arguement passed to it.

    To explain this - toString() is the secret:

    System is a class, with a static field out, of type PrintStream. So you're calling the println(Object x) method of a PrintStream.

    It is implemented like this:

     public void println(Object x) {
       String s = String.valueOf(x);
       synchronized (this) {
           print(s);
           newLine();
       }
    }
    

    As wee see, it's calling the String.valueOf(Object) method. This is implemented as follows:

     public static String valueOf(Object obj) {
       return (obj == null) ? "null" : obj.toString();
    }
    

    And here you see, that toString() is called.

    So whatever is returned from the toString() method of that class, same gets printed.

    And as we know the toString() is in Object class and thus inherits a default iplementation from Object.

    ex: Remember when we have a class whose toString() we override and then we pass that ref variable to print, what do you see printed? - It's what we return from the toString().

提交回复
热议问题