I have a question in my homework that looks like this.
Which of the following process happens ONLY during compilation time in Java?
(i) type inference – inferring the type of a variable whose type is not specified.
(ii) type erasure – replacing a type parameter of generics with either Object or its bound.
(iii) type checking – checking if the value matches the type of the variable it is assigned to.
A. Only (i)
B. Only (i) and (ii)
C. Only (i) and (iii)
D. Only (ii) and (iii)
E. (i), (ii), and (iii)
From my understanding, Java only performs type checks for generics during compile time, hence (i) and (ii) are definitely correct. However, I am unsure about type checking, and from the description provided it does not seem like type checking is not limited to generics, but other things as well.
The solution to this question is B, but there was no explanation given. I was wondering then, when does type checking happen? If it does not only happen during compile time, does it happen during both compile time and runtime, or only during runtime, and why?
It also happens during runtime because you can cast objects to their subtypes. You could manually force it to do type checking again at any point with instanceof.
You see Java is not a completely statically typed language. Whenever you cast an object from a type to a subtype, the JVM performs a dynamic (runtime) typecheck to check that the object really is an instance of the subtype. Using instanceof is another example of dynamic type checking.
from this answer