Is there a good reason for this?
Nothing exists 1 .
But flipside is that the Java compiler knows that the type is not needed and optimizes it. Thus, the only “damage” is readability.
For instance.
[ stephen@blackbox tmp]$ cat Test.java public class Test { public void test (String x) { String s = (String) x; System.out.println(s); } } [ stephen@blackbox tmp]$ javac Test.java [ stephen@blackbox tmp]$ javap -c Test Compiled from "Test.java" public class Test { public Test(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public void test(java.lang.String); Code: 0: aload_1 1: astore_2 2: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 5: aload_2 6: invokevirtual #3 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 9: return } [ stephen@blackbox tmp]$
Statement String s = (String) x; compiled for easy loading and storage; no checkcast .
I would not be surprised if the JIT compiler could optimize the redundant checkcast ... if he saw it.
1 -... in writing. In the source code that was generated, the redundant type can serve to simplify the writing of the source code generator. In the end, the readability of the generated code is largely irrelevant.
source share