Home Java Javatutorial Class Cast Exception Example in java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Class Cast Exception Example in java

Advertisement
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.

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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 8, 2013

Related Tutorials

Ask Questions?    Discuss: Class Cast Exception Example in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com