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?
Java is a statically typed programming language. This means that when identifiers are introduced they must be declared with an associated type and the compiler will check over the program to make sure the type declarations are consistent with the code.
In a dynamic language, type checking occurs at run-time. Many languages like python, ruby etc check the type safety of a program at runtime. Typically, It is done by tagging each run-time object with a tag (that is a reference to a type) which has all the type information.
Type checking happens at run time and at compile time.
Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With