Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Java var: Let Java Infer the Type

var flight = "BA-131" is a String, var bags = 2 an int, var tags = new ArrayList<String>() an ArrayList<String>. var total; and var gate = null won't compile, kg = "heavy" is still a type error, and var works in for-each loops and record patterns.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Declare local variables with var and say which type Java picks
  • Explain why var needs a value that has a type
  • Show that the type is fixed once it's chosen
  • Use var in a for-each loop and in a record pattern

Before you start

  • Java variables, keywords and naming
  • Java record patterns

Normally you write a variable's type yourself: String, int and so on. With var, Java reads the value on the right and works out the type on its own.

The type comes from the value

package org.studyeasy.s05l05;

import java.util.ArrayList;

public class Ex01_VarBasics {
    public static void main(String[] args) {
        // Explicit: you write the type on the left
        String owner = "Hana";
        int kg = 21;

        // var: Java reads the type from the value on the right
        var flight = "BA-131";                  // String
        var bags = 2;                           // int
        var tags = new ArrayList<String>();     // ArrayList<String>
        tags.add("BLR-1042");
        tags.add("DEL-7710");

        System.out.println(owner + ", " + kg + " kg, " + flight);
        System.out.println(bags + " bags: " + tags);
    }
}
Hana, 21 kg, BA-131
2 bags: [BLR-1042, DEL-7710]
Java reads each value and stamps its type on the variable. "BA-131" is text in quotes, so flight is a String. 2 is a whole number, so bags is an int. new ArrayList of String gives tags the type ArrayList of String. var flight = "BA-131"; var bags = 2; var tags = new ArrayList<String>(); String flight int bags ArrayList<String> tags Java reads the value
The type is still there; Java writes it for you.

Text in quotes is a String, a whole number is an int, and for new the type comes straight from what you create. Because tags is an ArrayList of String, add takes a String. Explicit and var variables mix freely.

No value, no type

var total;          // cannot infer type for local variable total
var gate = null;    // cannot infer type: the initializer is null
var total = 0;      // fine: an int

With nothing on the right, there's nothing to read, so the compiler says cannot infer type for local variable total (var needs an initializer). null has no type of its own, so it fails the same way. Give it a value like 0 and total becomes an int. var always needs a value, and that value must have a type.

Chosen once, then fixed

var kg = 21;                       // Java picks int from the 21
System.out.println("Checked in: " + kg + " kg");

kg = 23;                           // another int: fine
System.out.println("After weighing: " + kg + " kg");

var owner = "Hana";                // a String from now on
System.out.println(owner.toUpperCase());
Checked in: 21 kg
After weighing: 23 kg
HANA

Java decides the type once, on the first line. 23 is another int, so only the value changes. kg = "heavy"; is a String going into an int variable: incompatible types: String cannot be converted to int. owner is a String, so toUpperCase works. After that first line, it's exactly as if you had written the type yourself. var isn't dynamic typing.

var in a for-each loop

var tags = List.of("BLR-1042", "DEL-7710", "LHR-0031");

// tag is a String: Java takes it from List<String>
for (var tag : tags) {
    System.out.println(tag.toLowerCase());
}

var count = tags.size();    // an int, and it stays an int
System.out.println(count + " tags");
blr-1042
del-7710
lhr-0031
3 tags

The list is a List<String>, so Java stamps String onto tag on every pass, and toLowerCase works. size() returns an int, so count is an int. Inside the loop, int first = tag; fails, because tag is a String.

var in a record pattern

record Flight(String code, String to) {}
record Bag(String owner, Flight flight, int kg) {}

Object scan = new Bag("Hana", new Flight("BA-131", "London"), 21);

// Explicit types: every type written by hand
if (scan instanceof Bag(String owner, Flight flight, int kg)) {
    System.out.println(owner + ": " + kg + " kg");
}

// var: the record already says the types
if (scan instanceof Bag(var owner, var flight, var kg)) {
    System.out.println(owner + ": " + kg + " kg");
}
Hana: 21 kg
Hana: 21 kg

In a record pattern, there's nothing to guess. The record header already names every type, so var copies them: owner is a String, flight a Flight, kg an int. You still need one slot per component; Bag(var owner, var kg) is two of three and won't compile.

Recap

WhereThe type comes from
var flight = "BA-131";the value on the right
for (var tag : tags)the list's element type
Bag(var owner, var flight, var kg)the record header
var total; or var gate = null;nowhere: compile error

Once chosen, the type is fixed. Java reads the value; you keep the type.

Keep going in Java · 21 of 79

Previous
Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
Next post
Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • The type comes from the value
  • No value, no type
  • Chosen once, then fixed
  • var in a for-each loop
  • var in a record pattern
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.