java.lang.ClassCastException is a Runtime Exception in Java and hence the Java Compiler will not check for it.
Below is an example of code that generate a ClassCastException:
import java.util.ArrayList;
import java.util.List;
public class ClassCastExceptionExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add("Hello");
String str = (String) list.get(0); //ClassCastException
}
}
Here we have a list as a raw type so we can add Objects of any types without any issues, but it becomes really difficult to know what elements will the list return, this if you try to cast the element incorrectly we get a ClassCastExceptionExample at runtime.
Fix or ClassCastExceptionExample
It is always recommended to make use of Java Generics that were introduced with Java 1.5 instead of raw types. By using Generics you add type safety to your code and thus you do not need to do casting.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
//list.add(10); //incompatible types: int cannot be converted to java.lang.String
list.add("Hello");
String str = (String) list.get(0);
}
Instead you will get a Complication Error saying "incompatible types: int cannot be converted to java.lang.String". Thus you can avoid runtime exceptions.
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- [fix] docker: Error response from daemon: dial unix docker.raw.sock: connect: no such file or directory. - Docker
- Todays Apple Spring Loaded Event Live Updates - Apple
- How to install Spring CLI using Mac Terminal - HowTos
- Java 8: Predicate negate() default Function Example - Java
- How to Open a New Notebook in Google Colab - Google
- Share Image and Text on Instagram from Android App using Share Dialog - Android
- ls command sort by file size [Linix/UNIX/macOS/bash] - Linux
- Align left align text in Bootstrap - Bootstrap