How to compare two Strings in Java using equals() Method?

The Java String class provides several methods to compare the content of the two Strings. We can use equals() method to compare the content of the two strings. It returns true, if the content of the two Strings is the same otherwise it returns false. The equals() method by default check the content including case also i.e. The comparison is case sensitive. If the comparison is case insensitive it returns false. We can discuss the other way to compare the two strings in our next tutorials. Here, we can discuss only the equals() method.

Syntax: The syntax of the equals() method of String class is given below:

boolean equals(Object obj) 
Here, obj is the String object being compared with the invoking String object.


Example of compare two Strings by equals() Method

The simple way to compare the two string is by using the equals() method. By default, it checks the content including also case also. Let's see the example.

class StringCompare{
	public static void main(String args[]){
		String str1 = "Javastudypoint";
		String str2 = new String("Java");
		String str3 = new String("Javastudypoint");
		String str4 = "Java";
		System.out.println(str1.equals(str3)); //true
		System.out.println(str2.equals(str4)); //true
		System.out.println(str1.equals(str2)); //false
		
	}
}

Output:
compare two Strings in Java using equals() Method?

How to compare two Strings in Java using equals() Method? How to compare two Strings in Java using equals() Method? Reviewed by Prashant Srivastava on January 03, 2020 Rating: 5

No comments:

Powered by Blogger.