DEV Community

Prabu Subra
Prabu Subra

Posted on • Updated on

Local Variables Type Inference in Java

To be short, This post is about a type called var, which is introduced in java 10. Before started using var type, i have analysed and summarised about where to use and not to use var type like as an argument for methods, constructors, Exceptions, lambdas, Streams, etc...

var - Type Inference for local variables.

Before start using var, we need to understand few questions.

What is var ? what is the use of it ?

It is used to declare local variables and reduces the boilerplate code.

Is it a new keyword introduced in java ?

The answer is big No, it is not a keyword, a new type called var has created to improve type inference.

Is java becoming dynamic type language like JavaScript ?

No, Added an intelligent for compiler to understand the type of the local variable using its initializer without specifying explicitly.

How are the possible ways to declare local variables?

Examples:-

List<String> list = new ArrayList<String>(); // level 1
List<String> list = new ArrayList<>(); // level 2
var list = new ArrayList<String>(); // level 3

There are the places to use and not to use. Lets see few of that.

Scenario Example
Cannot use var without initializer. jshell> var a;

| Error:

| cannot infer type for local variable a

| (cannot use 'var' on variable without initializer)

| var a;

Cannot initialize with null. jshell> var a=null

| Error:

| cannot infer type for local variable a

| (variable initializer is 'null')

| var a=null;

| ^---------^

Cannot use with arrays jshell> var[] a = new int[]{1,2,3}

| Error:

| 'var' is not allowed as an element type of an array

Cannot use Multi variable declarations jshell> var a = "Alpha",b="Beta",c="Gamma";

| Error:

| 'var' is not allowed in a compound declaration

| var a = "Alpha",b="Beta",c="Gamma";

| ^

| Error:

| 'var' is not allowed in a compound declaration

| var a = "Alpha",b="Beta",c="Gamma";

Variables, methods can be named var. jshell> var var = "Hello World!!!"

var ==> "Hello World!!!"

jshell> /l var

1 : var var = "Hello World!!!";

jshell> public void var() { System.out.println("Hello world!!!");}

| created method var()

jshell> var()

Hello world!!!

Classes and Interfaces can't be named var jshell> class var {}

| Error:

| 'var' not allowed here

| as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations

| class var {}

| ^

jshell> interface var {}

| Error:

| 'var' not allowed here

| as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations

| interface var {}

| ^

Can be used with collections jshell> var list = List.of("alpha","beta","gamma");

list ==> [alpha, beta, gamma]

jshell> /v list

| List list = [alpha, beta, gamma]

jshell> var set = Set.of("alpha","beta","gamma");

set ==> [beta, gamma, alpha]

jshell> /v set

| Set set = [beta, gamma, alpha]

jshell> var map = Map.of(Map.entry("name","PrabuSubra"),Map.entry("city","Bangalore"))

map ==> {name=PrabuSubra=city=Bangalore}

jshell> /v map

| Map,Map.Entry> map = {name=PrabuSubra=city=Bangalore}

Cannot use in method/Constructor arguments jshell> public void displayError(var errorMessage) { System.out.println(" Error due to : "+errorMessage);}

| Error:

| 'var' is not allowed here

| public void displayError(var errorMessage) { System.out.println(" Error due to : "+errorMessage);}

| ^-^

Cannot used as return type in method signature. jshell> public var displayError(String errorMessage) { return "Error due to : "+errorMessage;}

| Error:

| 'var' is not allowed here

| public var displayError(String errorMessage) { return "Error due to : "+errorMessage;}

| ^-^

Can be used in loops. jshell> for(var templist : list){ System.out.println(templist);

}

for(var i = 0;i

}

Can be used with Streams shell> var streams = Stream.of("alpha","Beta","Gamme","delta","Epsilon");

streams ==> java.util.stream.ReferencePipeline$Head@1bce4f0a

jshell> /v streams

| Stream streams = java.util.stream.ReferencePipeline$Head@1bce4f0a

Cannot assigned Functional interfaces to it. jshell> var function = (data)->data

| Error:

| cannot infer type for local variable function

| (lambda expression needs an explicit target-type)

| var function = (data)->data;

| ^--------------------------^

jshell> var consumer = (data)->{}

| Error:

| cannot infer type for local variable consumer

| (lambda expression needs an explicit target-type)

| var consumer = (data)->{};

| ^------------------------^

jshell> var supplier = ()->{return new String("Hello world!!!");}

| Error:

| cannot infer type for local variable supplier

| (lambda expression needs an explicit target-type)

| var supplier = ()->{return new String("Hello world!!!");};

| ^--------------------------------------------------------^

jshell> var runnable = ()->{}

| Error:

| cannot infer type for local variable runnable

| (lambda expression needs an explicit target-type)

| var runnable = ()->{};

| ^--------------------^

Cannot use with Exception handlers jshell> try { } catch (var e){}

| Error:

| 'var' is not allowed here

| try { } catch (var e){}

| ^-^

Cannot assign to interface, it always reference to initializer type. jshell> var list = new ArrayList()

list ==> []

jshell> /v list

| ArrayList list = []

jshell>

Cannot used with type inference. jshell> class Alpha { var t;}

| Error:

| 'var' not allowed here

| as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations

| class Alpha { var t;}

| ^

| Error:

| 'var' is not allowed here

| class Alpha { var t;}

| ^-^

Law of var:-
Properly initialised, Non-array variables can use the luxury of var type inference.

Summary:-
Eventually, Java has added few spoon of sugar to existing Type Inference feature. it is not completely freed developers hands to use var in code, it comes with its own laws. Type inference is not completely new feature in java, it has improved a step to use for local variables,mostly to avoid boilerplate code with less upgrade hurdles. The target source code base shouldn't contains class or interface, which was named as var and possibility also rare, nearly nothing. It is one of the way(not only way) to declare local variables.

Reference:-

http://openjdk.java.net/jeps/286

https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html

https://github.com/prabusubra/Learning/blob/master/Java/JShell/jshell.txt

Note:- if you feel something has to be added or wrong, feel free to comment below. Thanks for reading!!!

Top comments (1)

Collapse
 
adduxe profile image
adduxe

I'm new to Java. The syntax appealed to me because it's simple enough and really programmer-centric. Another feature I love about it is its strong-typing (you know exactly the values to expect). I guess I have not programmed enough yet to appreciate the value of var.
With the introduction of the var, I feel like it's being loose again like JavaScript and PHP. That is why I am not in favor...for now.