🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #21

The var Keyword


The var Keyword

The var keyword was introduced in Java 10 (released in 2018).

The var keyword lets the compiler automatically detect the type of a variable based on the value you assign to it.

This helps you write cleaner code and avoid repeating types, especially for long or complex types.

For example, instead of writing int x = 5;, you can write:

Example

var x = 5;  // x is an int
System.out.println(x);

When using var, the compiler understands that 5 is an int.


Example with Different Types

Here are some examples showing how var can be used to create variables of different types, based on the values you assign:

Example

var myNum = 5;         // int
var myDouble = 9.98;   // double
var myChar = 'D';      // char
var myBoolean = true;  // boolean
var myString = "Hello"; // String

Important Notes

  1. var only works when you assign a value at the same time (you can't declare var x; without assigning a value):
var x; // Error
var x = 5;  // OK
  1. Once the type is chosen, it stays the same. See example below:
var x = 5;  // x is now an int
x = 10;     // OK - still an int
x =
9.99;   // Error - can't assign a double to an int

When to Use var

For simple variables, it's usually clearer to write the type directly (int, double, char, etc.).

But for more complex types, such as ArrayList or HashMap, var can make the code shorter and easier to read:

Example

// Without var
ArrayList<String> cars = new ArrayList<String>();

// With var
var cars = new ArrayList<String>();

Don't worry if the example above looks a bit advanced - you will learn more about these complex types later. For now, just remember that var was introduced in Java 10, and if you work with others, you might see it in their code - so it's good to know what it means.

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

The var Keyword – FAQs

Quick answers about learning The var Keyword in Java.

This free note from CodingNow 2.0 explains The var Keyword in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including The var Keyword, is 100% free with no signup required.
With focused practice, most students grasp The var Keyword in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now