Showing posts with label Java10. Show all posts
Showing posts with label Java10. Show all posts

Sunday, April 21, 2019

Java 10 - Local Variable Type Inference

Java 10 - Local Variable Type Inference

In one of my previous blog, I have already discussed about Type Inference. If you don’t have the idea about Type Inference then you can check my blog here.

If we want to understand Type Inference in one line then we can say that It is the capability of the compiler to automatically detect the datatype of a variable at the compiler time.

What is Local Variable type inference?

Java 10 added new feature that allows the developer to skip the type declaration associated with local variables (those defined inside method definitions, initialization blocks, for-loops, and other blocks like if-else), and the type is inferred by the JDK. It will, then, be the job of the compiler to figure out the datatype of the variable.
Until Java 9, we had to define the type of the local variable.

E.g.: String message = “Welcome to”;

The above statement is right as that’s how things have been since the inception of java but if you observe, the type of the object at right side is clearing mentioning the type of data that we have defined at left side which makes the variable redundant.
So with Java 10, We can declare a local variable without defining its data type at left side.

            Var message = “Welcome to”;

Over here, we don’t have to provide the data type of String to local variable message. Compiler will get the datatype based on right hand side value.

  • This feature is available only for local variables with the initializer. It cannot be used for member variables, method parameters, return types, etc as the initializer is required as without which compiler won’t be able to infer the type.
  • To support backward compatibility, var is not a java reserved keyword. So, we can create variable with name var as it is allowed.

Let’s see where all we can use var

package com.waheedtechblog.typeinference;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class TypeInferenceExample {

       static {
             // static block variable
             var staticVaribale = "var in static block";
             Consumer<String> displayOnConsole = msg -> {


       public static void main(String[] args) {

             TypeInferenceExample inferenceExample = new TypeInferenceExample();

             BiConsumer<String, String> displayOnConsole = (str, msg) -> {
                    System.out.println(str + msg);

             // Before Java 10
             String message = "Welcome to";
             displayOnConsole.accept("Before JDK 10: ", message);

             // Using JDK 10, Local Variable
             var message10 = "Welcome to";
             displayOnConsole.accept("With JDK 10: ", message);

             // local variable declaration in enhanced loops
             String[] countryName = { "India", "Japan", "UAE", "USA", "UK" };
             displayOnConsole.accept("", "List of Country using enhanced loop");
             for (var country : countryName) {
                    displayOnConsole.accept("", country);

             // basic for loop
             displayOnConsole.accept("", "List of Country using basic loop");
             for (var i = 0; i < countryName.length; i++) {
                    displayOnConsole.accept("", countryName[i]);

             displayOnConsole.accept("Length of string '" + message10 + "' is: ",

             // var is not keyword, so you can create variable with name var as well.
     String var = "var is not keyword";
     displayOnConsole.accept("", var);

       // can return var type as well
       private int getLenth(String msg) {
             var length = msg.length();
             return length;


var in static block
Before JDK 10: Welcome to
With JDK 10: Welcome to
List of Country using enhanced loop
List of Country using basic loop
Length of string 'Welcome to' is: 29
var is not keyword

Illegal use of Var:

1.    Can’t use as a class field
Class Test {
            Var msg; // not allowed as it is local variable inference
2.    Local variable without initialization
Private void getOTP(){
            Var otp ; // cant use without initializer
3.    Not allowed as parameter for any methods
Private void getOTP(var secretKey){
            //Error, cannot use var on method parameter
4.    Not permitted in method return type
Private var getOTP(String secretKey){
            //Error, Method return type cannot be var
5.    Not permitted with variable initialized with ‘NULL’
Private String getOTP(String secretKey){
            Var msg = null; Error, cant initialize as null

You can download the source code from my GitHub repository.

Happy Coding..!!!

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...