var keyword in java

In this tutorial you will learn about var keyword in java, how to use var keyword in java, where to use var keyword and brief description about var keyword in java.

The var keyword in java is not exist till java 9 version, it is introduce in java 10 version by oracle.

var keyword in java

The var keyword is used to allow coder to not declare variable type explicity.

Example: Declaration of variable without var keyword

int a=10
String name="programiz"

Example: Declaration of variable with var keyword

var a=10
var name="programiz"

Example 2: Declaration of variable without var keyword

List<String> list=new ArrayList<String>();

Example 2: Declaration of variable with var keyword

var list=new ArrayList<String>();

You can see that var is used to make code much simple, easier and shorter but there is some limitation of using var keyword in java.

Limitation of var keyword

  • We cannot used var keyword in global variable declaration means var keyword is only used inside method.
  • The var keyword cannot be used as genric type
  • The var keyword cannot be used with lambda expression.
  • var keyword cannot be used for return type and method parameter.
  • var keyword also cannot be used with genric type.
  • var keyword cannot be used without explicit initialization.

Also noted that we cannot declare variable with var without initialization

var a;

This will show error, so you have to initialize the code using null.

var a= null;

Was this article helpful?
YesNo

1 thought on “var keyword in java”

Leave a Comment