dagblog.
← Archive

Comparing strings in Java


Many people who are new to Java have trouble with the meaning of the comparison operator
 ==. The confusion comes from the fact that Java has objects as well as primitive 
 data types. The meaning of == differs for primitives, where it compares values, and 
 for objects, where it compares references instead of values. Objects usually provide a method called
 equals that compares one object with another. Consider these examples 
 for primitive types and for objects.

int foo = 1;
int hoo = 1;
System.out.println(foo == hoo); //true - rovno
Integer foo = new Integer(1);
Integer hoo = new Integer(1);
System.out.println(foo == hoo);
//false - nerovné (porovnáváme dva různé objekty)
System.out.println(foo.equals(hoo));
//true - rovno(porovnáváme hodnoty)

The String type is a special case where the distinction above doesn’t quite hold.

String foo = "nazdarbazar";
String hoo = "nazdarbazar";
System.out.println(foo == hoo);//true!
System.out.println(hoo == ("nazdar"+"bazar"));//true!

If that surprises you and you don’t feel like reading the Java Language Specification, where it’s explained nicely in
 3.10.5 String Literals, 
 I recommend the article (Not So) Stupid Questions:String Equality, which 
 explains the issue very well.

Medium version

Related articles

Related CZ Podcast episodes