This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
--------------------------------------------------------------------------- at ( 1 ) , the addresses are compared which are different for b1.toString ( ) and b1.toString .
whereas at ( 2 ) the values that the strings have are compared which are equal
so , in a sense the values are the same but the addressses are different others please shed some light on the issue
regards , Bhavesh
That is correct. if you want to compare the contents then use the equals() method, whereas the == operator checks if variables are referring to the same object. So in the example b1.toString() creates one String object and the second b1.toString() creates another String object. Therefore the variables are not refering to the same object. The below example demonstrate how to get two variables refering to the same object.
So if you wanted to check the contents of temp against temp2 then you would do the following:
just try this. String s1="abc"; String s2="abc"; here both (s1==s2) and (s1.equals(s2)) returns true. (s1.equals(s2)) is true as both s1 and s2 contains the same value. (s1==s2)is true due to the internal mechanism of java. In java two String containing the same value are referenced to the same object to save space in the internal String table.
but in the following case String s1="abc"; String s2= new String("abc"); (s1.equals(s2)) returns true as both contains the same value and (s1==s2) returns false as here we are forcing the compiler to allocate new memory space to s2.
As per the language specification: Literal strings and strings computed by constant expressions refer to the same String object.
Following is the example from the Java lang spec: String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " "); //----> PRINTS TRUE System.out.print((hello == ("Hel"+"lo")) + " "); //----> PRINTS TRUE System.out.print((hello == ("Hel"+lo)) + " "); //----> PRINTS FALSE
The expression "hel" + lo in the 3rd statement can't be determined by compier to be a constant. lo is a variable and could have been assigned any other value before line 3 -- compiler can never detemine this. Hence the 3rd statement prints false.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com