Java String Comparison

Let’s the Java String Comparison. There are many ways to compare the Strings in Java. We can compare string in java on the basis of content and reference.

Note the following ways to compare Strings –

  1. Using equals() method

  2. Using equalsIgnoreCase() method

  3. Using compareTo() method

  4. Using == Operator

 

Java String Comparison

Let’s discuss the methods in details with example.

Using equals() method

Most of the time I use equals() method to compare the Strings. equals() is the method in String class. The String equals() method compares the original content of the string. It compares values of string for equality. It will return the result in true or false only.

Output:

true
false

 

Automation Testing Video Tutorial:

 

Using equalsIgnoreCase() method

In some string comparison tests, you’ll want to ignore whether the strings are uppercase or lowercase. When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase() method of the String class.

Output:

true
true

 

Using compareTo() method

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

Suppose str1 and str2 are two string variables.

  • str1 == str2 : 0
  • str1 > str2   : positive value
  • str1 < str2   : negative value

Output:

0
-32
32

 

Using == Operator

When I first began working with Java I wanted to compare strings with the ==operator, like this:

  If (str1 == str2)”{

  // To do…

  }

but now I don’t recommend this approach to the process. The = = operator compares references not values.

Output:

true
false

0 Comment

Leave a Reply