
-----------------------------------
UnusedUsername
Tue Oct 30, 2007 6:39 pm

Odd String Behaviour
-----------------------------------
I'm leaving some details of the code out but those details shouldn't matter.

String expectedValue = ...
String output = myClass.toString();

System.out.println(myClass.toString().length()); //prints 0
System.out.println(output.length()); //prints a number, e.g. 72
System.out.println(expectedValue.length()); //prints a number, e.g. 72

System.out.println(output.equals(expectedValue)); //prints true
System.out.println(myClass.toString().equals(expectedValue)); //prints false

The output are in the comments, but I have no idea why they are like that. Can someone please explain?

-----------------------------------
HeavenAgain
Tue Oct 30, 2007 7:53 pm

RE:Odd String Behaviour
-----------------------------------
I believe this have something to do with "comparing address/references" rather than comparing what you acually see. 
example could be 
String s4 = new String ("restful"),
s5 = new String ("restful"),
s6 = new String ("peaceful"),
s7 = s4,
s8 = "restful",
s9 = "restful";

System.out.println (s4.equals (s5)); // true
System.out.println (s4.equals (s6)); // false
System.out.println (s4 == s5); // false
System.out.println (s4 == s7); //true
System.out.println (s4 == s8); // false
System.out.println (s8 == s9); // true

hope this help, but one thing i dont get in your code is the myClass.toString().length(), seems to me, if that gives you 0 then output.length() should give you 0 too
weird

-----------------------------------
Ultrahex
Wed Oct 31, 2007 1:30 am

Re: Odd String Behaviour
-----------------------------------
myClass.toString() should be equal to your pointer/reference, so its something like test$myclass@3e25a5
myClass.toString().length() should be the length of it. as in the reference. (which i get 19)
output.length() = 19 also ... (i dont understand how you got 0 in that one case, maybe variations between sdk/jre's)
also are you running Ready To Program Java? (which we dont recommend, but yes it sucks if you have to use for school)

... but anyhow try this code: (since maybe extra brackets will fix for no good reason)


System.out.println((myClass.toString()).length()); 
System.out.println(output.length());
System.out.println(expectedValue.length());

System.out.println(output.equals(expectedValue));
System.out.println((myClass.toString()).equals(expectedValue)); 


-----------------------------------
UnusedUsername
Fri Nov 02, 2007 10:28 am

Re: Odd String Behaviour
-----------------------------------
After debugging, I found the problem is within the toString() method. Thanks for the help.
