Quick Reach
The equals string method
The equals method of the String class is used to compare two strings whether two are the same or not.
A few main points about equals Java method are:
- The Java equals method is used to compare two strings.
- In the equals method, strings are compared as case-sensitive as well i.e. “Java” and “java” are different.
- The return result is True if strings are the same.
- The return result will be False if strings are not the same.
Syntax of Java string 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
The example below uses Java equals method that compares two strings. Total three string objects are used and compared in two Boolean variables with the equals method. See the result below:
Experience this online
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);
}
}
|
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 the first string. As such the equals method compares the strings as case-sensitive.
Also see: Java strings
Leave A Comment?