When we are trying to compare the values of two strings to be equal or not, better to use the equals() method. If you want to check for equality with case insensitivity, then you can use the equalsIgnoreCase() method.
The output from the program is shown here:
In this source code example, we will see string comparison using equals() and equalsIgnoreCase() methods.
Java String Compare Using equals() Method
package net.javaguides.corejava;
public class StringExample {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("ABC");
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
System.out.println(s1.equalsIgnoreCase(s3)); // true
}
}
The output from the program is shown here:
true
false
true
Here is one more example to compare two strings in Java:// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
}
}
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
Comments
Post a Comment