This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java and have Dr. Raoul-Gabriel Urma & Richard Warburton on-line! See this thread for details.
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.
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.
My Linked In
posted 17 years ago
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.
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...