×

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

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 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.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.