Chapter 11 of 77

var Keyword in Java

So far, every time we created a variable, we wrote its data type first:

int age = 21;
double price = 499.99;
String name = "Priya";

Look at the first line. The value 21 is clearly an int, and yet we still had to write int. Since Java 10, we can let the compiler work out the type for us by using var:

var age = 21;
var price = 499.99;
var name = "Priya";

These three lines mean exactly the same thing as the three lines above. In this chapter, we will see how var works, where it is allowed, where it is not allowed, and when it is a good idea to use it.

What is var?

var tells the compiler: "Look at the value on the right side and use its type for this variable." This is called local variable type inference.

  • Local variable: it only works for variables declared inside a method (such as inside main()).

  • Type inference: the compiler infers (figures out) the type from the value.

The most important thing to understand is this:

var does not create a variable without a type. The variable still has a fixed type. You just don't have to write it.

The compiler replaces var with the real type while compiling. After that, the program behaves exactly as if you had written the type yourself. There is no speed difference at all.

You write:            var age = 21;
Compiler sees 21  →   21 is an int literal
Compiler treats it:   int age = 21;

How the Compiler Picks the Type

The compiler uses the same rules we learned in the Literals and Data Types chapters. The type of the value decides the type of the variable:

Declaration

Inferred type

Why

var a = 21;

int

A whole-number literal is int by default

var b = 21L;

long

The L suffix makes it a long literal

var c = 4.5;

double

A decimal literal is double by default

var d = 4.5f;

float

The f suffix makes it a float literal

var e = 'A';

char

Single quotes mean a character

var f = true;

boolean

true and false are boolean literals

var g = "Hi";

String

Double quotes mean a String

var h = (byte) 10;

byte

The cast makes the value a byte

Notice the last row. There is no literal for byte or short, so var x = 10; always gives an int. If you really want a byte, you need a cast (as we learned in the Type Casting chapter), or simply write byte x = 10;, which is clearer.

The type can also come from an expression, not just a single literal:

class Main {
    public static void main(String[] args) {

        var code = 'A' + 1;
        System.out.println(code);

        var letter = (char) ('A' + 1);
        System.out.println(letter);

        var a = 10;
        var b = 4;
        System.out.println(a / b);

        var c = 10.0;
        System.out.println(c / b);
    }
}

Output:

66
B
2
2.5

Let's understand each line:

  • 'A' + 1 is a char plus an int. In arithmetic, Java first converts the char to its numeric value ('A' is 65, as we saw in the Type Conversion chapter), so the result is the int 66. That means code is an int, not a char.

  • (char) ('A' + 1) casts that int back to a char, so letter is a char and prints B.

  • a and b are both int, so a / b is integer division: the decimal part is dropped and the result is 2, not 2.5. We will look at this properly in the Operators chapter.

  • c is a double, so c / b gives 2.5.

So with var, you must still know the type of the value. var hides the type from your eyes, but not from the compiler.

The Type is Fixed After Declaration

Once the compiler has decided the type, it cannot change. Java is a statically typed language, and var does not change that.

var count = 10;     // count is an int
count = 25;         // fine, 25 is an int
count = "ten";      // Error

The compiler stops us with:

error: incompatible types: String cannot be converted to int

Similarly, normal conversion rules still apply:

var x = 10;   // x is an int
x = 3.5;      // Error
error: incompatible types: possible lossy conversion from double to int

This is a big difference from languages like JavaScript or Python, where the same variable can hold a number now and a string later. In Java, even with var, a variable holds only one type for its whole life.

Rules: Where var Cannot Be Used

Because the compiler needs a value to look at, var has a few rules. Each of the following will not compile.

1. You must give a value on the same line.

var count;   // Error
error: cannot infer type for local variable count
  (cannot use 'var' on variable without initializer)

Without a value, there is nothing to infer the type from.

2. The value cannot be null.

var data = null;   // Error
error: cannot infer type for local variable data
  (variable initializer is 'null')

null means "no object", so it doesn't tell the compiler which type you want.

3. An array initializer alone is not enough.

var marks = {90, 80, 70};            // Error
var marks2 = new int[]{90, 80, 70};  // OK, type is int[]
error: cannot infer type for local variable marks
  (array initializer needs an explicit target-type)

We will learn arrays properly in a later chapter. For now, just remember that {90, 80, 70} on its own does not say what kind of array it is.

4. Only one variable per declaration.

var a = 1, b = 2;   // Error
error: 'var' is not allowed in a compound declaration

Write them on separate lines instead: var a = 1; and var b = 2;.

5. Only for local variables. You cannot use var for fields of a class, method parameters, or method return types:

class Main {
    var count = 0;                      // Error: field
    static void show(var x) { }         // Error: parameter
    static var getValue() { return 1; } // Error: return type
}

Each of these gives:

error: 'var' is not allowed here

We will learn about classes, fields and methods soon. The reason for this rule is that a method's parameters and return type are part of how other code uses it, so Java wants them written out clearly.

Where var Is Allowed

You can use var for local variables wherever there is a value to infer from:

  • Normal local variables inside a method: var total = 0;

  • Together with final: final var LIMIT = 100; (a constant whose type is inferred)

  • The counter of a for loop: for (var i = 0; i < 5; i++), and the variable of a for-each loop. You will meet loops in a few chapters.

  • Later, with long type names such as collections, which is where var saves the most typing.

var is Not Really a Keyword

Here is a fun fact that sometimes appears in interviews. Technically, var is not a keyword like int or class. It is a reserved type name. This was done so that old code that already used var as a variable name would still compile.

So this is legal (but please don't do it):

int var = 5;
System.out.println(var);   // prints 5

However, since Java 10 you cannot name a class or other type var:

class var { }   // Error
error: 'var' not allowed here
  as of release 10, 'var' is a restricted type name and cannot be used for type declarations

A Complete Example

Let's write a small program that uses var for every local variable:

class Main {
    public static void main(String[] args) {

        var studentName = "Rahul";
        var semester = 5;
        var cgpa = 8.4;
        var backlogs = 0;
        var isPlaced = true;

        final var MAX_CGPA = 10.0;

        System.out.println("Student : " + studentName);
        System.out.println("Semester: " + semester);
        System.out.println("CGPA    : " + cgpa + " / " + MAX_CGPA);
        System.out.println("Backlogs: " + backlogs);
        System.out.println("Placed  : " + isPlaced);

        var percentage = cgpa * 9.5;
        System.out.println("Approx %: " + percentage);

        var wholePercentage = (int) percentage;
        System.out.println("Whole % : " + wholePercentage);
    }
}

Output:

Student : Rahul
Semester: 5
CGPA    : 8.4 / 10.0
Backlogs: 0
Placed  : true
Approx %: 79.8
Whole % : 79

Here the compiler inferred:

studentName      → String
semester         → int
cgpa             → double
backlogs         → int
isPlaced         → boolean
MAX_CGPA         → double (and final)
percentage       → double   (double * double)
wholePercentage  → int      (because of the (int) cast)

When Should You Use var?

var is a tool for readability. Use it when it makes code easier to read, and avoid it when it makes code harder to read.

Good use of var

Better to write the type

The type is obvious from the right side: var name = "Priya";

The type is not obvious: var result = calculate(); (what does calculate() return?)

The type name is very long (common with collections, later in this tutorial)

You need a specific type such as byte, short, long or float and don't want to rely on a suffix or cast

Short methods where the variable is used only nearby

Beginners' code and exam answers where showing the type makes your thinking clear

A good rule of thumb: if a reader cannot tell the type within a second, write the type.

Common Mistakes

  • Thinking var makes Java dynamically typed. It doesn't. The type is fixed at compile time, and count = "ten" still fails if count is an int.

  • Expecting a long or double automatically. var big = 10; is an int. Write 10L for a long and 10.0 for a double.

  • Forgetting integer division. With var a = 10; var b = 4;, the expression a / b is 2, because both are int.

  • Declaring without a value. var count; does not compile. Neither does var data = null;.

  • Using var for fields or parameters. It only works for local variables.

Interview Corner

  • Which Java version introduced var? Java 10, through JEP 286 (local variable type inference). Java 11 also allowed var for lambda parameters, which you will see in the Lambda Expressions chapter.

  • Is var slower? No. Type inference happens entirely at compile time. The compiled bytecode is the same as with an explicit type.

  • Is var a keyword? No, it is a reserved type name. int var = 5; compiles, but class var {} does not.

  • Is Java dynamically typed with var? No. Java remains statically typed. var only saves you from writing the type.

Quick Revision

var = let the compiler infer the type of a local variable from its value. The type is still fixed.

  • Available since Java 10, only for local variables.

  • Must have a value on the same line; the value cannot be null or a bare {...} array initializer.

  • One variable per declaration; not for fields, parameters or return types.

  • Use it when the type is obvious; write the type when it helps the reader.