java

How to Compare Two Strings in Java

In this tutorial, we are going to see how to compare two strings in Java in three ways.

  • By using the equals() method
  • By using the compareTo() method
  • By using the == operator

 

Method 1: Compare Two Strings Using the equals() method

The method equals() compares the contents of a string. It compares the values for equality.

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

Output:

true

 

 

Method 2: Compare Two Strings Using the compareTo() method

The compareTo() method compares values and returns an integer value that describes whether the first string is less than, equal to, or greater than the second string.

Suppose that str1 and str2 are two String. If:

  • str1 == str2: the result will be 0
  • str1 > str2: the result will be a positive value
  • str1 < str2: the result will be a negative value
public class Main {
	public static void main(String args[]){
		String str1 = "Java";
		String str2 = "Java";
		System.out.println(str1.compareTo(str2));
	}
}

Output:

0

 

 

Method 3: Compare Two Strings Using the == operator

Warning: The == operator compares the references and not the values.

public class Main {
	public static void main(String args[]){
		String str1 = "Java";
		String str2 = "Java";
		System.out.println(str1 == str2);
	}
}

Output:

true
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *