In order to compare Strings for equality, you should use the String object’s [equals](<https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equals-java.lang.Object->)
or [equalsIgnoreCase](<https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String->)
methods.
For example, the following snippet will determine if the two instances of [String](<https://docs.oracle.com/javase/7/docs/api/java/lang/String.html>)
are equal on all characters:
String firstString = "Test123";
String secondString = "Test" + 123;
if (firstString.equals(secondString)) {
// Both Strings have the same content.
}
This example will compare them, independent of their case:
String firstString = "Test123";
String secondString = "TEST123";
if (firstString.equalsIgnoreCase(secondString)) {
// Both Strings are equal, ignoring the case of the individual characters.
}
Note that equalsIgnoreCase
does not let you specify a Locale
. For instance, if you compare the two words "Taki"
and "TAKI"
in English they are equal; however, in Turkish they are different (in Turkish, the lowercase I
is ı
). For cases like this, converting both strings to lowercase (or uppercase) with Locale
and then comparing with equals
is the solution.
String firstString = "Taki";
String secondString = "TAKI";
System.out.println(firstString.equalsIgnoreCase(secondString)); //prints true
Locale locale = Locale.forLanguageTag("tr-TR");
System.out.println(firstString.toLowerCase(locale).equals(
secondString.toLowerCase(locale))); //prints false
Unless you can guarantee that all strings have been interned (see below), you should not use the ==
or !=
operators to compare Strings. These operators actually test references, and since multiple String
objects can represent the same String, this is liable to give the wrong answer.
Instead, use the String.equals(Object)
method, which will compare the String objects based on their values. For a detailed explanation, please refer to http://stackoverflow.com/documentation/java/4388/java-pitfalls/16290/pitfall-using-to-compare-strings.
As of Java 1.7, it is possible to compare a String variable to literals in a switch
statement. Make sure that the String is not null, otherwise it will always throw a [NullPointerException](<http://stackoverflow.com/documentation/java/1003/nullpointerexception#t=201608020755368222531>)
. Values are compared using String.equals
, i.e. case sensitive.
String stringToSwitch = "A";
switch (stringToSwitch) {
case "a":
System.out.println("a");
break;
case "A":
System.out.println("A"); //the code goes here
break;
case "B":
System.out.println("B");
break;
default:
break;
}