Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Trim

 
Vijay Jagannathan
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I believe that the following piece of code should give an answer true. But when complied, it gives false. Can someone please help me with this?



Regards
Vijay
 
Wayan Saryada
Ranch Hand
Posts: 105
IntelliJ IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vijay,

I think it becuase when you are comparing a string using == operator, using this operator Java will compare the reference address of those strings. If you want to compare their contents use String.equals() method instead.

Regards,
Wayan
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

[ October 17, 2005: Message edited by: Ken Blair ]
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ken Blair:


[ October 17, 2005: Message edited by: Ken Blair ]


I agree that your last example is bad, but it is entirely predictable if you understand how == works with String objects. In this case, the condition of the if statement evaluates to true because you are using String literals here. If you want to know more, you should google for "String Constant Pool" or something along those lines.

Layne
 
Vijay Jagannathan
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your comments. Sorry for not being more specific.

But what I was confused with was this:
-> When a new String is created and exists in the pool, both the new and existing String will point to the same object.

Based on this idea, when a String Object "String" is created and a second string object "String" is compared to it, it should point to the same object and the code should return a true.

For Example:



will return true.

But my code above



returns false. Does this have anything to do with the trim() function?

Regards
Vijay
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first thing to do is to check the API for String - do not trust your intuition or "feeling". You will read in the API for the trim method that " XXXXXXX ".trim() returns a new String object. Although the String object will contain the characters XXXXXXX, it does not say that the new String object will be the same as one previously defined as a String literal as in "XXXXXXX" or as a previously interned String containing those characters. So a "==" comparison will evaluate to false.

You may use the intern method of the String class to enter a string into the pool:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic