Exceptions in Java String compareTo() Method
compareTo() method in Java can raise two possible exceptions:
- NullPointerException
- ClassCastException
compareTo() NullPointerException
In Java, the compareTo() method throws a NullPointerException if either of the objects being compared is null. This ensures that you explicitly handle null values and prevents unexpected behavior.
Example:
Java
public class cmp5 { // main method public static void main(String[] args) { String str = null ; // null is invoking the compareTo method. Hence, the NullPointerException // will be raised int no = str.compareTo( "Geeks" ); System.out.println(no); } } |
Output:
Exception in thread "main" java.lang.NullPointerException at cmp5.main(cmp5.java:11)
compareTo() ClassCastException
It is a runtime exception and occurs when two objects of incompatible types are compared in the compareTo() method.
Example:
Java
public class ClassCastExceptionExample { public static void main(String[] args) { Object obj1 = "Hello" ; Object obj2 = 10 ; // Integer object // Explicitly cast obj2 to String to force the exception int comparison = ((String) obj2).compareTo(obj1); System.out.println( "Comparison: " + comparison); } } |
Output:
./ClassCastExceptionExample.java:8: error: incompatible types: Object cannot be converted to String
int comparison = ((String) obj2).compareTo(obj1); // ClassCastException occurs here
Java String compareTo() Method with Examples
Strings in Java are objects that are supported internally by an array only which means contiguous allocation of memory for characters . Please note that strings are immutable in Java which means once we create a String object and assign some values to it, we cannot change the content. However we can create another String object with the modifications that we want.
The String class of Java comprises a lot of methods to execute various operations on strings and we will be focusing on the Java String compareTo() method in this article.