This guide will explain different methods to compute if a string is not equal to another string in Java.
- Using the “!=” Operator
- Using the equals() Method
- Using the compareTo() Method
- Using the compareToIgnoreCase() Method
- Using the !equals() Method
Using the “!=” Operator
The “!=” operator is utilized to compare the values of two objects. In Java, strings are objects, and the “!=” operator can be utilized to compute if two strings are not equal. Here is an example:
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
if (str1 != str2) {
System.out.println("The two strings are not equal");
}
}
}
Output
The result of the above code demonstrates that two strings “Hello” and “World” are not equal in the terminal.
Using the equals() Method
This method is utilized to compute the values of two objects. The String class overrides the equals() for computing the values of two strings. Here is an example:
String str2 = "World";
if (!str1.equals(str2)) {
System.out.println("The two strings are not equal");
}
Output
The outcome of the above code confirms that the two strings “Hello” and “World” are not equal.
Using the compareTo() Method
The compareTo() method is utilized to compare the lexicographical order of two strings. When these strings are not equal, it returns a value other than zero. Here is an example:
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
if (str1.compareTo(str2) != 0) {
System.out.println("The two strings are not equal");
}
}}
Output
The output shows that two strings are not equal.
Using the compareToIgnoreCase() Method
The compareToIgnoreCase() method is like the compareTo() method, but it ignores the case of the strings. Here is a code:
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "WORLD";
if (str1.compareToIgnoreCase(str2) != 0) {
System.out.println("The two strings are not equal");
}}
}
Output
The output shows that strings are not equal.
Using the !equals() Method
The !equals() method is utilized to compute whether two strings are equal or not. Here is an example:
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
if (!str1.equals(str2)) {
System.out.println("The two strings are not equal");
}}
}
Output
The output confirms that strings are not equal.
Conclusion
In Java, check if a string is not equal to another string, utilize the “!=” operator, the equals() method, the compareTo() method, or the !equals() method. All these methods are utilized to compute whether one string is equal or not to another string in Java. The selection of the method is based on the specific needs of the program and the desired level of string comparison.