Java Var

Java Var: Simplifying Declarations

Discover what Java var is, its usage, benefits, and limitations. This post offers various scenarios and practical examples of employing var in Java.

Introduction

Java is a strongly typed language, which means that every variable has a specific data type that cannot be changed. For example, if you declare a variable as int, you can only assign integer values to it.

However, since Java 10, there is a new feature called local variable type inference that allows you to declare variables without specifying their data type. Instead, you can use the keyword var, and the compiler will infer the data type based on the value assigned to the variable. For example, if you write var x = 10;, the compiler will infer that x is an int.

In this blog post, we will explore what is var, how to use it, and what are its benefits and limitations. We will also provide you with different scenarios and examples of using var in Java.

What is var?

Java var is not a new data type, but a reserved type name that can be used to declare local variables. A local variable is a variable that is declared inside a method, a constructor, or a block of code. var can only be used for local variables, not for class fields, method parameters, or return types.

When you use var, you are telling the compiler to infer the data type of the variable based on the value assigned to it. For example, if you write var name = "Alice";, the compiler will infer that name is a String. You can also use var with complex expressions, such as var list = new ArrayList<String>();, and the compiler will infer the data type accordingly.



How to use var in Java?

To use var, you need to follow some rules:

  • You must initialize the variable with a value when you declare it. For example, var x; is not valid, but var x = 10; is valid.
  • You cannot assign a value of a different data type to the variable after it is declared. For example, if you write var x = 10;, you cannot write x = "Hello"; later, because x is inferred to be an int.
  • You cannot use var with null, because the compiler cannot infer the data type from null. For example, var x = null; is not valid.
  • You cannot use var with array initializers, because the compiler cannot infer the array type from the values. For example, var x = {1, 2, 3}; is not valid, but var x = new int[]{1, 2, 3}; is valid.

Here are some examples of using var in Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Consumer;

public class VarExamples {

    public static void main(String[] args) {
        // Example 1: Using var with primitive types
        var x = 10; // x is inferred to be an int
        var y = 3.14; // y is inferred to be a double
        var z = true; // z is inferred to be a boolean

        System.out.println("x: " + x); // Output: x: 10
        System.out.println("y: " + y); // Output: y: 3.14
        System.out.println("z: " + z); // Output: z: true

        // Example 2: Using var with reference types
        var name = "Alice"; // name is inferred to be a String
        var list = new ArrayList<String>(); // list is inferred to be an ArrayList<String>
        var map = new HashMap<String, Integer>(); // map is inferred to be a HashMap<String, Integer>

        name = "Bob"; // Reassigning name
        list.add("Example"); // Adding an element to the list
        map.put("Key", 123); // Adding a key-value pair to the map

        System.out.println("name: " + name); // Output: name: Bob
        System.out.println("list: " + list); // Output: list: [Example]
        System.out.println("map: " + map); // Output: map: {Key=123}

        // Example 3: Using var with lambda expressions
        var add = (BiFunction<Integer, Integer, Integer>) (a, b) -> a + b; // add is inferred to be a BiFunction<Integer, Integer, Integer>
        var square = (Function<Integer, Integer>) num -> num * num; // square is inferred to be a Function<Integer, Integer>
        var print = (Consumer<Object>) System.out::println; // print is inferred to be a Consumer<Object>

        int result = add.apply(5, 7); // Applying the add function
        int squared = square.apply(4); // Applying the square function
        print.accept("Result of add: " + result); // Output: Result of add: 12
        print.accept("Square of 4: " + squared); // Output: Square of 4: 16
    }
}
VarExamples.java

Examples of var Usage in Java

1. Local Variable Declarations

var list = new ArrayList<String>();    // infers ArrayList<String>
var stream = list.stream();            // infers Stream<String>
var path = Paths.get(fileName);        // infers Path
var bytes = Files.readAllBytes(path);  // infers bytes[]
Java

2. Enhanced For-loop and Traditional For-loop Usage

List<String> myList = Arrays.asList("a", "b", "c");
for (var element : myList) {...}  // infers String

for (var counter = 0; counter < 10; counter++) {...}   // infers int
Java

3. Simplifying Resource Management

try (var input = new FileInputStream("file.txt")) {...}   // infers FileInputStream
Java

4. Lambda Expressions

In lambda expressions, parameter types are inferred, but starting from JDK 11, var can also be used for explicit parameter typing.

BiFunction<Integer, Integer, Integer> = (a, b) -> a + b;

// With JDK 11+
(var a, var b) -> a + b;
Java


What are the benefits of the Java var keyword?

Using var can have some benefits, such as:

1. Conciseness and Readability Enhancement

It can make the code more concise and readable, especially when the data type is long or complex. For example, instead of writing Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();, you can write var map = new HashMap<String, List<Integer>>();.

2. Reduced Boilerplate Code

It can reduce the boilerplate code and avoid repetition. For example, instead of writing String name = employee.getName();, you can write var name = employee.getName();.

3. Enhanced Maintainability and Flexibility

It can improve the maintainability and flexibility of the code, as you don’t need to change the data type of the variable if you change the value assigned to it. For example, if you write var x = 10;, and later you want to assign a double value to x, you don’t need to change the declaration of x.

What are the limitations of var?

Using var can also have some limitations, such as:

1. Reduced Clarity and Explicitness

It can make the code less clear and explicit, especially when the value assigned to the variable is not obvious or descriptive. For example, if you write var x = foo();, it may not be clear what is the data type and meaning of x.

2. Potential for Bugs and Errors

It can introduce bugs and errors if you use var incorrectly or inconsistently. For example, if you write var x = 10; and var y = 10.0;, you may not realize that x and y are of different data types, and this may cause unexpected results when you compare or operate on them.

3. Reduced Compatibility and Interoperability

It can reduce the compatibility and interoperability of the code, as var is only supported by Java 10 and above. If you use var in your code, you may not be able to run it on older versions of Java, or use it with libraries or frameworks that are not compatible with var.

4. Mixing Guesses and Telling Types

In implicitly typed lambda expressions, you can’t mix inferred types and explicitly declared var types:

(var x, y) -> x.process(y)      // Cannot mix var and inferred types
Java

5. Mixing Var and Manifest Types

Similarly, in explicitly typed lambda expressions where you explicitly define types for parameters, you can’t mix explicit types and var:

(var x, int y) -> x.process(y)  // Cannot mix var and manifest types
Java


6. Exclusion of var in Instance Variable Declarations

Java does not permit the use of var when declaring instance variables within a class.

class VarExamples {
    var instanceVar = 50; // Invalid use of var for instance variable
    
    public static void main(String[] args) {
        System.out.println(instanceVar);
    }
}
Java

Output: compile time error

javac VarExamples.java 

VarExamples.java:2: error: 'var' is not allowed here
    var instanceVar = 50;
    ^
1 error
Java

7. Exclusion of var in Instance Variable Declarations

Java does not permit the use of var when declaring instance variables within a class.

public class VarExamples {

    public static void main(String[] args) {
        ArrayList<var> myList = new ArrayList<>(); // Invalid usage of var as a generic type
        myList.add(10);
        myList.add(20);
        myList.add(30);
        System.out.println(myList);
    }
}
Java

Output: compile time error

javac VarExamples.java

VarExamples.java:4: error: 'var' is not allowed here
        ArrayList<var> myList = new ArrayList<>();
                  ^
1 error
Java

8. Var Exclusion with the Generic Type

Java does not allow using var with generic types, specifically as the type argument in collections like ArrayList.

public class VarExamples {

    public static void main(String[] args) {
        var<Integer> myList = new ArrayList<>(); // Invalid usage of var as a generic type
        myList.add(10);
        myList.add(20);
        myList.add(30);
        System.out.println(myList);
    }
}
Java

Output: compile time error

javac VarExamples.java

VarExamples.java:4: error: illegal reference to restricted type 'var'
        var<Integer> myList = new ArrayList<>();
        ^
1 error
Java

9. Var Exclusion without Explicit Initialization

Java madates explicit initialization for var; utilizing var without assigning a value is not allowed.

public class VarExamples {

    public static void main(String[] args) {
        var variable; // Invalid use of var without explicit initialization
        var anotherVariable = null; // Also invalid; null isn't sufficient for var initialization
    }
}
Java

Output: compile time error

javac VarExamples.java

VarExamples.java:4: error: cannot infer type for local variable variable
        var variable;
            ^
  (cannot use 'var' on variable without initializer)
  
VarExamples.java:5: error: cannot infer type for local variable anotherVariable
        var anotherVariable = null;
            ^
  (variable initializer is 'null')
2 errors
Java

10. Var Exclusion in Lambda Expressions

var cannot be directly used in lambda expressions for implicit typing; explicit target types are required for lambda expressions.

public class VarExamples {

    public static void main(String[] args) {
        // Invalid use of var without explicit types in lambda expression
        var operation = (Integer a, Integer b) -> (a + b);
        System.out.println(operation.apply(2, 3));
    }
}
Java

Output: compile time error

javac VarExamples.java

VarExamples.java:5: error: cannot infer type for local variable operation
        var operation = (Integer a, Integer b) -> (a + b);
            ^
  (lambda expression needs an explicit target-type)
1 error
Java

11. Var Exclusion for Method Parameters and Return Type

var cannot be used to specify method parameters or return types explicitly.

public class VarExamples {

    // Invalid use of var for method return type
    var greetings() {
        return "Hello World";
    }

    // Invalid use of var for method parameter
    void customisedGreetings(var param) {
        System.out.println("Hello " + param);
    }

    public static void main(String[] args) {
        VarExamples obj = new VarExamples();
        var greetings = obj.greetings(); // Compilation error - var cannot be used for method return types
        obj.customisedGreetings(); // Compilation error - var cannot be used for method parameters
    }
}
Java

Output: compile time error

javac VarExamples.java

VarExamples.java:4: error: 'var' is not allowed here
    var greetings() {
    ^
VarExamples.java:9: error: 'var' is not allowed here
    void customisedGreetings(var param) {
                             ^
2 errors
Java


Things to Consider

Here are some things to consider when using var in Java:

  • Use var when the data type is obvious or redundant, such as when the value is a literal, a constructor call, or a method call that returns a specific type. For example, var name = "Alice"; or var list = new ArrayList<String>();.
  • Avoid using var when the data type is unclear or ambiguous, such as when the value is a null, a complex expression, or a method call that returns a generic type. For example, var x = null; or var y = foo();.
  • Use meaningful and descriptive variable names when using var, as they can help to convey the purpose and meaning of the variable. For example, var name = employee.getName(); or var age = person.getAge();.
  • Be consistent and follow the coding conventions and best practices when using var, as they can help to maintain the readability and quality of the code. For example, use var only for local variables.

FAQs

What is var in Java?

In Java, var is a type introduced for local variable type inference. It allows developers to declare variables without explicitly stating their data types. Instead, the compiler deduces the type from the assigned value.

Is var a keyword in Java?

No, var isn’t a keyword in Java but rather a reserved type name. This means var can be utilized as a variable name, method name, or package name, but it cannot serve as a class name, interface name, or enum name.

Can var be used for class fields, method parameters, or return types?

No, var is exclusively meant for local variables. It cannot be used for class fields, method parameters, or return types since they aren’t considered local variables.

Can var be used with generics, annotations, or modifiers?

Yes, var can be used with generics, annotations, or modifiers, provided they are applicable to local variables. For instance, using ‘final var x = 10;’ is acceptable.

Can var be used with primitive types, reference types, or lambda expressions?

Yes, var can be employed with any type of value assignable to a local variable, inclusive of primitive types, reference types, or lambda expressions.

When to use var in java?

Use var when the data type is evident or redundant, such as with literals, constructor calls, or method calls returning a specific type. For instance, ‘var age = 25;’ or ‘var customer = new Customer();’.

Are there situations where using var should be avoided in Java?

Avoid using var when the data type is unclear or ambiguous, such as with null, complex expressions, or method calls returning a generic type. For example, ‘var x = null;’ or ‘var flag = checkValidity();’.

Conclusion

In summary, Java var makes declaring variables shorter and more flexible. It helps keep code concise and easier to read. However, using it the wrong way might confuse things and cause compatibility problems. Learning how to use var in Java well keeps code neat and easy to work with, finding the sweet spot between brief code and clear, organized Java programs.

Learn More

#

Interested in learning more?

Check out our blog on Java Record: A New Way to Create Data Classes

Top Picks for Learning Java

Explore the recommended Java books tailored for learners at different levels, from beginners to advanced programmers.

Disclaimer: The products featured or recommended on this site are affiliated. If you purchase these products through the provided links, I may earn a commission at no additional cost to you.

1
Java: The Complete Reference
13th Edition

Java: The Complete Reference

  • All Levels Covered: Designed for novice, intermediate, and professional programmers alike
  • Accessible Source Code: Source code for all examples and projects are available for download
  • Clear Writing Style: Written in the clear, uncompromising style Herb Schildt is famous for
2
Head First Java: A Brain-Friendly Guide

Head First Java: A Brain-Friendly Guide

  • Engaging Learning: It uses a fun approach to teach Java and object-oriented programming.
  • Comprehensive Content: Covers Java's basics and advanced topics like lambdas and GUIs.
  • Interactive Learning: The book's visuals and engaging style make learning Java more enjoyable.
3
Modern Java in Action: Lambdas, streams, functional and reactive programming
2nd Edition

Modern Java in Action: Lambdas, streams, functional and reactive programming

  • Latest Java Features: Explores modern Java functionalities from version 8 and beyond, like streams, modules, and concurrency.
  • Real-world Applications: Demonstrates how to use these new features practically, enhancing understanding and coding skills.
  • Developer-Friendly: Tailored for Java developers already familiar with core Java, making it accessible for advancing their expertise.
4
Java For Dummies
8th Edition

Java For Dummies

  • Java Essentials: Learn fundamental Java programming through easy tutorials and practical tips in the latest edition of the For Dummies series.
  • Programming Basics: Gain control over program flow, master classes, objects, and methods, and explore functional programming features.
  • Updated Coverage: Covers Java 17, the latest long-term support release, including the new 'switch' statement syntax, making it perfect for beginners or those wanting to brush up their skills.

Add a Comment

Your email address will not be published.