This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
public class abc { public static void main(String args[]) { String str1 = "string1"; String str2 = "string1"; System.out.println(str1==s.str); System.out.println(str1.equals(str2)); System.out.println(str1=="string1"); } }
I tried the above comparisons and got the result as 'true' in all the three cases. but if i initialize str1 and str2 as : String str1 = new String("string1"); String str2 = new String("string1"); This comparison returns false. plez explain the reason for the same...i will be greatful.... Monika
sasi dhulipala
Ranch Hand
Joined: Dec 28, 2000
Posts: 31
posted
0
Originally posted by Monika Pasricha: public class abc { public static void main(String args[]) { String str1 = "string1"; String str2 = "string1"; System.out.println(str1==s.str); System.out.println(str1.equals(str2)); System.out.println(str1=="string1"); } } when you say that String str1 = "string1"; internally an anonymous string object is created and every time "string" is equated to some String object ( like in this case str1, str2,.... ) the reference to the same anonymous String object is returned . This means that str1 and str2 will have the same reference value. yr first println statement should be corrected as System.out.println(str1==str2); //returns true becoz of same reference System.out.println(str1.equals(str2)); // this mearly compares // //the contents of the two string objects since in this case both //store "string" it returns true System.out.println(str1=="string1"); // this is same as case 1 //above where an anonymous object is created internally. Ans is //true. String str1 = new String("string1"); String str2 = new String("string1"); In the above cases we are forcibly creating two new string objects and hence two new references . there for all the tests except System.out.println(str1.equals(str2)); should retrun false. HTH Sasidhar
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.