CoreJava Java10

Java 10 – Create an Object Using var (Local Variable Type Inference)

Java 10 – Create an Object Using var (Local Variable Type Inference)

Java 10 introduced local variable type inference with the var keyword. Instead of writing the full class name on the left side of an assignment, you can write var and let the compiler infer the type from the right-hand side. This tutorial shows how to use var when creating a custom object.

What is var?

var is not a keyword that changes how Java works — it is a reserved type name. The compiler replaces it with the actual inferred type at compile time. The bytecode is identical to code written without var.

  • Only works for local variables (inside methods)
  • Cannot be used for fields, method parameters, or return types
  • The variable still has a fixed, static type — var is not like JavaScript's dynamic typing
  • The right-hand side must provide enough information to infer the type

Product.java

package com.java9r;

public class Product {

    private int    id;
    private String name;
    private double price;
    private int    quantity;

    public int    getId()       { return id; }
    public String getName()     { return name; }
    public double getPrice()    { return price; }
    public int    getQuantity() { return quantity; }

    public void setId(int id)             { this.id = id; }
    public void setName(String name)       { this.name = name; }
    public void setPrice(double price)     { this.price = price; }
    public void setQuantity(int quantity)  { this.quantity = quantity; }

    @Override
    public String toString() {
        return String.format("Product{id=%d, name='%s', price=%.1f, qty=%d}",
                             id, name, price, quantity);
    }
}

Java10CreateObjectUsingVar.java

package com.java9r;

public class Java10CreateObjectUsingVar {

    public static void main(String[] args) {

        // Without var (Java 9 and earlier)
        Product productOld = new Product();
        productOld.setId(99);
        productOld.setName("Old Way");

        // With var (Java 10+) — compiler infers type as Product
        var product = new Product();
        product.setId(100);
        product.setName("Product 1");
        product.setPrice(55.2);
        product.setQuantity(20);

        System.out.println("Product Details");
        System.out.println("Id:       " + product.getId());
        System.out.println("Name:     " + product.getName());
        System.out.println("Price:    " + product.getPrice());
        System.out.println("Quantity: " + product.getQuantity());

        // var also works with constructors that take parameters
        var another = new Product();
        another.setId(101);
        another.setName("Product 2");
        another.setPrice(120.5);
        another.setQuantity(5);

        System.out.println("\nAnother Product: " + another);
    }
}

Output

Product Details
Id:       100
Name:     Product 1
Price:    55.2
Quantity: 20

Another Product: Product{id=101, name='Product 2', price=120.5, qty=5}

var – What is and isn't allowed

// ALLOWED — local variable with clear right-hand side type
var product  = new Product();
var price    = 99.99;
var name     = "Laptop";
var count    = 10;

// NOT ALLOWED — compiler cannot infer type
var x;                  // no initializer
var y = null;           // null has no type
var z = {1, 2, 3};     // array initializer without new

// NOT ALLOWED — not a local variable
class Example {
    var field = new Product();  // fields cannot use var

    var getProduct() {          // return types cannot use var
        return new Product();
    }

    void process(var p) {}     // parameters cannot use var
}

var with Other Types

import java.util.*;

var list = new ArrayList<String>();    // inferred as ArrayList<String>
list.add("Java");
list.add("Python");

var map = new HashMap<String, Integer>();   // inferred as HashMap<String, Integer>
map.put("Java", 1);

var sb = new StringBuilder();   // inferred as StringBuilder
sb.append("Hello").append(" World");

System.out.println(list);
System.out.println(map);
System.out.println(sb);

var vs Explicit Type Declaration

Aspect Explicit Type var
Readability Always clear from the declaration Type visible only from right-hand side
Verbosity More verbose with long type names Shorter, especially with generics
Type safety Static type, compile-time checked Same — still statically typed
IDE support Full Full (IDE shows inferred type on hover)
Java version All versions Java 10+

Summary

Java 10's var reduces boilerplate by letting the compiler infer local variable types from the initializer expression. When you write var product = new Product(), the compiler treats product exactly as if you had written Product product = new Product(). Use var when the type is obvious from the right-hand side and when it genuinely reduces noise. Avoid it when the right-hand side doesn't make the type clear, as that hurts readability.

Topics: CoreJava Java10
← Newer Post Older Post →