What type is a var?

Java 10 introduced “var” where the type of the variable is implied. This leads to some tricky scenarios.

We first learn that “var” can replace the type. That means these two code blocks are equivalent.

int a = 9;
int b = a;
var a = 9;
int b = a;

Ok. So far so good. Now we have this code:

short a = 9;
short b = a;

So we substitute var and the code no longer compiles!

var a = 9;
short b = a;

What’s going on? Well, Java is only using the one line to figure out the type. Since int seems like a reasonable default, variable a is an int. Until of course, we get to the next line and it isn’t.

This would compile, but defeats the purpose of using var. So be careful!

var a = (short) 9;
short b = a;

Leave a Reply

Your email address will not be published. Required fields are marked *