Java: String immutability and operator == -


this question has answer here:

i have code cannot understand. in beginning can see 2 identical strings, , when compare them use of operator == says true, same equals() method, when create 2 identical strings during runtime operator == says false. why happening ?

does mean when hardcode identical strings placed in same position in memory , both references point it? found similar question, there no explicit answer.

public class stringtesting {     public static void main(string[] args){         string string1 = "hello";                   //\                                                     // } same place in memory ?         string string2 = "hello";                   ///          system.out.println(string1 == string2);     //true         system.out.println(string1.equals(string2));      //true          string string3 = "hey";         string string4 = "he";          system.out.println(string3 == string4);          //false         system.out.println(string3.equals(string4));     //false          string4 += "y";          system.out.println(string3 == string4);          //false ????         system.out.println(string3.equals(string4));     //true          system.out.println(string3 + " " + string4);      //hey hey     } } 

the following compound assignment operator:

string4 += "y"; 

performs string concatenation @ runtime. since value of string4 evaluated @ runtime only. , string concatenation done @ runtime creates new object.

from jls section 3.10.5 (see towards end of section):

strings computed concatenation @ run time newly created , therefore distinct.

however if perform concatenation of 2 string literals, won't create different objects. following code return true:

"he" + "y" == "hey"; 

that jls section contains code segment various string concatenation example:

string hello = "hello",  string lo = "lo";  system.out.print((hello == "hello") + " ");          // true system.out.print((other.hello == hello) + " ");      // true system.out.print((other.other.hello == hello) + " ");// true system.out.print((hello == ("hel" + "lo")) + " ");     // true system.out.print((hello == ("hel" + lo)) + " ");       // false system.out.println(hello == ("hel" + lo).intern());    // true 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -