Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing Strings returned by toString()  RSS feed

 
Tresa P Anthony
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am confused about how the toString()works.




Sec 3.10.5 of the JLS says:
Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
Strings computed at run time are newly created and therefore distinct.


In the above code, isn't i.toString() evaluated at run time? But the output says both strings are Equal. Why is this so? Please explain.

Thanks
Tresa
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that you are comparing strings with ==.
Don't use == to compare strings. Use .equals(...) instead.

The == operator checks if the two references you are comparing refer to the exact same String object. That's not the same as having two separate String objects that contain the same sequence of characters.


It is up to the implementation of class Integer, class String etc. if it wants to implement some caching mechanism, to that if you call toString() twice on the same Integer object it returns exactly the same String object twice. You should not write programs that count on that implementation specific behaviour.

Probably class Integer has such an optimization. I haven't looked at the source code for class Integer, but it probably caches the result of toString when you call it for the first time, something like this:
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With my JDK (1.4 for Windows, part of JBuilder), the result is Not Equal. But when I change 50 to 5, I get Equal.

The same result when run by JRE 1.5.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer.toString() calls String.getValue(int) which according to the API
is exactly the one returned by the Integer.toString method of one argument
and Integer.toString(int) returns an appropriate String literal if the argument is equal to Integer.MAX_VALUE or is between -3 and 10 inclusive. Otherwise it returns a new String object
So should return true if i contains the value Integer.MAX_VALUE or is between -3 and 10 inclusive and false otherwise.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!