Concatenation of Strings and characters

后端 未结 5 1761
日久生厌
日久生厌 2020-12-24 10:46

The following statements,

String string = \"string\";   

string = string +((char)65) + 5;
System.out.println(string);

Produce the output <

5条回答
  •  天涯浪人
    2020-12-24 10:55

    Case 1

    string = string +((char)65) + 5;
    

    everything is treated as String but in second case

    Sequence of operation performed:

    • string +((char)65 = stringA
    • stringA + 5 = stringA5

    Case 2

     string += ((char)65) + 5;
    

    first right hand side is calculated means first operation will be like ((char)65) + 5, So result of ((char)65) + 5 is 70 and after that += operation.

    Sequence of operation performed:

    • (char)65 + 5 = 70
    • string + 70 = string70

    Lets see 1 more example

    String string = "string";
    string += ((char)65) + 5 + "A";
    System.out.println(string); 
    

    Output string70A

    Reason Same first right hand side is calculated and sequesce of opertion performed is

    • (char)65 + 5 = 70
    • 70 + "A" = 70A
    • string + 70A = string70A

提交回复
热议问题