This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Methods

 
rahul V kumar
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
rahul V kumar
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That was really helpful.
 
Robbie kyodo
Ranch Hand
Posts: 97
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ->
 
Rajinder Yadav
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic