The Wayback Machine - https://web.archive.org/web/20241205151803/https://www.geeksforgeeks.org/var-keyword-in-java/
Open In App

var keyword in Java

Last Updated : 22 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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);
    }
}


Output

100
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);
    }
}


Output

100

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


Next Article

Similar Reads

Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Usage of Break keyword in Java
Break keyword is often used inside loops control structures and switch statements. It is used to terminate loops and switch statements in java. When the break keyword is encountered within a loop, the loop is immediately terminated and the program control goes to the next statement following the loop. When the break keyword is used in a nested loop
6 min read
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class when we're working with objects. You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.  The Keyword "super" came into the picture with the concept of Inheritance. In this article, we gonna covers all about super in Java
8 min read
Protected Keyword in Java with Examples
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java. The access of various modifiers can be seen in the following table below as follows:  The protected keyword in Java refers to one of its access modifiers. The methods or data memb
5 min read
volatile Keyword in Java
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example. class SharedObj { // Changes made to sharedVar in one thread // may not immediately reflect in other th
5 min read
transient keyword in Java
transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type. transient keyword plays an impo
3 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 boolean true or false as in Java we do not have 0
4 min read
return keyword in Java
In Java, return is a reserved keyword i.e., we can't use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows:  Case 1: Methods returning a valueCase 2: Methods not returning a valueLet us illustrate by directly implementing them as follows: Case 1
6 min read
strictfp keyword in java
In Java, the strictfp is a modifier that stands for strict floating-point which was not introduced in the base version of Java as it was introduced in Java version 1.2. It is used in Java for restricting floating-point calculations and ensuring the same result on every platform while performing operations in the floating-point variable. Floating-po
2 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 Abstract KeywordIn Java, the abstract keyword is use
7 min read
Native Keyword in Java
The native keyword in Java is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface). The native keyword is a modifier that is applicable only for methods, and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called native methods or foreign methods. The native
4 min read
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java. The following are different contexts where the final is used: VariableMethodClass The final keyword is used to define constants or prevent inheritance in Java. To understand how and when to use final
12 min read
static Keyword in Java
The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class rather than an instance of the class. The static keyword is used f
9 min read
Can String be considered as a Keyword?
Is string a keyword? A string is NOT a keyword. It is one of the names of data types declared in the standard library. How to check if a string is a keyword in C++? In C++ there is no special method to check whether the given string is a keyword or not. But there are a set of keywords present which is listed below-"auto", "break", "case", "char", "
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Article Tags :
Practice Tags :