Meaning of + symbol with Strings in Java println statement

后端 未结 7 908
孤独总比滥情好
孤独总比滥情好 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:05

    In that context, the + operator is acting as the string concatenation operator. It acts as a different operator in the context of two integral types, where addition will be performed.

    Assuming i is an integral type, it'll be converted to a String and then added on to the end of a new string beginning with "Count is: ". That new string is then printed.

    ie. If i had the value 0, it'd be the same as:

    "Count is: " + "0"
    

    Which would be:

    "Count is: 0"
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-16 10:14

    + is string concatenation operator and it is used for conversion of other objects to strings (based upon the implementation of toString() method) and also concatenate two strings.

    String str1="Hello";
    String str2="World"
    
    String result=str1 + " " + str2;
    
    0 讨论(0)
  • 2021-01-16 10:14

    The + sign in the context of strings is the concatenation operator. It joins two strings together.

    E.g.

    String str = "hello" + "world";
    

    would result in a String object called str, with a value of "helloworld".

    0 讨论(0)
  • 2021-01-16 10:15

    The plus operator has a double meaning. Its a concatination operator as well. As the "Count is:" is of type String the "i" (Integer?) is converted to a String as well.

    I haven't read it as I prefer reference books, however some really like the Book Head First Java as it seems to explain concepts.

    0 讨论(0)
  • 2021-01-16 10:17

    The + in arithmetic adds 2 numbers together, like this:

    2 + 2 = 4
    

    now apply the same thing to a string:

    "hello " + "world!" = "hello world!"
    

    now adding strings and variables will do this:

    int number = 4;
    String string = "what was the number? oh yeah: "+number;
    System.out.println(string);
    

    if all goes well you should get "what was the number? oh yeah: 4"

    Java took the value of the variable and put it into the string for you, hope this helped!

    0 讨论(0)
提交回复
热议问题