The var reserved type name (not a Java keyword) was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it.
1. We can declare any datatype with the var keyword.
Java
// Java program to explain that
// var can used to declare any datatype
class Demo1 {
public static void main(String[] args)
{
// int
var x = 100;
// double
var y = 1.90;
// char
var z = 'a';
// string
var p = "tanu";
// boolean
var q = false;
// type inference is used in var keyword in which it
// automatically detects the datatype of a variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(p);
System.out.println(q);
}
}
Output100
1.9
a
tanu
false
2. var can be used in a local variable declaration.
Java
// Java program to demonstrate that
// var can be used to declare a local variable
class Demo2 {
public static void main(String[] args)
{
// local variable
var x = 100;
// print x to the console
System.out.println(x);
}
}
3. var cannot be used in an instance and global variable declaration.
Java
// Java program to demonstrate that
// var cannot be used to declare
// instance and global variables
class Demo3 {
// instance variable
var x = 50;
public static void main(String[] args)
{
System.out.println(x);
}
}
Output
prog.java:8: error: 'var' is not allowed here
var x = 50;
^
1 error
4. var cannot be used as a Generic type.
Java
// Java program to demonstrate that
// var cannot be used as a Generic
// type
import java.util.*;
class Demo4 {
public static void main(String[] args)
{
// Generic list using var
var<var> al = new ArrayList<>();
// add elements
al.add(10);
al.add(20);
al.add(30);
// print the list
System.out.println(al);
}
}
Output
prog.java:10: error: 'var' is not allowed here
var<var> al = new ArrayList<>();
^
1 error
5. var cannot be used with the generic type.
Java
// Java program to demonstrate that
// var cannot be used with Generic type
import java.util.*;
class Demo5 {
public static void main(String[] args)
{
// var used with Generic type
var<Integer> al = new ArrayList<Integer>();
// add elements
al.add(10);
al.add(20);
al.add(30);
// print the list
System.out.println(al);
// This is valid since type is decided
// based on ArrayList<String>
var list = new ArrayList<String>();
}
}
Output
prog.java:9: error: illegal reference to restricted type 'var'
var<Integer> al = new ArrayList<Integer>();
^
1 error
6. var cannot be used without explicit initialization.
Java
// Java program to demonstrate that
// var cannot be used without explicit
// initialization
import java.io.*;
class Demo6 {
public static void main(String[] args)
{
// declaration without
// initialization
var variable;
// This is also not valid
var variable = null;
}
}
Output
prog.java:13: error: cannot infer type for local variable variable
var variable;
^
(cannot use 'var' on variable without initializer)
prog.java:16: error: cannot infer type for local variable variable
var variable = null;
^
(variable initializer is 'null')
2 errors
7. var cannot be used with Lambda Expression.
Java
// Java program to demonstrate that
// var cannot be used with Lambda
// Expression
import java.util.*;
interface myInt {
int add(int a, int b);
}
class Demo7 {
public static void main(String[] args)
{
// var cannot be used since they
// require explicit target type
var obj = (a, b) -> (a + b);
// calling add method
System.out.println(obj.add(2, 3));
}
}
prog.java:13: error: cannot infer type for local variable obj
var obj = (a, b) -> {
^
(lambda expression needs an explicit target-type)
1 error
8. var cannot be used for method parameters and return type.
Java
// Java program to explain that
// var cannot be used for a method
// parameters and return type
class Demo8 {
// method1 using var
// as a return type
var method1() { return ("Inside Method1"); }
// method2 using var for a
// parameter
void method2(var a) { System.out.println(a); }
public static void main(String[] args)
{
// create an instance
Demo1 obj = new Demo1();
// call method1
var res = obj.method1();
// call method2
obj.method2();
}
}
Output
prog.java:6: error: 'var' is not allowed here
var method1()
^
prog.java:11: error: 'var' is not allowed here
void method2(var a)
^
2 errors
Similar Reads
Java Keywords
In Java, keywords are the reserved words that have some predefined meanings and are used by the Java compiler for some internal process or represent some predefined actions. These words cannot be used as identifiers such as variable names, method names, class names, or object names. Now, let us go t
5 min read
final Keyword in Java
The final Keyword in Java is used as a non-access modifier applicable to a variable, a method, or a class. It is used to restrict a user in Java. We cannot use the final keyword in a block. It restricts the user from accessing that particular part of the program, such as restricting the modification
11 min read
new operator in Java
When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process : Declaration : First, you must declare a variable of the class type. This vari
5 min read
abstract keyword in java
In Java, abstract is a non-access modifier in java applicable for classes, and methods but not variables. It is used to achieve abstraction which is one of the pillars of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Characteristics of Java Ab
7 min read
Important Keywords in Java
Keywords refer to the reserved set of words of a language. These are used for some predefined actions. abstract: It is a non-access modifier applicable for classes and methods. It is used to achieve abstraction. For more, refer to abstract keyword in javaenum: It is used to define enum in Javainstan
2 min read
instanceof Keyword in Java
In Java, instanceof is a keyword used for checking if a reference variable contains a given type of object reference or not. Following is a Java program to show different behaviors of instanceof. Henceforth it is known as a comparison operator where the instance is getting compared to type returning
4 min read
Separators in Java
Be it a programmer who is unaware of this concept but is indulging in every program. Separators help us defining the structure of a program. In Java, There are few characters used as separators. The most commonly used separator in java is a semicolon(;). Let us explore more with the help of an illus
2 min read
Vector get() Method in Java
The java.util.vector.get() method is used to fetch or retrieve an element at a specific index from a Vector. Syntax: Vector.get(int index) Parameters: This method accepts a mandatory parameter index which is of integer data type. It specifies the position or index of the element to be fetched from t
2 min read
Literals in Java
Literal: Any constant value which can be assigned to the variable is called literal/constant. In simple words, Literals in Java is a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable nam
6 min read
dot(.) Operator in Java
The dot (.) operator is one of the most frequently used operators in Java. It is essential for accessing members of classes and objects, such as methods, fields, and inner classes. This article provides an in-depth look at the dot operator, its uses, and its importance in Java programming.Dot(.) Ope
4 min read