To my understanding, if type checking can be done during compilation, the type casting will be done during compilation and will not incur any runtime overhead.
For example
public Child getChild() {
Parent o = new Child();
return (Child) o;
}
Is the type casting done during compilation or during runtime?
And is there any general rule to decide if a type casting is done by javac compiler or by the VM?
Actually, there are three possibilities in this case:
javaccompiler could perform the optimization.I expect that it is option 1. or 2. but this could be platform specific.
In fact, on my system the bytecode is not optimized. If any optimization is to occur it will be up the the JIT compiler to do it. (This fits with what I’ve heard … that most Java bytecode compilers do little in the way of optimization before generating bytecodes.)