You are on page 1of 12

How do I compare strings in Java?

- Stack Overflow

sign up

Questions

Tags

log in

Users

tour

help

Badges

stack overflow careers

search

Unanswered

Ask Question

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no
registration required.

Take the 2-minute tour


How do I compare strings in Java?


asked 5 years ago
viewed 794054 times
active 12 days ago

730

4G Telecom - Sr Engineer - R&D


(VoLTE, RCS, WebRTC) - MS
Mavenir Systems India
Bengaluru, India / relocation

Is == bad? When should it and should it not be used? What's the difference?
java

342

Looking for a job?

I've been using the == operator in my program to compare all my strings so far.
However, I ran into a
bug, changed one of them into .equals() instead, and it fixed the bug.

string

equality

sip

share

edited Jan 23 '13 at 13:36

community wiki

Nathan H

Frontend and UX pro at Chumbak


Chumbak Design
Bangalore, India
javascript

locked by animuson Jan 26 at 20:00


This question's answer is a collaborative effort: if you see something that can be improved, just edit to improve it!
No additional answers can be added here

Java Engineer - 4+ Years


Fission Labs
Hyderabad, India
java

12 Also its good to know that, if you are overridding .equals () method, make sure you are overridding

Leaving a link to my explanation on why == works the way it does on Objects:


stackoverflow.com/a/19966154/2284641

Johannes H.

== will work some of the time, as java has a String pool, where it tries to reuse memory references of
commonly used strings. But == compares that objects are equal, not the values... so .equals() is the
proper use you want to use.

VenomFangs

javascript

Geez... the sheer number of duplicate answers on this question is staggering. I wish a moderator could
come and clean them up. I can't vote-to-delete anything that doesn't have a negative score.

Mysticial
Dec 18 '13 at 19:41
Never use == to test whether Strings are the same, unless you enjoy tracking down subtle errors and
studying the intricacies of the Java String interning process. "12"=="1"+2 is false (probably)

Flight Odyssey

comments disabled on deleted / locked posts / reviews

23

active

Linked
214
Java String.equals versus

==
34
Java comparison with ==

of two strings is false?


21
why equals() method

when we have ==
operator?

oldest

strings are equal in


value, what is the best
method?

votes
4

.equals() tests for value equality.


Consequently, if you actually want to test whether two strings have the same value you should use
.equals() (except in a few situations where you can guarantee that two strings with the same value will
be represented by the same object eg: String interning).

Java Does Not Equal (!=)

Not Working?

== tests for reference equality.

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

linux

10
How to compare two

Answers

1743

cloud

Full Stack Engineer


HashCube
Bangalore, India

.hashcode () method, otherwise you will end up with violating equivalence relation b/w equals and
hashcode. For more info refer java doc.

Surendhar

backbone.js

Comparing two identical

strings with == returns


false
7

Why is F + alse not ==

False?

How do I compare strings in Java? - Stack Overflow

== is for testing whether two strings are the same object.

doesn't work in android

// These two have the same value


new String("test").equals("test") // --> true
// ... but they are not the same object
new String("test") == "test" // --> false

if(a == a) not working

Strings in Java : equals vs

==
see more linked questions

// ... neither are these


new String("test") == new String("test") // --> false

Related

// ... but these are because literals are interned by


// the compiler and thus refer to the same object
"test" == "test" // --> true

1261 Read/convert an

InputStream to a String
56 What's wrong with using

// concatenation of string literals happens at compile time,


// also resulting in the same object
"test" == "te" + "st" // --> true

== to compare floats in
Java?
453 Comparing Java enum

members: == or
equals()?

// but .substring() is invoked at runtime, generating distinct objects


"test" == "!test".substring(1) // --> false

2435 How can I check if one

// interned strings can also be recalled by calling .intern()


"test" == "!test".substring(1).intern() // --> true

string contains another


substring in JavaScript?

It is important to note that == is a bit cheaper than equals() (a single reference comparison instead of
a method call), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing
with interned strings) it can present an important performance improvement. However, these situations
are rare.
share

edited Apr 10 at 10:41

community wiki

13 revs, 10 users 47%


Aaron Maenpaa

140 I guess in Java you should say "references" instead of "pointers".

Henrik Paul
11 @Xokas11: compareTo is generally used for sorting.

Michael Myers
38 Just a note equals() exactly Compares this String to another String, BUT equalsIgnoreCase()
Compares this String to another String, ignoring case considerations

Yajli Maclo

667 How to convert string to

int in Java?
0

String issue - Java

-3 Java not saying that two

Strings equal when they


do?
4

Java, pointer equality


and string comparison

Java comparing string

179 Comparing strings with ==

which are declared final


in Java

Java does use pointers, but they are abstracted away to Object References, it was a design decision and
provides a whole level of program safety that you cannot always guarantee with pointers, even with a high
level of understanding of pointers and pointer arithmetic. Structured Data (Struct) I think is coming in
Java8 or may have been pushed back to Java9. Anyways, java is java, with it's lumps and it's pearls. :/

SnakeDoc

10 @SnakeDoc We can say the opposite. Always use equals() unless you have a good reason. What
you call safety is entirely context-dependent. For instance, when comparing passwords to determine
whether the user has entered the right password, it is unsafe to ignore case differences.

Nicolas Barbulesco
show 27 more comments

Hot Network
Questions

SSL3 "POODLE" Vulnerability

Trip Advisor - Train routes

Programming with a Sporadic


Shift Key

Why are airlines against the


transferring of tickets to other
persons?

Did you find this question interesting? Try our newsletter

Sign up for our newsletter and get our top new questions
delivered to your inbox (see an example).

comparison of two Strings

Subscribe

Can't recognize these


handwritten kana (or kanji) in a
text

What is the result of running


`chmod 7` on a file?

== tests object references, .equals() tests the string values.

167

Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make
sure identical in-line strings are actually the same object.
For example:
String fooString1 = new String("foo");
String fooString2 = new String("foo");

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

vCPU performance between 1


or 2 vCPU's

Should Disney princess


movies be avoided?

I'm trying to randomly inject


values in a circular area

How do I compare strings in Java? - Stack Overflow

Problem obtaining a marginal


from the joint distribution

// Evaluates to false
fooString1 == fooString2;

Write a square program that


outputs the number of times it
has been "unrolled"

// Evaluates to true
fooString1.equals(fooString2);

gzip: not sure it has


decompressed the whole file

// Evaluates to true, because Java uses the same object


"bar" == "bar";

Charisma vs. credentials in


academic hiring

But beware of nulls!


== handles null strings fine, but calling .equals() from a null string will cause an exception:
String nullString1 = null;
String nullString2 = null;

What is a "2.5D" environment?

Using a bottle of water as a


resistor

// Evaluates to true
nullString1 == nullString2;

How to (quickly) count the


number of rows in ArcGIS
attribute table?

// Throws an Exception
nullString1.equals(nullString2);
share

edited Jun 3 at 8:18

community wiki

4 revs, 4 users 90%


Whatsit

27 Sometimes it looks as if "==" compares values, -- == do always compare values! (It's just that certain
values are references!)

aioobe

Alas, there is no static method for isNullOrEmpty(), and no custom overloading of operators, which makes
this part of Java clunkier than in C# or Python. And since Java doesn't have extension methods, you can't
write your own utility to extend java.lang.String. Right? Any thoughts on subclassing String, adding that
static utility method, and then always using MyString instead? A static method with two parameters for
doing null-safe comparisons would be nice to have in that subclass too.

J Coombs

1 Groovy makes this a little easier with the safe navigation operator (groovy.codehaus.org/), ?. . That
would convert nullString1?.equals(nullString2); into an entirely null statement. However, it
doesn't help if you have validString?.equals(nullString); -- that still throws an exception.

Charles Wood
add a comment

== compares Object reference

90

What was the inflight


entertainment in the early
seventies?

.equals() compares String value


Sometimes == gives illusions of comparing String values, in following cases
String a="Test";
String b="Test";
if(a==b) ===> true
This is a because when you create any String literal, JVM first searches for that literal in String pool, if it
matches, same reference will be given to that new String, because of this we are getting
(a==b) ===> true
String Pool
b -----------------> "test" <-----------------a
== fails in following case
String a="test";
String b=new String("test");
if (a==b) ===> false
in this case for new String("test") the statement new String will be created in heap that reference will
be given to b , so b will be given reference in heap not in String Pool.
Now a is pointing to String in

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

Is "ps -u" Really a Bad


Syntax?

Alternative expression for "xyz


Nazi"

Discard unsaved changes in


tab if user switches to a
different tab?

Solved to be 7 after arithmetic

How do I force re-evaluation of


a defvar?

Does 1.00000000001 with


an infinite number of 0 in it
exist?

Gatwick airport to London by


Oyster card

How do I compare strings in Java? - Stack Overflow

String pool while b is pointing to String in heap, because of that we are getting
if(a==b) ===> false.
String Pool
"test" <-------------------- a
Heap
"test" <-------------------- b
While .equals() always compares value of String so it gives true in both cases
String a="Test";
String b="Test";
if(a.equals(b)) ===> true
String a="test";
String b=new String("test");
if(a.equals(b)) ===> true
So using .equals() is awalys better.
Hope this will help.
share

edited Jul 19 '13 at 0:04

community wiki

Ganesh

Nice explanation aboout string literals with heap and string pool context.

rohan-patel
Really nice explantions

Null
add a comment

The == operator checks to see if the two strings are exactly the same object.

62

The .equals() method will check if the two strings have the same value.
share

edited Dec 24 '13 at 7:49

community wiki

2 revs, 2 users 67%


Clayton

Generally I strongly recommend apache commons library: commons.apache.org/proper/commonslang/javadocs/api-2.6/org/, java.lang.String)

Marcin Erbel
add a comment

40

String in java are immutable that means whenever you try to change/modify the string you get a new
instance. You cannot change the original string. This has been done so that these string instances can be
cached. A typical program contains a lot of string references and caching these instances can decrease
the memory footprint and increase the performance of the program.
When using == operator for string comparison you are not comparing the contents of the string but are
actually comparing the memory address, if they are both equal it will return true and false otherwise.
Whereas equals in string compares the string contents.
So the question is if all the strings are cached in the system how come == returns false whereas equals
return true. Well this is possible. If you make a new string like String str = new String("Testing")
you end up creating a new string in the cache even if the cache already contains a string having the same
content. In short "MyString" == new String("MyString") will always return false.
Java also talks about the function intern() that can be used on a string to make it part of the cache so
"MyString" == new String("MyString").intern() will return true.
Note: == operator is much faster that equals just because you are comparing two memory addresses, but
you need to be sure that the code isn't creating new String instances in the code otherwise you will
encounter bugs.

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

share

answered Feb 5 '09 at 10:54

community wiki

Faisal Feroz

add a comment

Yea, it's bad...

28

"==" means that your two string references are exactly the same object. You may have heard that this is
the case because Java keeps sort of a literal table (which it does), but that is not always the case. Some
strings are loaded in different ways, constructed from other strings, etc., so you must never assume that
two identical strings are stored in the same location.
Equals does the real comparison for you.
share

answered Feb 4 '09 at 23:20

community wiki

Uri

add a comment

28

String a = new String("foo");


String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true
Make sure you understand why. It's because the == comparison only compares references; the
equals() method does a character-by-character comparison of the contents.
When you call new for a and b , each one gets a new reference that points to the "foo" in the string
table. The references are different, but the content is the same.
share

edited Nov 9 '13 at 12:50

community wiki

duffymo

5 "Make sure you understand why". You answered the question, it would be helpful if you explained why.

Simon Andr Forsberg


add a comment

26

Java is having a String pool under which java manages the memory allocation for the String objects. See
String Pools in java
What happens is when you check(compare) two objects using == operator it compares the address
equality into the string-pool. If two String objects having same address references then it returns true
otherwise false . But if you want to compare the contents of two String objects then you must override
equals method.
equals is actually the method of Object class but is Overridden into the String class and new definition is
given which compares the contents of object.
Example:
stringObjectOne.equals(stringObjectTwo);
But mind it respects the case of String. If you want Case insensitive compare then you must go for
equalsIgnoreCase method of the String class.
Lets See:
String
String
String
String

one
two
three
four

one == two;

=
=
=
=

"HELLO";
"HELLO";
new String("HELLO");
"hello";

// TRUE

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

one == three; // FALSE


one == four; // FALSE
one.equals(two);
one.equals(three);
one.equals(four);
one.equalsIgnoreCase(four);
share

//
//
//
//

TRUE
TRUE
FALSE
TRUE
edited Apr 4 '13 at 8:45

community wiki

Saurabh Agarwal

1 I see that this is a late answer to big question. May I ask what it provides that isn't already mentioned in the
existing answers?

Mysticial

1 @Mysticial he has added equalsIgnoreCase which might be informative for the fresher.

AmitG
at 8:48
add a comment

== compares object references in Java, and that is no exception for String objects.

23

For comparing the actual contents of objects (including String ), one must use the equals
method.
If a comparison of two String objects using == turns out to be true , that is because the String
objects were interned, and the Java Virtual Machine is having multiple references point to the same
instance of String . One should not expect that comparing one String object containing the same
contents as another String object using == to evaluate as true .
share

answered Feb 4 '09 at 23:20

community wiki

coobird

add a comment

19

Yes, == is bad for comparing Strings (any objects really, unless you know they're canonical). == just
compares object references. .equals() tests equality. For Strings, often they'll be the same but as you've
discovered that's not guaranteed.
share

answered Feb 4 '09 at 23:19

community wiki

cletus

add a comment

19

.equals compares the data in a class (assuming the function is implemented).


== compares pointer
locations (location of the object in memory)
== returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance

.equals returns true of two objects contain the same data equals( ) Versus == in Java
That may help you.
share

edited Jun 8 at 10:16

community wiki

2 revs, 2 users 76%


Matt Razza

add a comment

18

== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same
object in the memory.
The equals() method will check if the contents or the states of 2 objects are the same.
Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 strings

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

hold the same text.


Definitely the use of equals() method is recommended.
Don't worry about the performance. Some things to encourage using String.equals() :
1. Implementation of String.equals() first checks for reference equality (using == ), and if the 2
strings are the same by reference, no further calculation is performed!
2. If the 2 string references are not the same, String.equals() will next check the lengths of the
strings. This is also a fast operation because the String class stores the length of the string, no need
to count the characters or code points. If the lengths differ, no further check is performed, we know
they cannot be equal.
3. Only if we got this far will the contents of the 2 strings be actually compared, and this will be a shorthand comparison: not all the characters will be compared, if we find a different character (at the same
position in the 2 strings), no further characters will be checked.
When all is said and done, even if we have guarantee that the strings are interns, using the equals()
method is still not that overhead that one might think, definitely the recommended way. If you want
efficient reference check, then use enums where it is guaranteed by the language specification and
implementation that the same enum value will be the same object (by reference).
share

edited Oct 3 at 7:37

community wiki

4 revs
icza

add a comment

Function:

15

// word-by-word fixed-cut similarity


public static float simple_similarity (String u, String v)
{
String [] a = u.split(" ");
String [] b = v.split(" ");
long correct = 0;
int minLen = Math.min(a.length,b.length);
for (int i=0; i<minLen; i++)
{
for (int j=0; j<Math.min(a[i].size(),b[i].size()); i++)
{
if (a[i][j] == b[i][j])
{
correct++;
}
}
}

return (float)(((double)correct)/Math.max(u.size(),v.size()));

Test:
String a = "This is the first string.";
String b = "this is not 1st string!";
// for exact string comparison, use .equals
boolean exact = a.equals(b);
// For similarity check, there are libraries for this
// Here I'll try a simple example I wrote
float similarity = simple_similarity(a,b);
share

edited Apr 10 '13 at 2:21

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

community wiki

How do I compare strings in Java? - Stack Overflow

Khaled A Khunaifer
add a comment

15

== compares the reference value of objects whereas the equals() method present in the
java.lang.String class compares the contents of the String object (to another object).
share

edited Mar 4 at 20:19

community wiki

3 revs, 3 users 50%


samkit shah

9 not to be nit picky, but the equals() method for String is actually in the String class, not in Object .
The default equals() in Object would not compare that the contents are the same, and in fact just
returns true when the reference is the same.

jschoen
add a comment

I agree with the answer from zacherates.

14

But what you can do is to call intern() on your non-literal strings.


From zacherates example:
// ... but they are not the same object
new String("test") == "test" ==> false
If you intern the non-literal String equality is true
new String("test").intern() == "test" ==> true
share

answered Feb 5 '09 at 8:14

community wiki

pgras

add a comment

13

If you're like me, when I first started using Java, I wanted to use the "==" operator to test whether two
String instances were equal, but for better or worse, that's not the correct way to do it in Java.
In this tutorial I'll demonstrate several different ways to correctly compare Java strings, starting with the
approach I use most of the time. At the end of this Java String comparison tutorial I'll also discuss why the
"==" operator doesn't work when comparing Java strings.
Option 1: Java String comparison with the equals method
Most of the time (maybe 95% of the time) I
compare strings with the equals method of the Java String class, like this:
if (string1.equals(string2))
This String equals method looks at the two Java strings, and if they contain the exact same string of
characters, they are considered equal.
Taking a look at a quick String comparison example with the equals method, if the following test were run,
the two strings would not be considered equal because the characters are not the exactly the same (the
case of the characters is different):
String string1 = "foo";
String string2 = "FOO";
if (string1.equals(string2))
{
// this line will not print because the
// java string equals method returns false:
System.out.println("The two strings are the same.")
}
But, when the two strings contain the exact same string of characters, the equals method will return true,

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

as in this example:
String string1 = "foo";
String string2 = "foo";
// test for equality with the java string equals method
if (string1.equals(string2))
{
// this line WILL print
System.out.println("The two strings are the same.")
}
Option 2: String comparison with the equalsIgnoreCase method
In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase.
When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase
method of the String class, like this:
String string1 = "foo";
String string2 = "FOO";
// java string compare while ignoring case
if (string1.equalsIgnoreCase(string2))
{
// this line WILL print
System.out.println("Ignoring case, the two strings are the same.")
}
Option 3: Java String comparison with the compareTo method
There is also a third, less common way to compare Java strings, and that's with the String class
compareTo method. If the two strings are exactly the same, the compareTo method will return a value of
0 (zero). Here's a quick example of what this String comparison approach looks like:
String string1 = "foo bar";
String string2 = "foo bar";
// java string compare example
if (string1.compareTo(string2) == 0)
{
// this line WILL print
System.out.println("The two strings are the same.")
}
While I'm writing about this concept of equality in Java, it's important to note that the Java language
includes an equals method in the base Java Object class. Whenever you're creating your own objects and
you want to provide a means to see if two instances of your object are "equal", you should override (and
implement) this equals method in your class (in the same way the Java language provides this
equality/comparison behavior in the String equals method).
You may want to have a look at this ==, .equals(), compareTo(), and compare()
share

answered Jun 11 '13 at 9:17

community wiki

Mohamed E. ManSour

1 for string literals Like String string1 = "foo bar"; String string2 = "foo bar"; you can directly use == operator to
test content equality

sunny
add a comment

10

always == operator meant for object reference comparison,where as String class .equals() method is
overridden for content comparison
String s1= new String("abc");
String s2= new String("abc");
System.out.println(s1 == s2);//It prints false(reference comparison)
System.out.println(s1.equals(s2));//It prints true (content comparison)

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

share

edited Apr 30 '13 at 6:21

community wiki

sham.y

add a comment

I think that when you define a String you defines an object. So you need to use .equals(). When you use
primitive data types you use == but with String (and any object) you must use .equals()
share

answered Jan 8 '13 at 4:37

community wiki

fabricioflores

Also note that == doesn't work for char[]

Khaled A Khunaifer
add a comment

== operator check if the two references point to the same object or not.
.equals() check for the actual string content(value).
Note that .equals() method belongs to Class Object(Super class of all classes). You need to override it as
per you class requirement but for String it is already implemented and it checks whether two string have
same value or not.
Case1)
String s1 = "StackOverflow";
String s2 = "StackOverflow";
s1 == s2;
//true
s1.equals(s2); //true
Reason: String literals created without null are stores in String pool in permgen
area of heap. So both s1 and s2 point to same object in the pool.
Case2)
String s1 = new String("StackOverflow");
String s2 = new String("StackOverflow");
s1 == s2;
//false
s1.equals(s2); //true
Reason: If you create String object using new keyword separate space is allocated to
it on heap.
share

edited Aug 19 '13 at 11:27

community wiki

Aniket Thakur

add a comment

equals() method is present in the java.lang.Object class and it is expected to check for the
equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is
expected to check the actual object instances are same or not.
Example
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

Now you will get the FALSE as output because both str1 and str2 are pointing to two different
objects even though both of them share the same string content. It is because of new String()
everytime a new object is created.
share

answered Dec 18 '13 at 19:26

community wiki

Rakesh KR

add a comment

All objects are guaranteed to have a .equals method since Object contains a method equals() that returns
a boolean. It is the subclasses jobs to override this method if a further defining definition is required.
Without it(i.e. using ==) only memory addresses are checked between two objects for equality. String
overrides this .equals method and instead of using the memory address it returns the comparison of
strings at the character level for equality.
A key note is that strings are stored in one lump pool so once a string is created it is forever stored in a
program at the same address. Strings do not change, they are immutable. This is why it is a bad idea to
use regular string concatenation if you have a serious of amount of string processing to do. Instead you
would use the StringBuilder classes provided. Remeber the pointers to this string can change and if you
were interested to see if two pointers were the same == would be a fine way to go. Strings themselves do
not.
share

answered Sep 3 '12 at 4:55

community wiki

James

1 "once a string is created it is forever stored in a program at the same address" - This is flat-out wrong. Only
compile-time constant string expressions (possibly involving final String variables) and strings that your
program explicitly interns are stored in what you call a "lump pool". All other String objects are subject to
garbage collection once there are no more live references to them, just like any other type of object. Also,
while immutability is required for the whole interning mechanism to work, it's otherwise irrelevant to this.

Ted Hopp
add a comment

In Java, when the == operator is used to compare 2 objects, it checks to see if the objects refer to the
same place in memory. In other words, it checks to see if the 2 object names are basically references to
the same memory location.
The Java String class actually overrides the default equals() implementation in the Object class and it
overrides the method so that it checks only the values of the strings, not their locations in memory.
This
means that if you call the equals() method to compare 2 String objects, then as long as the actual
sequence of characters is equal, both objects are considered equal.
The == operator checks if the two strings are exactly the same object.
The .equals() method check if the two strings have the same value.
share

edited Aug 4 at 0:48

community wiki

3 revs, 2 users 88%


Lijo

unless one of them is null, since s.equals(s2) will crash if s is null, causing the comparison to fail. Of course,
this doesn't really contradict the answer; it's just a caveat.

J Coombs
add a comment

You can also use compareTo() method to compare two Strings. If the compareTo result is 0, then the
two strings are equal, otherwise the strings being compared are not equal.
The == compares the references and does not compare the actual strings. If you did create every string
using new String(somestring).intern() then you can use the == operator to compare two strings,
otherwise equals() or compareTo methods can only be used.

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

How do I compare strings in Java? - Stack Overflow

share

edited Oct 6 at 9:20

community wiki

2 revs, 2 users 60%


Liarez

add a comment

protected by Community Jan 31 at 5:20

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now
requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged java string
equality or ask your own question.

tour
help
badges
blog
chat
data
legal
privacy policy
work here
advertising info
mobile
contact us
feedback
TECHNOLOGY
Stack Overflow

Programmers

Server Fault

Unix & Linux

Super User

Ask Different (Apple)

Web Applications

WordPress
Development

Ask Ubuntu
Webmasters

Geographic
Information Systems

Game Development

Electrical Engineering

TeX - LaTeX

Android Enthusiasts
Information Security

Database
Administrators

LIFE / ARTS

CULTURE /
RECREATION

SCIENCE

OTHER

Photography

English Language &


Usage

Mathematics

Stack Apps

Cross Validated (stats)

Meta Stack Exchange


Area 51

Drupal Answers

Science Fiction &


Fantasy

SharePoint

Graphic Design

Mi Yodeya (Judaism)

Theoretical Computer
Science

User Experience

Seasoned Advice
(cooking)

Travel

Physics

Christianity

MathOverflow

Arqade (gaming)

more (7)

Mathematica
Salesforce

more (13)

Home Improvement

Skeptics

Personal Finance &


Money

Bicycles

Academia

Role-playing Games

more (10)

more (21)

site design / logo 2014 stack exchange inc; user contributions licensed under cc by-sa 3.0 with attribution required

rev 2014.10.18.1953

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java[18-10-2014 16:16:39]

Stack Overflow
Careers

You might also like