Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does type checking happen in Java

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?

like image 442
Meowmi Avatar asked Apr 24 '19 18:04

Meowmi


People also ask

How does java do type checking?

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.

Is type checking done at runtime?

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.

Does type checking happen during compilation?

Type checking happens at run time and at compile time.

Does java check types at runtime?

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.


Video Answer


1 Answers

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

like image 97
LuKenneth Avatar answered Oct 17 '22 22:10

LuKenneth