Immutable objects and references - String
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   s_s
Posted On:   Saturday, March 28, 2009 02:02 PM

Hi, The output of the following code is : false - string true - st Please help me understand why its true in second case. public class Test { public static void main(String[] args) { String s1 = new String("test"); String s2 = new String("test"); if(s1 == s2){ System.out.println("true - string "); }else{ System.out.println("false - string "); } String st1 = "test"; String st2 = "test"; if(st1 == st2){ System.out.println("true - st "); }else{ System.out.println("false - st "); }    More>>

Hi, The output of the following code is :

false - string

true - st

Please help me understand why its true in second case.


			
public class Test {
public static void main(String[] args) {
String s1 = new String("test");
String s2 = new String("test");
if(s1 == s2){
System.out.println("true - string ");
}else{
System.out.println("false - string ");
}

String st1 = "test";
String st2 = "test";
if(st1 == st2){
System.out.println("true - st ");
}else{
System.out.println("false - st ");
}

}//main
}
   <<Less

Re: Immutable objects and references - String

Posted By:   Tim_Frith  
Posted On:   Tuesday, March 31, 2009 01:47 PM

The second way you declared the strings uses the string pool. As an optimization, before instantiating a new string Java checks if that string is already in use and if so, just refers to it.


Using new String() forces Java to always instantiate a new object.


Of course, you shouldn't be comparing strings with == anyways. You should be doing st1.equals(st2).

About | Sitemap | Contact