CodesJava

Easy learning with example program codes

ClassCastException at runtime test


Java generics runtime type checking : Let us see the ClassCastException at runtime test in generics with the below example.

ClassCastException at run time test example:

GenericsTest.java

import java.util.ArrayList;
import java.util.List;
 
/**
 * This class is used to show the 
 * ClassCastException at runtime test.
 * @author codesjava
 */
public class GenericsTest {
	public static void main(String args[]){
		//Arraylist without generics.
		List list1 = new ArrayList();
		list1.add("Roxy");
		list1.add("Sandy");
		list1.add(new Integer(6));
		try{
			//Retrieve and print list elements.
			for(Object obj : list1){
				//ClassCastException at runtime when 
				//try to cast an integer to string.
		                String str=(String) obj;
		                System.out.println(str);
			}
		}catch(ClassCastException e){
			System.out.println();
			System.out.println();
			e.printStackTrace();
		}
 
 
		//Arraylist with generics.	
		List list2 = new ArrayList();
		list2.add("Roxy");
		list2.add("Sandy");
		list2.add("Sunil");
 
		//Retrieve and print list elements.
		for(String str : list2){
			//No ClassCastException at runtime 
			//because casting is not required.
	                System.out.println(str);
		}
 
	}
}

Output:

Roxy
Sandy
java.lang.ClassCastException: 
java.lang.Integer cannot be cast to java.lang.String
Roxy
Sandy
Sunil
at com.codesjava.business.GenericsTest.main
(GenericsTest.java:23)

Download this example.
 
Next Topic: Wildcard in generics.
Previous Topic: Compile time checking test.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki