Quick Reach
Java string comparison
Java provides a few methods by which strings can be compared. The methods are:
- Using equals method
- Using compareTo method
Each of these methods explained below with example.
String comparison by equals() method
The java String class method equals() is used to compare two strings whether two are the same or not.
A few main points about equals method:
- The equal method is used to compare two strings
- In equals method strings are compares as case sensitive i.e. “Java” and “java” are different
- The return result is True is strings are same
- The return result will be false if strings are not same
Syntax of equals method
The syntax of equals method is:
Strex.equals(Strex2)
Where Strex and Strex2 are two strings being compared.
Example of using equals method in java
The example below uses equals method that compares two strings. Total three string objects are used and compared in two Boolean variables with equals method. See the result below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class string_example {
public static void main(String []args) {
String Strex1 = "This is string tutorial";
String strex2 = "This is String tutorial";
String strex3 = "This is string tutorial";
boolean a,b;
a = Strex1.equals(strex2);
b = Strex1.equals(strex3);
System.out.println("String 1 and 2 are equal? " + a);
System.out.println("String 1 and 2 are equal? " + b);
}
}
|
See graphic of above example
The output will be:
String 1 and 2 are equal? false
String 1 and 2 are equal? True
The first result is false as ‘s’ is small in first string.
String comparison by compareTo() method
The compareTo() method also takes two strings to be compared however unlike equals() method it returns an int value.
- If two strings are equal the return result will be 0.
- If string one is greater than string two, the return result will be positive.
- If string one is less than string two the returned result will be negative.
Example of using compareTo method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class string_example {
public static void main(String []args) {
String strex1 = "Java";
String strex2 = "Java";
String strex3 = "Tutorial";
int a,b,c;
a = strex1.compareTo(strex2);
b = strex3.compareTo(strex1);
c = strex1.compareTo(strex3);
System.out.println("Returned value: " + a);
System.out.println("Returned value: " + b);
System.out.println("Returned value: " + c);
}
}
|
See graphic of above example
The output will be:
Returned value: 0
Returned value: 10
Returned value: -10
Also see Java Strings
Leave A Comment?