Java String equals() method explained
Syntax of equals() method
public boolean equals(Object anObject) {}
here, the Object inside the parameter, represents another string to be compared simply.
Example 01 of equals() method
public class Equals {
public static void main(String[] args)
{
String s1 = "hello";
String s2 = "bello";
System.out.println(s1.equals(s2));
}
}
Output:
false
here, the strings "hello" and "bello" are not equal so it has returned false checkout the compareTo() method to compare two strings lexicographically.
Imp.note: here, the string class overrides the equals method present inside the Object class.
Why to use equals() instead of (==) to compare two strings
Because by comparing two strings using (==) the reference to the object is actually checked for example here the string object s1 points to the string "hello" inside the string constant pool and the string object s2 points to the string "bello" inside the string constant pool so it will also print false because both the object refer to the different strings and we use equals() method to compare the content of the string.
Example of compare strings using (==) operator
public class Equals {
public static void main(String[] args)
{
String s1 = "hello";
String s2 = "hello";
System.out.println(s1==s2);//also prints false
//because both objects refer to the different strings
//inside the string constant pool
String s3 = "jack";
String s4 = "jack";
System.out.println(s3==s4);
//it will prints true because both the objects
//refer to the same string inside the string
//constant pool
}
}
output:
true
true
To know more about various operators in Java refer to operators in Java.
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.