How To Compare Strings With == in Java

By Angsuman Chakraborty, Gaea News Network
Saturday, February 25, 2006

Almost every java developer finds one fine morning that he cannot compare String with “==” as he has been doing with int or char. Then either he finds out or someone kindly tells him that objects cannot be compared with “==”. He has to use equals(Object) method. However rarely, if ever, he realizes that it is possible to use == to compare two String for equality. There are two greatThe benefits of being able to use == for String comparison - improved performance and memory usage reduction.

To achieve this you need to call the magic method - intern() on a String.

String class internally maintains a private pool of strings which are initially empty.

When the intern() method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

All literal strings and string-valued constant expressions are interned.

So if you compare an interned String with another interned String or String constant then you can safely use == instead of (or in addition to) equals(Object) method.

This is widely used while processing large XML documents where the tags are interned for faster comparison and lower memory consumption.

Update: Based two comments below by Christian and Markus, I re-evaluated the validity of touted performance benefit. With JDK 1.5 (I tested with) there isn’t any performance difference between equals(Object) and == for String. It is most likely because of equals implementation which first does a == comparison anyway as pointed out by Markus Kohler. Thanks for correcting me guys.

PS. It is amazing how Java is improving over the versions. Several previous assumptions of performance are not valid anymore. There goes another. I wonder when String concatenation with + operator will follow suit.

Discussion
June 22, 2010: 3:09 am

very nice information how to compare strings in JAVA. Thanks sharing with informative blog.


priyanka
May 6, 2010: 1:00 am

how to compare string containing ‘/’ ?


A.Pushpanjali
April 28, 2009: 4:57 pm

HI,

I have a small question in java.
I have two inputs , which are word documents .I want to compare these two document values.Is it possible in Java.If any one knows this please let me know.

thanks & Regards,
A.Pushpanjali


A.Pushpanjali
April 28, 2009: 4:53 pm

HI,

I have a small question in java.
I have to inputs , which are word documents .I want to compare these two document values.Is it possible in Java.If any one knows this please let me know.

thanks & Regards,
A.Pushpanjali


heroin
January 15, 2009: 3:41 am

jeh: you must be f* joking


jeh
March 1, 2008: 8:38 am

how to uncompare 2 strings??

if (arr3[u].equalsIgnoreCase(search))
is to compare

how about the right this??
if (arr3[u] NOT EQUAL TO (search));

what is tha code for that??


Erik
January 26, 2007: 10:33 am

Krishna: you may want to make sure there’s no trailing spaces by doing:

if (name3.trim().equals(name1.trim()))…

Or even compare case-insensitively by using

name.toUpper(); // I think

At least if you want to be Microsoftish :D

otherwise I see not problems with your code… (other than calling passwords for “name” — be careful with variable names or it will come back and bite you some day… had a colleague that used zib and zob and variations thereof for his variable names… guess how fun that was to work with? ;o)

HTH

/Erik

December 24, 2006: 12:09 pm

out.println(” user from form”);String name3= request.getParameter(”uname”);out.println(name3);
out.println(”user from DB”);String name1= rs.getString(”uname”);out.println(name1);
String test=name1;
out.println(”pass from DB”);String name2= rs.getString(”pass”);out.println(name2);

out.println(” pass from form”);String name4= request.getParameter(”pass”);out.println(name4);

if (name3.equals(name1))
{
out.println(”Authentication successful- usewwerwrwrname is correct”);
}
else {
out.println(”kindly check your usernasame and/or password”);
}

the above are my codes, i get the output in the jsp page as :

user from form krishna
user from DB krishna
pass from DB krishna
pass from form krishna
kindly check your usernasame and/or password

what is wrong in my statement… the strings are same, but the if clause is not executed.. will be kindful to know the answer..

April 3, 2006: 3:38 am

String.equals()


Srinivas
April 2, 2006: 5:25 am

Hi
I am in urgent need for the program in java which compares two huge strings and return boolean value

Do help me by giving the appraoch and code
with regards
seenu


Niels Harremoes
March 23, 2006: 11:37 am

Whoops - the parser ate my <’s.
Anyway, you get my menaing.


Niels Harremoes
March 23, 2006: 11:35 am

In your specific case,
String myString = "first bit"+"next bit";
is still better, since the compiler will do the
optimization while compiling - so it will compile to the same bytecode as
String myString = "first bitnext bit";

But for the more general case where it is not constant strings, you are almost right.

The only difference is that in java 1.5 the compiler will use a StringBuilder - it’s just like StringBuffer, but without the synchronisation. With some JVM’s, this might make the + version marginally faster.
As well as more readable.

Now, if you start doing multiple concatenations in different statements, it is a different matter. In that case, using an explicit StringBuilder will save the jvm from constructing a lot of temporary StringBuilders.

It will be much faster to do

StringBuilder result = new StringBuilder();
for(int i = 0; i

than


String result = "";
for(int i = 0; i


Mark
March 1, 2006: 2:14 am

Hi,
Regarding your last comment, it was my understanding that since 1.5 there are no performance advantages to doing:


StringBuffer buff = New StringBuffer("first bit");
buff.append(" next bit");

instead of:

String myString = "first bit"+"next bit";

as most 1.5 jvm implement the string + operator using the StringBuffer class anyway.

Please correct me if I am wrong.


Niels Harremoes
February 27, 2006: 2:29 am

intern() will pollute the intern constant pool and you will not get the entries out of the pool

Older JVMs will put .intern()’ed strings into a pool of strings that live for the duration of the JVM instance. Thus, if a long-living process uses .intern() on dynamic strings, it will eventually run out of memory.

A quick test is this program:

public static void main(String[] args) {
while (true) {
System.out.println(String.valueOf(Math.random()).intern());
}
}

- it may run out of memory.

February 26, 2006: 9:00 am

Thanks for the correction. I checked with sample code and you guys are absolutely right. With current versions of JDK (I tested with 1.5) I couldn’t find any performance difference.

However I couldn’t understand the “intern() will pollute the intern constant pool and you will not get the entries out of the pool” part.
Do you mean not being able to garbage collect?
Christian, can you please clarify?


Markus Kohler
February 26, 2006: 8:13 am

Hi,
I’m not sure whether using intern should really be recommended.

Actually if you compare the speed of intern versus a simple hashmap at least on SUN JDK 1.4 the hashmap is much faster. Another point is the String.equals first compares for == anyway. So there’s almost no point to use == directly.
You are right some XML parsers use intern, but I’m not sure that is optimal. They may save some memory by using intern instead of a simple HashMap.

Regards,
Markus

February 26, 2006: 3:52 am

This is highly problematic. intern() will pollute the intern constant pool and you will not get the entries out of the pool. I think it is the best to use a private data structure mimicking the behaviour.

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :