What is var type in java with example

var type in java: – A variable with the type of var can store any kind of value in it. ( ex. int, float, char, boolean, etc.)

Table of Contents

Most Important Points –

  • var is not a keyword.
  • var type was introduced in version 10 of java.
  • var is not a datatype.
  • variable name in java can be var.
  • A variable with the type of var can not be static and non-static.
  • method argument can not be a type of var.

var type in java with example

Note 1 – A variable with the type of var can store any kind of value in it.

Example 1

public class A{
	public static void main(String[] args) {
 		var x1=10;
 		var x2=30.24f;
 		var x3="raju";
 		var x4=true;
 		var x5=new A();
 		System.out.println(x1);
 		System.out.println(x2);
 		System.out.println(x3);
 		System.out.println(x4);
 		System.out.println(x5);
	}
}
Output:
10
30.24
raju
true
A@3fee733d

You Also Learn –

Note 2: – var is not a keyword in java, enhance variable name in java can be var.

Example 2

public class A{
	public static void main(String[] args) {
 		var var=748;
 		System.out.println(var);
	}
}
Output: 748

Note 3 – A variable with the type of var can not be static and non-static. hence we can error below program.

Example 3

public class A{
	static var x1;  // error
	var x2;         // error   
	public static void main(String[] args) {
 		var var=748;  // correct
 		System.out.println(var);
	}
}

Note 4 – method argument can not be a type of var. hence the below program throws error.

Example 4

public class A{   
	public static void main(String[] args) {
 		
	}
	public void test(var x) {  // Error
		
	}
}

Leave a Comment