jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes String Trim Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Trim" Watch "String Trim" New topic

String Trim

Vijay Jagannathan

Joined: Feb 17, 2003
Posts: 22

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?

Wayan Saryada
Ranch Hand

Joined: Feb 05, 2004
Posts: 105

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.


Website: Learn Java by Examples
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078

[ October 17, 2005: Message edited by: Ken Blair ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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.


Java API Documentation
The Java Tutorial
Vijay Jagannathan

Joined: Feb 17, 2003
Posts: 22
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?

Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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:

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link: http://aspose.com/file-tools
subject: String Trim
It's not a secret anymore!