Generel this is a comparison on the object reference, thats why i don�t understand this code ! Byte b1 = new Byte("127"); if(b1.toString() == b1.toString()) System.out.println("True"); else System.out.println("False"); Here is the result false, but why, here returns the b1.toString methoed "127" and they are both in the String pool and pointing on the same String Object or ??? Can anyone tell me why this code prints "True";
Simply because the toString method returns a new reference to the string, and although, the referenced string are the same, the references themselves are different. Comparing with == only compares the "value" of the references themselves and not the values they are referencing.
You can make your code to return "True" if you did something like: Byte b1 = new Byte("127"); String s1, s2; s1 = b1.toString(); s2 = s1; if(s1 == s2) System.out.println("True"); else System.out.println("False"); wherein you assign s2 to the same reference as s1.
Owee<br />SCJP 1.4
Joined: Aug 26, 2001
Isn't it because each toString() method returns a new String object? I don't understand the term 'new reference'. In fact, the case of String is particular. toString() does in fact return a new reference, BUT the referenced string should already be in the constant string pool somewhere. If you will, "127" is put into the string pool. Then b1.toString() returns one reference to "127" and the second b1.toString() invocation returns another reference to "127". Finally, when == is used, the value of the references themselves are compared and not the value they are referencing (i.e. "127"). References are more or less addresses in memory which contain the address of the value they are referencing, much like pointers. == compares the address of the references and not the address they are pointing to.
Joined: Jun 04, 2002
Woah, I never heard of that before. Will it make a difference if I stick with my explanation, i.e. will believing that a new String object is made by the toString() method instead of the 'new reference' thingy make some wrong answers right (and vice versa)? My exam's tomorrow, and last-minute cramming isn't gonna help me any.
My exam's tomorrow, and last-minute cramming isn't gonna help me any.[/QB]
Paul, All the best for your exam. plz do not forget to share your experience with ranchers thanks murthy
Joined: Aug 26, 2001
will believing that a new String object is made by the toString() method instead of the 'new reference' thingy Believe what helps you the most I wish you good luck for tomorrow Come back with good news...
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