|
Abstract |
In the Java™ programming language, all class casts of
non-primitive types are dynamic and are performed at runtime. If a type
conversion cannot be performed when a class is cast, the cast operation
will throw a ClassCastException. |
|
|
Content |
We can learn three very important things from this:
1) A ClassCastException is caused when we do not properly convert the
types when casting a class.
- In the example below, we perform a conversion converting
Turkey into a string. The string is then used in the program.
2) All non-primative type class casts are done at runtime.
3) If we cast a class that can return an error, we need to catch the
error.
In a Java try/catch block, you would catch a ClassCastException.
public class ClassCastExceptionTrial {
public static void main(String[] args)
{
String b = "Turkey";
try
{
String a = (String)b;
// successful conversion
System.out.println(b);
System.out.println(a);
}
catch(ClassCastException e)
{
// failed to carry out test
}
System.out.println(b);
}
}
NOTE! If you try to print out "a" outside of the try catch block, it will
give you an error because "a" does not exist outside of the try catch
block. This is another programming mistake that is made. Further, if you
initialize the variable to something and change it later on, since the
conversion is done at runtime, the variable will take on the new value.
The output for the code above should be:
Turkey
Turkey
Turkey |
|
|
|
Cross Reference information |
Segment |
Product |
Component |
Platform |
Version |
Edition |
Application Servers |
Runtimes for Java Technology |
Java SDK |
|
|
|
|
|
|
|