aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Immutable Strings!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Immutable Strings!!!!" Watch "Immutable Strings!!!!" New topic
Author

Immutable Strings!!!!

Preety Narashimhan
Greenhorn

Joined: Aug 19, 2002
Posts: 28
public class Test012
{
public static void main(String args[])
{
String s0 = new String("Java");
String s1 = s0.trim();
String s2 = s0.substring(0, 4);
String s3 = s0.toString();
System.out.println(s0 == s1);
System.out.println(s0 == s2);
System.out.println(s0 == s3);
}
}
The Answer to this is actually
true
true
true
The first and the Third case is understandable, but in the second case that is "substring" even the docs mention that a new String is returned.(though there is no mention about such an example!!).
Please explain, how can the second case return a true?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12327
    
    1
That is a fluke of a particular implementation - obviously it sees that the start and end correspond exactly to the existing string and just returns the existing string. Similar to the way trim returns the existing string if there are no characters to trim.
You should not get any questions that depend on a fluke of implementation.
Bill


Java Resources at www.wbrogden.com
Preety Narashimhan
Greenhorn

Joined: Aug 19, 2002
Posts: 28
Thanks a lot ..
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Immutable Strings!!!!
 
Similar Threads
confusion in String methods
String comparison question
Strings
again String anyone??
String tricky question