Type Casting Compile and Runtime Error

This section provides a tutorial example on compilation time casting error and runtime casting exception.

If you are trying to convert reference type to another type that is not compatible, you will get a compiler error. Here is a simple example:

/* TypeCastingCompileError.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.util.*;
class TypeCastingCompileError {
   public static void main(String[] a) {

      // Compiler error: Casting from Integer to Long is not allowed
      Integer myInteger = new Integer(777);
      Long myLong = (Long) myInteger;
   }
}

Try to compile it. You will see a compilation error:

TypeCastingCompileError.java:10: error: incompatible types: Integer
cannot be converted to Long
      Long myLong = (Long) myInteger;
                           ^
Note: TypeCastingCompileError.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

If you want, you can avoid the compiler error by casting Integer to Object, before casting it to Long. But you will get a runtime error. Here is a simple example:

/* TypeCastingRuntimeError.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
class TypeCastingRuntimeError {
   public static void main(String[] a) {

      try {
         // Runtime error: Casting from Integer to Long is not allowed
         Integer myInteger = Integer.valueOf(777);
         Object myObject = (Object) myInteger;
         Long myLong = (Long) myObject;
      } catch (Exception e) {
         e.printStackTrace();
      }

      try {
         // Runtime error: Casting from Integer to Long is not allowed
         Integer hisInteger = Integer.valueOf(888);
         Number hisNumber = (Number) hisInteger;
         Long hisLong = (Long) hisNumber;
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Try to compile and run it with JDK 13:

java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast
to java.base/java.lang.Long
        at TypeCastingRuntimeError.main(TypeCastingRuntimeError.java:11)
java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast
to java.base/java.lang.Long
        at TypeCastingRuntimeError.main(TypeCastingRuntimeError.java:20)

Try to compile and run it with JDK 8:

java.lang.ClassCastException:
   java.lang.Integer cannot be cast to java.lang.Long
        at TypeCastingRuntimeError.main(TypeCastingRuntimeError.java:11)

java.lang.ClassCastException:
   java.lang.Integer cannot be cast to java.lang.Long
        at TypeCastingRuntimeError.main(TypeCastingRuntimeError.java:20)

As you can see from this example, the compiler fails to detect the type casting error, because down casting "(Long) Object" or "(Long) Number" is a valid casting if the reference object is a Long object.

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

Reference Data Types and Variables

 Reference Types Supported in Java

 Creating Class Type Objects

 Class Type Variables Storing References

 Interface Type Variables

 Class and Interface Hierarchy

 Supertype and Subtype

 Explicit and Implicit Type Casting

 Type Casting Example Program

Type Casting Compile and Runtime Error

 Enum Types and Enum Constants

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Assert Statements and -ea" Option

 Annotation Statements and Declarations

 Java Related Terminologies

 Archived Tutorials

 References

 Full Version in PDF/EPUB