Net-informations.com
SiteMap  | About    

String Comparison in Java

Java String class has a number of methods for comparing strings. The following are the some of the frequently used methods:

  1. == operator
  2. equals() method
  3. equalsIgnoreCase
  4. compareTo() method

Using == operator

The == operator tests for reference , not values , equality that means check whether they are the same object. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false.

Here, the literals are interned by the compiler and thus refer to the same object

Above two String variables point to the different object in memory

Above two String variables point to the different object in memory

It is important to note that the '==' operator does not compare the content inside the String objects. It only compares the references the 2 Strings are pointing to.

Example

Output

String equals() method

Java String equals() method check the original content (i.e. the same values) of the string. The equal() method returns true if the parameter is a String object that represents contain the exact same string of characters as this object.

If you want to test whether two strings have the same value you will probably want to use Objects.equals() .

Example

Output

String equalsIgnoreCase

Java String equalsIgnoreCase Compares two strings lexicographically , ignoring differences in case. Returns true if and only if the argument is a String object that represents the same sequence of characters as this object. When you want to test your strings for equality in case-insensitive manner, you can use the equalsIgnoreCase method of the String class.

Example

Output

String compareTo() method

The compareTo method is used when we need to determine the order of Strings lexicographically . It compares char values similar to the equals method. If the two strings are exactly the same, the compareTo method will return a value of 0 (result is = 0). It returns a positive (result is > 0) integer if the first String object follows the second string. The compareTo method returns a negative (result is < 0) integer if the first String object precedes the second string.

Example

Output







net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.