How to use the var keyword in Java?

Java is statically typed.

It means the type of a variable is known at compile time.

And it is strongly typed , an integer variable will always be an integer variable .

Starting Java 10 , Java introduced the concept of local variable type.

Since then you can use var keyword to represent variables. This seems to break static typing but it is not as we will see shortly.

var keyword can be used only within local scope (within a method and within a block).

So an integer variable like this :

int i=10;

could be replaced by :

var i=10;

It applies to all data types.

Even user defined objects can be referred to with a ‘var’ keyword within local scope.

In the below example instead of using the class name , var keyword is used to create an object for the class LocalVariableTypeDemo:

package localvariable;
public class LocalVariableTypeDemo {
	public String getMessage() {
		return "Hey how are you?";
	}
	public static void main(String a[]) {
		var localObj = new LocalVariableTypeDemo();
		System.out.println(localObj.getMessage());
	}
}

But doesn’t this make Java dynamically typed?

No!

Java infers the type of a variable referred by ‘var’ keyword based on how it is initialized.

So in the above example , since localObj is initialized to LocalVariableTypeDemo object , it is referred as of type LocalVariableTypeDemo class at compile time .

Once it is initialized you cannot change the data type. You cannot assign a string value to the above variable localObj.

So , where can var keywords be used?

  • To initialize local variables as in the above example
  • As an index variable in loops like this :
	for(var i=0;i<10;i++) {
			
			System.out.println(i);
			
		}
  • Inside try with resources statement:
	try (var f = new FileInputStream(new File("C:/hello.txt"))) {
		} catch (Exception e) {
		}

Where cannot var keyword be used?

  • Class fields
  • Method parameters
  • Method return types

It cannot be used in these places because any data type can be passed to the above at run time.

Quoting JDK docs:

..suppose that the return type of a method were inferred from the expression in the method’s return statement. A change to the method’s implementation might end up changing the type of the expression in the return statement. This in turn might change the method’s return type. This could result in a source or binary incompatibility. Such incompatible changes should not arise from harmless-looking changes to the implementation.

Suppose a field’s type were inferred. A change to the field’s initializer could change the field’s type, which might unexpectedly break reflective code.

Further restrictions on var keyword include:

  • You cannot use var keyword without initializing it (as the data type is inferred during initialization)
  • You cannot assign null to a var variable

To summarize, var keyword makes code shorter and cleaner.


Posted

in

by

Tags:

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading