In Java, a String is a sequence of characters. It is a reference type, meaning it is an object rather than a primitive data type. Strings are immutable, which means that their values cannot be changed after they are created.
There are several ways to compare two strings in Java and we are going to discuss three methods out of them.
1. Using the equals() method: This method compares the contents of the strings and returns a boolean value. For strings, the equals() method is used to compare the characters of two strings to check if they are equal or not.
Java Example Code:
class StringComp { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; String str3 = "World"; if(str1.equals(str2)) { System.out.println("str1 is equal to str2"); } else { System.out.println("str1 is not equal to str2"); } if(str1.equals(str3)) { System.out.println("str1 is equal to str3"); } else { System.out.println("str1 is not equal to str3"); } } }
str1 is equal to str2
str1 is not equal to str3
//Java code to compare two strings class StringComp { public static void main(String[] args) { String str1 = "Apple"; String str2 = "Banana"; int result = str1.compareTo(str2); if (result == 0) { System.out.println("Strings are equal"); } else if (result < 0) { System.out.println("String 1 is less than String 2"); } else { System.out.println("String 1 is greater than String 2"); } } }
String 1 is less than String 2
//Java code to compare two with case strings class StringComp { public static void main(String[] args) { String str1 = "HELLO"; String str2 = "hello"; if (str1.equalsIgnoreCase(str2)) { System.out.println("Strings are equal"); } }
Strings are equal
Why we should not use == for String Comparison in Java?
class StringCompare { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); System.out.println(str1 == str2); // true System.out.println(str1 == str3); // false } }
true false
No comments:
Post a Comment