Skip to content

How to Compare Two Strings in Java

Java String Compare, How to Compare two Strings in Java and difference between == and .equals() for string comparison in Java.

Category
Programming
Covers
Java
Versions & support
About Java →
On this page

Question – How do I compare two strings in the Java programming language?

Java provides two options for string compare. First is == operator and second is .equals() function for Java string compare. This Java tutorial will help you to understand string comparison under Java and difference between == and .equals() for string comparison in Java.

  • Operator == checks for the object reference and matches true if both string belongs to same object.
  • Function .equals() checks for the value of string, it doesn’t matter to which object they belongs.

Compare two Simple Strings

If both strings are simple strings. Java will consider them the same object. So both (== & equals()) will result as true.

Compare two String Objects

If both strings are object strings. Java will consider them different-2 objects. So == operator will return false and equals() function will result in true;

Compare one Simple String with one Object

If one is a simple string and other is an object string. Java will consider them different-2 objects. So == operator will return false and equals() function will result in true;

Compare with NULL String

But in case of comparison with null string == will return false but .equals() function will throw an exception. To avoid null exception we can use Objects.equals(str1, str2) function like following example.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top