Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a String?
3.
Comparing Strings
4.
== operator
4.1.
Example
5.
compareTo() method
5.1.
Syntax
5.2.
Example
6.
equals() method
6.1.
Syntax
6.2.
Example
7.
equalsIgnoreCase() method
7.1.
Syntax
7.2.
Example
8.
Objects.equals() method
8.1.
Syntax
8.2.
Example
9.
Frequently Asked Questions
9.1.
Are Strings in Java mutable?
9.2.
Which method can be used to compare strings with null values?
9.3.
What is the equals() method?
9.4.
Which method compares the string ignoring the case of the letters?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

String Comparison

Author Nagendra
0 upvote

Introduction

Java is one of the most popular programming languages. Learning Java reinforces essential computer science principles while also providing access to a wide range of professional options.
A string is a collection of characters in Java, while a char is a single number used to hold variables. By implementing strings as built-in objects, Java can provide a full set of features that facilitate string manipulation. It offers, among other things, techniques for comparing two strings, searching for a substring, and concatenating two strings. This blog discusses the many methods for string comparison.

Without further ado, let's get started.

Recommended Topic-  Iteration Statements in Java, and Duck Number in Java.

What is a String?

The string is an immutable class, which means that its object can't be changed after it's been formed, although it can reference other objects. Immutable objects are thread-safe in multithreading environments because many threads cannot change the state of the object. Arrays are unchangeable in Java, and strings are as well. In any instance, if a string is modified, a whole new string is created.

Some facts about Strings are : 

  • The index of strings starts from 0.
  • String objects are immutable.

Take a look at the example below to see how to convert all letters in a string to uppercase.

Code

public class Upper_Case {
   public static void main(String args[]) {
      String s = "string comparison";
    /*s.setCharAt(1,”A”); This will result in error as String is immutable*/
      System.out.println(s.toUpperCase());
   }
}

Output

STRING COMPARISON

Explanation:

The toUpperCase() is a String class predefined function that returns all letters to uppercase.

Let's continue by learning different ways to compare strings.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Comparing Strings

A number of methods for string comparison are available in the Java String class. The following are a few of the most commonly utilised methods:

  • == operator
  • compareTo() method
  • equals() method
  • equalsIgnoreCase() method
  • Objects.equals() method

Let's get into each method in detail.

== operator

The == operator checks for reference equality rather than value equality that is, whether they are the same object. The string comparison returns true if two String variables point to the same memory object. Otherwise, the string comparison returns false.

Take a look at the example below to see how the == operator functions.

Example

With the help of the following code snippet, we will see the working of == operator.

Code

class string_comparison
{  
 public static void main(String args[])
 {  
   String s1="String";  
   String s2="String";  
   String s3=new String("String");  
   System.out.println(s1==s2);//returns true because both the objects refer to same instance
   System.out.println(s1==s3);// returns false because s3 refers to nonpool instance )
 }  
}  

Output

true
false

Explanation

The first statement returns true because the compiler has interned the literals, so they all refer to the same object.
The second statement returns false because each of the two string variables points to a different memory object.

Also see, Swap Function in Java

compareTo() method

When we need to identify the lexicographic order of Strings, we use the compareTo() method. It compares char values in the same way that equals() does.

The return value of the function is determined as :

  • It will return a value of 0 if the two strings are identical. 
  • If the first String object comes after the second string (string1 > string2), it returns a positive integer. 
  • If the first String object predates the second string(string1 < string2), it returns a negative integer.

Syntax

The compareTo() method has the following syntax:

public int compareTo(String s)

Example

With the help of the following code snippet, we will see the working of compareTo() method.

Code

class String_comparison{  
 public static void main(String args[]){  
   String s1="String";  
   String s2="String";  
   String s3="Comparison";  
   System.out.println(s1.compareTo(s2));//0  
   System.out.println(s1.compareTo(s3));//16(because s1>s3)  
   System.out.println(s3.compareTo(s1));//-16(because s3 < s1 )  
 }  
}  

Output

0
16
-16

Explanation

The first statement prints 0 because the two strings are identical.
The second statement returns a positive value as String s1 > String s3.
The third statement returns a negative value as String s3 < String s1.

You can also read about the topic of Java Destructor and Hashcode Method in Java.

equals() method

The equals() function in Java compares two provided strings depending on their data. It returns true if the contents of both strings are identical. It returns false if any character does not match.

Syntax

The equals() method has the following syntax:

public boolean equals(object a)

Example

With the help of the following code snippet, we will see the working of equals() method.

Code

class String_comparison{  
 public static void main(String args[])
 {  
   String s1="String";  
   String s2="String";  
   String s3="Comparison";  
   System.out.println(s1.equals(s2));//true  
   System.out.println(s1.equals(s3));//false because both are different strings  
 }  
}  

Output

true
false

Explanation

The first statement prints true because the two strings are identical.
The second statement prints false because both are different strings.

equalsIgnoreCase() method

The equalsIgnoreCase() compares two strings lexicographically, disregarding case differences. It returns true if the contents of both strings are identical regardless of the string's case (lower or upper); otherwise, it returns false.

Syntax

The equalsIgnoreCase() method has the following syntax:

public boolean equalsIgnoreCase(String s)

Example

With the help of the following code snippet, we will see the working of equals() method.

Code

class String_comparison{  
 public static void main(String args[]){  
   String s1="String";  
   String s2="STRING";  
   String s3="Comparison";  
   System.out.println(s1.equals(s2));//true  
   System.out.println(s1.equals(s3));//false because both are different strings  
 }  
}  

Output

true
false

Explanation

The first statement prints true because the two strings are identical, ignoring the case.
The second statement prints false because both are different strings.

Objects.equals() method

If the arguments are equal, this method returns true; otherwise, it returns false. As a result, true is returned if both arguments are null, and false is returned if only one argument is null. Otherwise, the equals() method is used to determine equality.

Syntax

The Object.equals() method has the following syntax:

public static boolean equals(Object a , Object b)

Example

With the help of the following code snippet, we will see the working of equals() method.

Code

import java.util.*;
class String_comparison{  
 public static void main(String args[]){  
   String s1="String";  
   String s2="String";  
   String s3="Comparison";  
   System.out.println(Objects.equals(s1, s2));//true
   System.out.println(Objects.equals(null, null));//true
   System.out.println(Objects.equals(s1, s3));//false because both are different strings  
 }  
}  

Output

true
true
false

 

Try it on java compiler.

Explanation

The first statement prints true because the two strings are identical.
The second statement prints true because both are null strings having no data (identical).
The third statement prints false because both are different strings.

Must Read Conditional Statements in Java

Frequently Asked Questions

Are Strings in Java mutable?

No, Strings in Java are immutable.

Which method can be used to compare strings with null values?

The Objects.equals() method can be used to compare strings with null values.

What is the equals() method?

The equals() method is used when two strings are compared; it returns true if they are equal and false if they are not.

Which method compares the string ignoring the case of the letters?

The equalsIgnoreCase() method compares the string ignoring the case of the letters.

Conclusion

In this article, we have extensively discussed the different methods used for String comparison, along with their syntax and examples.
We hope that this blog has helped you enhance your knowledge regarding String comparison, and if you would like to learn more, check out our articles on Java. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavascript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Also check out - String Interview Questions In Java
 

Recommended problems -

Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Live masterclass