How does System.out.print() work?

后端 未结 9 2174
鱼传尺愫
鱼传尺愫 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:40

    Even though it look as if System.put.print...() take a variable number of arguments it doesn't. If you look closely, the string is simply concatenated and you can do the same with any string. The only thing that happens is, that the objects you are passing in, are implicitily converted to a string by java calling the toString() method.

    If you try to do this it will fail:

    int i = 0;
    String s = i;
    System.out.println(s);
    

    Reason is, because here the implicit conversion is not done.

    However if you change it to

    int i = 0;
    String s = "" + i;
    System.out.println(s);
    

    It works and this is what happens when using System.put.print...() as well.

    If you want to implement a variable number of arguments in java to mimimc something like C printf you can declare it like this:

    public void t(String s, String ... args)
    {
        String val = args[1];
    }
    

    What happens here is that an array of Strings is passed in, with the length of the provided arguments. Here Java can do the type checking for you.

    If you want truly a printf then you have to do it like this:

    public void t(String s, Object ... args)
    {
        String val = args[1].toString();
    }
    

    Then would you have to cast or interpret the arguments accordingly.

    0 讨论(0)
  • 2020-11-27 04:44

    Evidently, the compiler was made in a confusing way although the compiler developers thought they added some smartness. The true smartness they should really add is to look entire argument and interpret + operator consistently. For example, System.out.println(1+2+"hello"+3+4); should output 3hello7 instead of 3hello34

    0 讨论(0)
  • 2020-11-27 04:45

    It is a very sensitive point to understand how to work System.out.print. If the first element is String then plus(+) operator works as String concate operator. If the first element is integer plus(+) operator works as mathematical operator.

    public static void main(String args[]) {
        System.out.println("String" + 8 + 8); //String88
        System.out.println(8 + 8+ "String"); //16String
    }
    
    0 讨论(0)
提交回复
热议问题