What is var in Java?
var, introduced in Java 10, is a reserved type name that allows the compiler to infer the data type based on the right-hand side initializer. It is used for local variables to reduce boilerplate code while keeping Java strongly typed.
For example:
// Instead of explicitly writing:
String name = "Rahul";
// You can write:
var name = "Rahul"; // Compiler infers String
Similarly,
var age = 25; // Inferred as int
var price = 99.99; // Inferred as double
var isActive = true; // Inferred as boolean
Rules and Characteristics of var in Java
There are the following core rules of var in Java that you must keep in mind when using it.
- Not a Data Type: var is a reserved type name used as a placeholder, not an actual data type.
- Compile-Time Type Inference: The compiler determines the variable’s exact type at compile time, not at runtime.
- Preserves Static Typing: Once a type is inferred, it cannot be changed later. For example, assigning a String to
var age = 25;causes a compile-time error. - Scope Restriction: You can use var only for local variables inside methods, constructors, and initializer blocks and for loop variables. You cannot use it for class fields, method parameters, or return types.
- Initialization Required: A var variable must have an initializer at declaration so the compiler can infer its type. For example,
var x;is illegal.
How Does var Work?
When the Java compiler encounters:
var age = 25;
It inspects the right-hand value (25) and internally compiles it as:
int age = 25;
Similarly:
var salary = 50000.75;
Becomes:
double salary = 50000.75;
Once the compiler determines the type, it is fixed. The inferred type never changes at runtime.
Problem Statement
Write a Java program that stores and displays an employee’s information using var for all local variable declarations instead of explicitly specifying the variable types.
The program should store the following information:
- Employee ID
- Employee Name
- Age
- Department
- Salary
- Years of Experience
- Permanent Employee Status
Use var for each local variable declaration, and initialize every variable with an appropriate value. The program should then display all the stored employee information.
Learning Objectives
After completing this exercise, you will be able to:
- Understand what var means in Java.
- Understand local variable type inference.
- Understand how the Java compiler infers a variable’s type from its initializer at compile time.
- Use var correctly for local variable declarations.
- Understand that var is not a data type.
- Understand that a variable declared with var still has a specific, fixed type after compilation.
- Distinguish between var and explicitly declared variable types such as int, String, double, and boolean.
- Identify situations where var can and cannot be used.
- Write concise and readable Java code using var appropriately.
Input Format
No user input is required. Initialize all values directly in the program using hardcoded local variables.
Output Format
Display the employee information as a well-formatted console report.
========== Employee Information ========== Employee ID : 101 Employee Name : Rahul Sharma Age : 25 Department : Software Development Salary : 55000.75 Experience : 2.5 Permanent Employee : true ==========================================
Constraints
- Use var for all local variables.
- Do not declare explicit types on the left-hand side of local variable declarations. For example, use
var name = "Alex";instead ofString name = "Alex";. - Every var variable must be assigned a value at the time of declaration.
- The program must compile successfully on Java 10 or higher without any compilation errors.
Expected Solution Approach
Start ↓ Declare and initialize local variables using 'var' ↓ Process / Format employee data ↓ Display the employee report ↓ End
Java Program: Displaying Employee Information Using var
This program demonstrates local variable type inference in Java by declaring and initializing various data types using the var keyword. The compiler automatically infers types like int, String, double, and boolean based on the assigned values.
/**
* Program: Employee Information System using 'var'
* Description: Demonstrates local variable type inference introduced in Java 10 (JEP 286).
* Highlights how the Java compiler automatically infers types at compile time.
*/
public class EmployeeInformationUsingVar {
public static void main(String[] args) {
// ==========================================
// Local Variable Type Inference Examples
// ==========================================
// Compiler infers 'int' from integer literal 101
var employeeId = 101;
// Compiler infers 'String' from text literal "Rahul Sharma"
var employeeName = "Rahul Sharma";
// Compiler infers 'int' from integer literal 25
var age = 25;
// Compiler infers 'String' from text literal "Software Development"
var department = "Software Development";
// Compiler infers 'double' from floating-point literal 55000.75
var salary = 55000.75;
// Compiler infers 'double' from floating-point literal 2.5
var experience = 2.5;
// Compiler infers 'boolean' from boolean literal true
var isPermanentEmployee = true;
// ==========================================
// Output / Formatting Section
// ==========================================
System.out.println("========== Employee Information ==========\n");
System.out.println("Employee ID : " + employeeId);
System.out.println("Employee Name : " + employeeName);
System.out.println("Age : " + age);
System.out.println("Department : " + department);
System.out.println("Salary : $" + salary);
System.out.println("Experience (Years) : " + experience);
System.out.println("Permanent Employee : " + isPermanentEmployee);
System.out.println("\n==========================================");
}
}Expected Output:
========== Employee Information ========== Employee ID : 101 Employee Name : Rahul Sharma Age : 25 Department : Software Development Salary : $55000.75 Experience (Years) : 2.5 Permanent Employee : true ==========================================
Step-by-Step Code Explanation
Step 1: Class Declaration
We have defined a standard public class named EmployeeInformationUsingVar. In Java, every executable code unit must reside inside a class wrapper, and the file name must match the public class name (EmployeeInformationUsingVar.java).
public class EmployeeInformationUsingVar {Step 2: Entry Point Method
This is the standard entry point where the Java Virtual Machine (JVM) begins program execution.
public static void main(String[] args) {The method signature uses standard explicit modifiers (public static void). Note that var cannot be used as a parameter type (e.g., var[] args is illegal).
Step 3: Local Variable Declarations with Type Inference
In the program code, we have defined seven local variables using var instead of explicit types.
var employeeId = 101; var employeeName = "Rahul Sharma"; var age = 25; var department = "Software Development"; var salary = 55000.75; var experience = 2.5; var isPermanentEmployee = true;
Technical Details & Compiler Behavior:
var employeeId = 101;— The right-hand side 101 is an integer literal. javac infers employeeId to be of primitive type int.var employeeName = "Rahul Sharma";— The string literal “Rahul Sharma” causes the compiler to infer java.lang.String.var age = 25;— The integer literal 25 causes the compiler to infer primitive int.var department = "Software Development";— The string literal causes the compiler to infer java.lang.String.var salary = 55000.75;— A floating-point literal with a decimal point and no suffix is of type double, so the compiler infers salary as the primitive type double.var experience = 2.5;— 2.5 is a floating-point literal with no suffix, so it is of type double. Therefore, experience is inferred as the primitive type double.var isPermanentEmployee = true;— The boolean literal true causes the compiler to infer primitive boolean.
Crucial Rule: Every single variable above is initialized on the exact same line as its declaration. This fulfills the strict rule that var requires an immediate initializer so the compiler can determine its type at compile time.
For example:
var employeeId = 101; // Valid
But:
var employeeId; // Compile-time error
The compiler cannot infer a type when no initializer is provided.
Step 4: Printing Header and Output Formatting
This statement outputs the top header bar to System.out (standard output) with a trailing newline character (\n) for spacing.
System.out.println("========== Employee Information ==========\n");Step 5: Data Output and String Concatenation
The + operator performs string concatenation. For primitive variables (employeeId, age, salary, experience, isPermanentEmployee), Java automatically invokes implicit string conversion (via String.valueOf(…)) before appending them to the output label.
System.out.println("Employee ID : " + employeeId);
System.out.println("Employee Name : " + employeeName);
System.out.println("Age : " + age);
System.out.println("Department : " + department);
System.out.println("Salary : $" + salary);
System.out.println("Experience (Years) : " + experience);
System.out.println("Permanent Employee : " + isPermanentEmployee);
Step 6: Printing Footer
This statement prints a closing divider bar to finalize the report layout.
System.out.println("\n==========================================");Step 7: Method and Class Closing
The first closing curly brace closes the main method block, while the second curly close brace closes EmployeeInformationUsingVar class definition, ending execution gracefully.
} }
Technical Summary
- Compile-Time Replacement: In the generated .class bytecode, there is zero record of the keyword var. The compiler replaces var with concrete types, such as int, String, double, boolean.
- Zero Runtime Performance Overhead: Because type inference happens at compile time, var does not introduce runtime type-inference overhead. Using var provides convenience for the programmer without any execution time performance penalty.
- Still Statically Typed: Java remains a statically typed language. Once the compiler infers a type, that type is fixed.
Common Beginner Mistakes with var
- Thinking var is a new data type: var is not a data type; it is a feature for local variable type inference. The compiler replaces it with the inferred type during compilation.
- Declaring var without initialization: Writing var x; causes a compilation error because the compiler needs an initializer expression to infer the type.
- Attempting to initialize var with null: Writing var obj = null; fails to compile because the compiler cannot infer a specific reference type from null.
- Using var for class fields, method parameters, or return types: var is restricted exclusively to local variables (inside methods, constructors, and initializer blocks).
- Assuming var makes Java dynamically typed: Java remains strictly and statically typed. The variable’s type is determined at compile time, not at runtime, and cannot be changed later.
Follow-Up Coding Challenge: The var Refactoring Bug Hunt
Scenario
A junior developer attempted to use var across an entire Java program. However, their code is completely broken and fails to compile because they misunderstood where and how var can be used.
Your Task
- Identify all 5 compilation errors in the buggy code below.
- Explain why each error occurs based on Java’s type inference rules.
- Write the corrected version of the program so it compiles and runs successfully.
The Buggy Code
public class EmployeeBonusCalculator {
// Bug 1: Class-level field declaration
private var defaultBonusRate = 0.10;
// Bug 2: Method parameter
public double calculateTotalSalary(var baseSalary, var bonusRate) {
// Bug 3: Declaration without initialization
var total;
// Bug 4: Initialized with null
var departmentName = null;
total = baseSalary + (baseSalary * bonusRate);
// Bug 5: Type reassignment
var employeeStatus = "Active";
employeeStatus = 1; // Reassigning an integer to a String variable
return total;
}
}Solution & Detailed Analysis
1. Error Identification & Explanation
1. private var defaultBonusRate = 0.10;
var is not allowed for fields because it can only be used for local variables inside methods, constructors, or initializer blocks.
2. public double calculateTotalSalary(var baseSalary, var bonusRate)
var is not allowed for method parameters because method parameters require explicit types so the compiler can enforce API contracts.
3. var total;
Missing initializer: var requires an immediate initializer at declaration time to deduce its type.
4. var departmentName = null;
Here, the initializer is null. Since null has no type, the compiler cannot infer what kind of object departmentName should be.
5. employeeStatus = 1;
Incompatible types: The compiler inferred employeeStatus as String. Because Java is statically typed, you cannot reassign an int to a String variable.
Corrected Java Code
/**
* Refactored EmployeeBonusCalculator
* Demonstrates proper usage of 'var' alongside explicit Java types.
*/
public class EmployeeBonusCalculator {
// Fixed: Fields MUST use explicit types
private double defaultBonusRate = 0.10;
// Fixed: Method parameters MUST use explicit types
public double calculateTotalSalary(double baseSalary, double bonusRate) {
// Fixed: Initialized with explicit String reference type (or direct value)
String departmentName = null;
// Fixed: Initialized at declaration using 'var'
var total = baseSalary + (baseSalary * bonusRate);
// Fixed: Keeping String type consistent
var employeeStatus = "Active";
employeeStatus = "Promoted"; // Valid: Assigning another String
return total;
}
public static void main(String[] args) {
var calculator = new EmployeeBonusCalculator(); // Valid: Local variable
var finalSalary = calculator.calculateTotalSalary(50000.0, 0.10); // Valid: Inferred as double
System.out.println("Final Calculated Salary: $" + finalSalary);
}
}Here is the console output when executing the corrected EmployeeBonusCalculator program:
Final Calculated Salary: $55000.0
How the Calculation Works
- baseSalary = 50000.0 (inferred as double)
- bonusRate = 0.10 (inferred as double)
- Calculation: $50000.0 + (50000.0 * 0.10) = 50000.0 + 5000.0 =$ 55000.0
- var finalSalary infers the result of calculator.calculateTotalSalary(…) as a double and prints it to the console.






