×

How to Compare Two Strings in Java

How to Compare Two Strings in Java

On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting (by compareTo() method), and authentication (by equals() method). Following are the three ways to compare two strings in Java.

1) By using == operator

2) By using compareTo() method

3) By using equals() method

1) By Using == Operator

The == operator makes the comparison of references, not values. Let’s understand it with the help of the following program.

FileName: StringComparisonExample.java

 public class StringComparisonExample
{ 
// main method
public static void main(String argvs[])
{
// Input strings
String str1 = "Tutorial & Example";
String str2 = "Tutorial & Example";
if(str1 == str2) // true, because st1 & str2 have same reference
{
System.out.println("Strings have the same reference.");
}
else
{
System.out.println("Strings do not have the same reference.");
}
}
} 

Output:

Strings have the same reference.


Explanation: Whenever a string is directly assigned to a variable, an object for the assigned string is implicitly created inside the string pool. When the same string is again assigned to another variable, the JVM (Java Virtual Machine) checks whether the object of the string is already exists in the string pool or not. If object is already present, the JVM returns the reference of the created object; otherwise, it creates an object for the assigned string.

In our example, the exact string is assigned twice. Therefore, both the variables str1 and str2 point to the same object, which is created in the string pool. Hence, the if condition returns true, and its print statement is executed.

Now, consider the following program.

FileName: StringComparisonExample1.java

 public class StringComparisonExample1
{ 
// main method
public static void main(String argvs[])
{
// Input strings
String str1 = "Tutorial & Example"; 
// Creating a string object explicitly
String str2 = new String("Tutorial & Example");
if(str1 == str2)
{
System.out.println("Strings have the same reference.");
}
else // false, because st1 & str2 do not have same reference
{
System.out.println("Strings do not have the same reference.");
}
}
} 

Output:

Strings do not have the same reference.


Explanation: In this example, the str2 variable is holding the reference of the object that is explicitly created. The explicitly created string objects do not reside in the string pool. Therefore, the references held by the variables str1 and str2 are different. Hence, this time the print statement of the else block executes.

2) By Using compareTo() Method

The compareTo() method does the comparison of string lexicographically and renders an integer value that represents whether the first string is either greater than, or less than, or equal to the second string.

Syntax:

public int compareTo (String  anotherStr)

anotherStr: represents the string that is being compared with the current string.

An integer value is returned depending on the current string is greater than, or less than, or equal to the anotherStr string.

FileName: StringComparisonExample2.java

 public class StringComparisonExample2
{ 
// main method
public static void main(String argvs[])
{
// Input strings
String str1 = "Rohit Gurunath Sharma"; 
String str2 = "Mahendra Singh Dhoni";
String str3 = "Mahendra Singh Dhoni";
String str4 = "Mahi";
// compareTo() method is invoked inside the print statements
System.out.println( "The comparison result is: " + str1.compareTo(str2) );
System.out.println( "The comparison result is: " + str2.compareTo(str1) );
System.out.println( "The comparison result is: " + str2.compareTo(str3) );
System.out.println( "The comparison result is: " + str4.compareTo(str3) );
}
} 

Output:

 The comparison result is: 5
The comparison result is: -5
The comparison result is: 0
The comparison result is: 4 

Explanation: The first print statement gives 5 because the ASCII value of ‘R’ is 5 more than ‘M’. The second print statement gives -5 because the ASCII value of ‘M’ is 5 less than ‘R’. The third print statement gives 0 because the contents of str2 and str3 are exactly the same. For the last print statement, the first three letters of the word “Mahi” and “Mahendra” are the same. Therefore, the result is 0 till this point. However, the fourth letter of the word “Mahi”, i.e. the letter i, gets compared with the fourth letter, i.e. the letter e, of the word “Mahendra”. Here, the difference in the ASCII values of the letter is 4, which is being displayed in the output.

3) By Using String.equals() Method

The equals() method compares the content of the strings and returns true value when there is a complete match; otherwise, false value. Note that it overrides the equals() method of the Object class.

Syntax:

 public boolean equals (Object  anObject)
anObject: represents the string that is being compared with the current string.
A boolean value is returned depending on the current string is either equal to the anotherStr string or not.
FileName: StringComparisonExample3.java
public class StringComparisonExample3
{ 
// main method
public static void main(String argvs[])
{
// Input strings
String str1 = "Rohit Gurunath Sharma"; 
String str2 = "Mahendra Singh Dhoni";
String str3 = "Mahendra Singh Dhoni";
String str4 = "mahendra singh dhoni";
// equals() method is invoked inside the print statements
System.out.println( "The comparison result is: " + str1.equals(str2) );
System.out.println( "The comparison result is: " + str2.equals(str1) );
System.out.println( "The comparison result is: " + str2.equals (str3) );
System.out.println( "The comparison result is: " + str3.equals (str4) );
}
} 

Output:

 The comparison result is: false
The comparison result is: false
The comparison result is: true
The comparison result is: false 

Explanation: The first print statement gives 5 because the ASCII value of ‘R’ is 5 more than ‘M’. The second print statement gives -5 because the ASCII value of ‘M’ is 5 less than ‘R’. The third print statement gives 0 because the contents of str2 and str3 are precisely the same.


Related Topics

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.