How to compare String in Java

In this post, we are going to compare two String objects in Java. A String is a sequence of characters and a class in Java.

To compare two objects String provides equals() and compareTo() method. The equals() method is used to compare the content of two String object whereas compareTo() compare two strings lexicographically and returns an integer value.

The equals() method returns either true or false. If string objects are equal, it returns true, false otherwise.

There is another way to compare two string objects which is "==" operator and used to compare two memory references of these string objects.

Time for an Example:

Let's create an example to compare two string objects. Here, we are using the equals() method that returns a boolean value.

public class Main {
	public static void main(String[] args){
		String str1 = "Studytonight";
		String str2 = "studytonight";
		boolean val = str1.equals(str2);
		System.out.println(val);
		String str3 = str2;
		val = str2.equals(str3);
		System.out.println(val);
	}
}


false
true

Example: Compare String using equal Operator

In this example, we are comparing two string objects reference by using the == (equal to) operator. It compares whether these two string objects refer to the same string in the memory or not. It returns a boolean either true or false.

public class Main {
	public static void main(String[] args){
		String str1 = "Studytonight";
		String str2 = "studytonight";
		boolean val = str1 == str2;
		System.out.println(val);
		String str3 = str2;
		val = str2 == str3;
		System.out.println(val);
	}
}


false
true

Example: Compare String using compareTo() Method

Let's take one more example to compare strings. Here, we are using the compareTo() method that compares strings on the basis of the Unicode value of each character in the strings. It returns an integer value either positive or negative integer.

public class Main {
	public static void main(String[] args){
		String str1 = "Studytonight";
		String str2 = "studytonight";
		int val = str1.compareTo(str2);
		System.out.println(val);
		String str3 = str2;
		val = str2.compareTo(str3);
		System.out.println(val);
	}
}


-32
0