Difference between addition of String Literals and String objects

后端 未结 4 1879
忘掉有多难
忘掉有多难 2021-01-14 10:23

What is the difference between an addition of String Literal and String Object?

For example

    String s1 =\"hello\";
    String s2 =\"hello1\";
             


        
4条回答
  •  遥遥无期
    2021-01-14 11:16

    Because the compiler optimizes concatenation of String literals.

    In practice this should not matter (most of the time), as you usually want to compare Strings for equality using the equals method and not to check if the object references are the same.

    Also note that you can intern s5 using e.g.:

    s5 = s5.intern();
    

    This is rarely needed, though.

提交回复
热议问题