Side-by-side comparison of ClassCastException and NullPointerException — understand the differences, causes, and fixes.
ClassCastExceptionAn object is cast to a type that it is not an instance of.
The runtime type of the object is not compatible with the target type in the cast. This often occurs when downcasting from a superclass or when collections contain mixed types.
Use instanceof to check the type before casting. Use generics to ensure type safety at compile time. Review the class hierarchy to ensure the cast is valid.
NullPointerExceptionA null reference is used where an object is required.
A method is called or a field is accessed on a reference that is null. This is one of the most common Java exceptions. It occurs when objects are not properly initialized, returned as null from methods, or when collections contain null elements.
Add null checks before accessing objects. Use Optional'<'T> to represent values that may be absent. Initialize objects properly before use. Use Objects.requireNonNull() for fail-fast null detection.