Meaning of + symbol with Strings in Java println statement

后端 未结 7 907
孤独总比滥情好
孤独总比滥情好 2021-01-16 09:57

I\'m new to Java. What does the below mean?

(addition) + sign in println

System.out.println ("Count is: " + i);

7条回答
  •  隐瞒了意图╮
    2021-01-16 10:13

    It does exactly what it does outside the println method, id adds to objects:

    if the objects are Strings it concatenates them:

    "hello" + "world" --> "helloworld"
    

    if the objects are numbers it adds the UNLESS there's a String to the left (or at least a String with higher precedence).

    2 + 4 + "hello" --> "6hello"
    
    "hello" + 2 + 4 --> "hello24"
    
    "hello" + (2 + 4) --> "hello6"
    

    if the object is any thing else it will treat them as Strings using the toString() method

提交回复
热议问题