Java Program to Compare Strings

In this program, you’ll learn to compare two strings in Java.

Example 1: Compare two strings

  1. public class CompareStrings {
  2. public static void main(String[] args) {
  3. String style = "Bold";
  4. String style2 = "Bold";
  5. if(style == style2)
  6. System.out.println("Equal");
  7. else
  8. System.out.println("Not Equal");
  9. }
  10. }

When you run the program, the output will be:

Equal

In the above program, we’ve two strings style and style2. We simply use equality operator (==) to compare the two strings, which compares the value Bold to Bold and prints Equal.


Example 2: Compare two strings using equals()

  1. public class CompareStrings {
  2. public static void main(String[] args) {
  3. String style = new String("Bold");
  4. String style2 = new String("Bold");
  5. if(style.equals(style2))
  6. System.out.println("Equal");
  7. else
  8. System.out.println("Not Equal");
  9. }
  10. }

When you run the program, the output will be:

Equal

In the above program, we have two strings style and style2 both containing the same world Bold.

However, we’ve used String constructor to create the strings. To compare these strings in Java, we need to use the equals() method of the string.

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.

On the other hand, equals() method compares whether the value of the strings are equal, and not the object itself.

If you instead change the program to use equality operator, you’ll get Not Equal as shown in the program below.


Example 3: Compare two string objects using == (Doesn’t work)

  1. public class CompareStrings {
  2. public static void main(String[] args) {
  3. String style = new String("Bold");
  4. String style2 = new String("Bold");
  5. if(style == style2)
  6. System.out.println("Equal");
  7. else
  8. System.out.println("Not Equal");
  9. }
  10. }

When you run the program, the output will be:

Not Equal

Example 4: Different ways to compare two strings

Here are the string comparison which are possible in Java.

  1. public class CompareStrings {
  2. public static void main(String[] args) {
  3. String style = new String("Bold");
  4. String style2 = new String("Bold");
  5. boolean result = style.equals("Bold"); // true
  6. System.out.println(result);
  7. result = style2 == "Bold"; // false
  8. System.out.println(result);
  9. result = style == style2; // false
  10. System.out.println(result);
  11. result = "Bold" == "Bold"; // true
  12. System.out.println(result);
  13. }
  14. }

When you run the program, the output will be:

true
false
false
true