Online Hibernate Training just in Rs. 1000

One week online training in Hibernate ORM framework. Learn Hibernate Framework and enhance your skills. Best Online Hibernate training at 90% discount. Join Now!! Offer is valid Only for limited Period!!! Online Training

Class Cast Exception Example in java

We are going to describe class cast exception in java. The class cast exception is a converting one data type into another data type. A Class cast exception is a thrown by java. In this example instances to handle class cast exception in a programs..Exceptions are the way in Java to indicate to a calling method that an unnatural condition has occurred.

Ads

Class Cast Exception Example in java

We are going to describe class cast exception in java. The class cast exception is a converting one data type into another data type. A Class cast exception is a thrown by java. In this example instances to handle class cast exception in a programs..Exceptions are the way in Java to indicate to a calling method that an unnatural condition has occurred.

In this example we have to convert one  data type into to another data type  by using castiing.

Vector vector = new Vector():-Creates a new vector.

Object obj = vector.add( a ):-Adds an integer type to the vector and stores in an object

To avoid this exception we have to add Integer a = new Integer((String)obj)

instead of String a = (String)obj.

Example

import java.util.Vector;


public class ClassCast {
	public static void main(String[] args) {
		
		  Vector vector = new Vector();
		  int a = 10;
		  Object obj = vector.add(a);
		  try {
		  String b = (String)obj;
		  vector.add(b);
		 } catch (ClassCastException e) {
		  System.out.println("Class cast exception: " + obj.getClass().getName());
		  e.printStackTrace();
		  }
		  }
		}

output

Download Source Code

Advertisements

Share on Google+Share on Google+

Class Cast Exception Example in java

Posted on: July 8, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Class Cast Exception Example in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads