Can a local variable with the specified type be reassigned to another type?

I remember reading somewhere that local variables with inferred types can be reassigned to values ​​of the same type, which makes sense.

var x = 5;
x = 1; // Should compile, no?

However, I am curious what happens if you reassign xto an object of a different type. Will something like this still compile?

var x = 5;
x = new Scanner(System.in); // What happens?

Currently, I cannot install an earlier version of JDK 10 and do not want to wait until tomorrow to find out.

+4
source share
2 answers

It does not compile, it produces "incompatible types: the scanner cannot be converted to int". Local type inference does not change the static typing of Java. In other words:

var x = 5;
x = new Scanner(System.in);

is just syntactic sugar for:

int x = 5;
x = new Scanner(System.in);
+7

var , .

, :

var x = 5;
x = 1; 

, x int 1, , .

, - :

var x = 5;
x = "1"; 

, x int, string to x .

Scanner, , .

+3

Source: https://habr.com/ru/post/1695079/


All Articles