BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String Compare

Last Updated: June 4, 2024 by Chaitanya Singh | Filed Under: java

In Java, you can compare strings using several different approaches. In this tutorial, we will write various Java programs to compare Strings in java.

  1. Using equal to operator (==)
  2. Using equals() method of String class
  3. compareTo() method of String class
  4. Using compareToIgnoreCase() method
  5. Using contentEquals() method

1. Comparing two strings by using == operator

In the following program we are using equal to operator == to compare two strings. This operator returns true if the string references are equal else it returns false. The program is self explanatory, we have created two strings with the same value, when we compared them using ==, it returned true so the statement inside if statement got executed.

class JavaExample{
  public static void main(String args[]){
    String website="BeginnersBook";
    String website2="BeginnersBook";
    if(website == website2)
      System.out.println("Both Strings are Equal");
    else
      System.out.println("Both Strings are Not Equal");
  }
} 

Output:

Both Strings are Equal

Note: The == operator only compares the String references so if you are creating a new instance of the String class then you should not use == operator. It will return false, even if the string value is same. For this, you should use the equals() method of String class, which we have discussed below.

2. Compare two strings using equals() method

As I have mentioned in the Note in the above section, when we create a new instance of the String, we should not use == operator for comparing these strings as it only compares the references of the Strings. We should use the equals() method for such scenarios.

In the following example we have two strings which are same but we have called String class constructor to create these strings. It created a new instance for both of these strings that is the reason, the == operator returned false, even though the strings are same. However the method returned true as expected.

public class JavaExample {

  public static void main(String[] args) {

    String name = new String("Chaitanya");
    String name2 = new String("Chaitanya");

    System.out.print("Comparison using equals() method: ");
    if(name.equals(name2))
      System.out.println("Strings are Equal");
    else
      System.out.println("Strings are Not Equal");

    System.out.print("Comparison using == operator: ");
    if(name==name2)
      System.out.println("Strings are Equal");
    else
      System.out.println("Strings are Not Equal");
  }
}

Output:

Comparison using equals() method: Strings are Equal
Comparison using == operator: Strings are Not Equal

Example 2: Comparing two strings while ignoring the case

Method equals() is a case-sensitive method, to compare the strings where we need to ignore the case, we can use an alternative method of String class, which is equalsIgnoreCase().

class JavaExample{
  public static void main(String args[]){
    String name="Carl";
    String name2="CARL";

    System.out.println(name.equals(name2));
    System.out.println(name.equalsIgnoreCase(name2));
  }
} 

Output:

false
true

3. Java String compare: using compareTo() method

The compareTo() method compares the strings and returns an int value, if the strings are equal it returns 0 else it returns an int value (negative if string is less than other string, positive if string is greater than other string).

class JavaExample{
  public static void main(String args[]){
    String name="Steve";
    String name2="Steve";

    if(name.compareTo(name2)==0)
      System.out.println("Strings are equal");
    else
      System.out.println("Strings are not equal");
  }
}  

Output:

Strings are equal

4. Using compareToIgnoreCase() Method

This method works exactly same as compareTo() method except that it ignores the case during comparison, which means comparison done by this method is not case-sensitive. I have covered this method in detail here: String compareToIgnoreCase()

String str1 = "Apple";
String str2 = "apple";

int result = str1.compareToIgnoreCase(str2); // 0

5. Using contentEquals() Method

The contentEquals() method of String class compares the string with CharSequence, such as a StringBuilder, StringBuffer, or any other class that implements the CharSequence interface.

  • The comparison is case-sensitive.
  • It returns true if the content matches else it returns false.
  • This method is mostly used when you need to compare a String with sequence-based objects.
public class ContentEqualsExample {
public static void main(String[] args) {
String str = "hello";

StringBuilder sb = new StringBuilder("hello");
StringBuffer sf = new StringBuffer("hello");
CharSequence cs = "hello";

// Comparing String with StringBuilder
boolean result1 = str.contentEquals(sb);
// Output: true
System.out.println("str and sb content equals: " + result1);

// Comparing String with StringBuffer
boolean result2 = str.contentEquals(sf);
// Output: true
System.out.println("str and sf content equals: " + result2);

// Comparing String with CharSequence
boolean result3 = str.contentEquals(cs);
// Output: true
System.out.println("str and cs content equals: " + result3);

// Comparing String with different StringBuilder
StringBuilder sbDifferent = new StringBuilder("world");
boolean result4 = str.contentEquals(sbDifferent);
// Output: false
System.out.println("str and sbDifferent content equals: " + result4);
}
}

To learn more about this method refer: String contentEquals()

Conclusion

We learned three ways to compare java strings. Lets summarise these points:

  • You should use equals() method when you want to compare strings without ignoring case. If you do not want to consider the case for comparison then use equalsIgnoreCase().
  • Use compareTo() method when you do not want true or false as a result of string comparison, this is especially useful when you are sorting the strings in alphabetical order like dictionary.
  • == operator should only be used for string references comparison.
  • Use contentEquals() method when you want to compare string with a char sequence objects such as StringBuilder or StringBuffer.
Main Article: Java String Class

Top Related Articles:

  1. Java Array Declaration and Initialization
  2. how to copy one hashmap content to another hashmap
  3. Java StringBuilder delete()
  4. Unary Operators in Java with Examples
  5. Java StringBuilder append() Method

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap