EN
Java - compare strings
3 points
One of the most common problem that affects new Java Developers is how to compare two String
objects. They try to compare strings with ==
operator what makes only reference comparision - not values. To solve this problem equals method should be used. This article explains how to compare two strings.
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
5
String a = "text 1";
6
String b = "text 1";
7
String c = "text 2";
8
9
// CORRECT WAY OF VALUES COMPARISON:
10
11
System.out.println(a.equals(b)); // true
12
System.out.println(a.equals(c)); // false
13
14
// good practice because of literal on left site
15
// NullPoiterException will not occur if a or c variables will be null
16
System.out.println("text 1".equals(a)); // true
17
System.out.println("text 1".equals(c)); // false
18
19
System.out.println("text 1".equals("text 1")); // true
20
System.out.println("text 2".equals("text 1")); // false
21
22
// BAD PRACTICE BECAUSE OF VARIABLE ON LEFT SITE AND LITERAL ON RIGHT SITE:
23
24
// possible NullPoiterException if a or c variable will be null
25
System.out.println(a.equals("text 1")); // true
26
System.out.println(c.equals("text 1")); // false
27
}
28
}
29
Note: this approach is available sice java 1.7.
Output:
xxxxxxxxxx
1
true
2
false
3
true
4
false
5
true
6
false
7
true
8
false
xxxxxxxxxx
1
import java.util.Objects;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
String a = "text 1";
8
String b = "text 1";
9
String c = "text 2";
10
11
System.out.println(Objects.equals(a, b)); // true
12
System.out.println(Objects.equals(a, c)); // false
13
System.out.println(Objects.equals(b, a)); // true
14
System.out.println(Objects.equals(c, a)); // false
15
16
System.out.println(Objects.equals(a, "text 1")); // true
17
System.out.println(Objects.equals("text 1", b)); // true
18
19
System.out.println(Objects.equals("text 1", "text 1")); // true
20
System.out.println(Objects.equals("text 1", "text 2")); // false
21
}
22
}
Output:
xxxxxxxxxx
1
true
2
false
3
true
4
false
5
true
6
true
7
true
8
false
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
5
String a = "text 1";
6
String b = "text 1";
7
String c = "text 2";
8
9
// INCORRECT WAY OF VALUES COMPARISON:
10
11
// this examples return true because of reference to same object in memory
12
System.out.println(a == b); // true
13
System.out.println("text 1" == "text 1"); // true
14
}
15
}
Output:
xxxxxxxxxx
1
true
2
true
Note: for all
"text 1"
occurrences java uses same object in memory what caused true result during references comparison with==
operator.