Meet Java 10’s var

3248 VIEWS

Java is, without a doubt, syntactically verbose! Constructs that span only a single line in other programming languages may span several lines in Java. This is partly due to Java being a statically typed language. Beginners, for this reason, find Java somewhat daunting. But there is a tool that makes it all easier that I will discuss in this post.

 #Python 3
foo = "bar"
print(foo)
 // JavaScript
var foo = "bar";
console.log(foo);
 // Java
String foo = "NOT bar";
System.out.println(foo);

The Java construct doesn’t seem to be much different from the rest. However, to successfully run in a non-REPL environment, this must be included in a class whose name should be equal to the name of the file (not including the .java extension). In short, you need to write undesirably long code to do very trivial things in Java.

JEP 286 to the Rescue

Shortly after the release of Java 9 came the release of Java 10. Java 9 brought Java programmers the Module System, JShell, the Javadoc search feature, multi-release jars, and several other interesting features aimed at making programmers’ lives easier. Java 10 brought the introduction of var, thanks to JDK Enhancement Proposal (JEP) 286. The sole aim of JEP 286 is captured in its title: Local-Variable Type Inference. And var allows you to omit the type when the compiler is able to infer the type for you. Type inference is not new—If you’ve used generics in Java 7 or later, you’ve come across the omission of type using the diamond (<>). Several other popular statically typed languages already provide some sort of support for local variable type inference, like Go, C#, Scala, and even C++. Java is late on this. Nonetheless, Java developers are excited for such an interesting inclusion.

Before I continue, you should note that var is not a keyword in Java as you may have expected. It simply is an identifier with special meaning as the type of a local variable declaration. If you haven’t already noted, var works only in a local context. Once in the main method (and any other local context) you are at liberty to use var for local variable declarations.

Usage

When var is used, the compiler should immediately be able to infer the type. (It will fail otherwise.) In addition, var variables cannot hold the value null, and it cannot be used as the name of a class.

 // Okay! Type inferred
var foo = "bar";	

// Not allowed! Type cannot be inferred	
var foo1;

//variable initializer is null
var oh = null;		

//as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations
class var {}

The second expression will fail with the compiler displaying something like cannot infer type for local variable foo1 (cannot use ‘var’ on variable without initializer).

Additionally, var does not allow declaration of multiple variables.

 //Not allowed
//'var' is not allowed in a compound declaration

var foo = "bar", line = 1;

Again, var cannot be used to declare arrays. Sad!

 //Not Allowed
//'var' is not allowed as an element type of an array

var lot[] = new int[10];
Var lot[] = {1, 2, 4};

// This is PERMITTED
var lot = new ArrayList();
var b = List.of(1, 2, 3, 4);

Plus, var is also not allowed for self-referencing.

 // Not allowed
//cannot use 'var' on self-referencing variable

var self = (self = "me");

Once a variable is declared, assigning it to a different type fails.
// Okay
var foo = 33;
foo = 45;


// Not Allowed
// Error: incompatible types: possible lossy conversion from double to int
foo = 33.0;

However, var is perfect for loops, as it reduces the lines of code one has to write. See it in action in the following loop.

 for(var i = 0; i < 10; i++) 
			System.out.println(i);
		System.out.println("Fire!");
// print 0 to 9, then Fire!

Also note that var is not allowed for parameters. It is quite easy to err on this.

Conclusion

By knowing the do’s and don’ts of using var in Java 10, you should be able to reduce the amount of code you write, and possibly save some time. Although var may seem like a minor feature addition, it is one Java developers will certainly use often. Once you switch to Java 10, you should definitely take advantage of it.


Bruno is a junior at Ashesi University College studying Computer Science. He is interested in leveraging the power of technology to increase productivity. As a big fan of open source technology, he is currently exploring the possibility of using the Bitcoin Blockchain to fight corruption in government. Bruno is a regular contributor at Fixate IO.


Discussion

Leave a Comment

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

Menu
Skip to toolbar