| Author |
String Methods
|
rahul V kumar
Ranch Hand
Joined: May 20, 2003
Posts: 82
|
|
Can anyone whats going behind the scenes for the followig code snippets Q1) ****************************************** if(" String ".trim() == "String") System.out.println("Equal"); else System.out.println("Not Equal"); Answer is "Not Equal" ****************************************** Q2) ****************************************** if("String".substring(0,6) == "String") System.out.println("Equal"); else System.out.println("Not Equal"); Answer is "Equal" ****************************************** Q3) ****************************************** if("String".replace('g','G') == "String".replace('g','G')) System.out.println("Equal"); else System.out.println("Not Equal"); Answer is "Not Equal" ****************************************** Q4) ********************************************** if("String".replace('t','t') == "String") System.out.println("Equal"); else System.out.println("Not Equal"); Answer is "Equal" ******************************************** Thanks
|
 |
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
|
|
Strings are immutable. That means that they can never be changed. Because of this, most of the methods of the String class behave a certain way - if the result of the method is a different String than the original, they create a brand new String object and return it. If the result is the same, however, rather than creating a useless object, the method simply returns the original String that was passed as an argument back. I hope that helps, Corey
|
SCJP Tipline, etc.
|
 |
rahul V kumar
Ranch Hand
Joined: May 20, 2003
Posts: 82
|
|
|
Thanks. That was really helpful.
|
 |
Robbie kyodo
Ranch Hand
Joined: May 05, 2003
Posts: 97
|
|
String s1 = "ABC"; String s2 = new String (s1); String s3 = new String (s1); if (s2 == s3) // return false why ?? s2.trim() == s2.toUpperCase() // true why ?? can u explain using below diagram ? s2 -> s1 -> "ABC" s3 ->
|
SCJP 2 1.4
|
 |
Rajinder Yadav
Greenhorn
Joined: May 13, 2003
Posts: 27
|
|
Read what Corey said earlier s1 is created on constant string constant pool s2 and s3 are created on the heap s1 -> "ABC" s2 -> "ABC" s3 -> "ABC"
|
When faced with an easy thing to do and a hard thing to do, always pick the right thing to do!<p><a href="http://yadav.shorturl.com" target="_blank" rel="nofollow">Rajinder Yadav</a>
|
 |
 |
|
|
subject: String Methods
|
|
|