Java Tips String comparison

A Java tips during String comparison. We must use .equals() instead of ==.

Using ==, it checks for reference equality.

Using .equals(), it checks for the value equality.

For example,

String a = "YongHao";
String b = "YongHao";
System.out.println(a == b);

OK, if you run above code, you will see true true.


String a = new String("YongHao");
String b = new String("YongHao");
System.out.println(a == b);

You will get false true.

In first case, a = “YongHao” and b = “YongHao”, as Java will perform String interning by default. String interning meant create a single copy of String and stored in String Constant Pool. So a and b will point to same object in this case, so does a == b is true. String constant pool is fixed size. The reason to create String constant pool is to save space and memory. Note, this is not always guarantee String interning will happens, this is based on JVM setting.

In second case, new String(“YongHao”) guarantee always new object, a and b points to different objects, so a == b return false, but a.equals(b) return true, which is expected.

Conclusion, in Java, when compare String, KEEP IN MIND, always use .equals()

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.