DEV Community

Cover image for Var Type Identifier/Keyword of Java
Aditya
Aditya

Posted on

Var Type Identifier/Keyword of Java

Java 10 added the var keyword, which allows you to declare local variables without explicitly defining their type. Instead, the compiler deduces the type from the variable's assigned value.

var message = "Hello, World!";  // Compiler infers type as String
var count = 42;                // Compiler infers type as int
Enter fullscreen mode Exit fullscreen mode

Key Points About var:

  1. var can only be used for local variables (e.g., within methods, loops, or blocks).
  2. It cannot be used for method parameters, constructor parameters ,return types or fields (class-level variables).
  3. The type of the variable is inferred at compile-time, not runtime.
  4. var is not a reserved keyword but a reserved type name, meaning it cannot be used as an identifier in contexts where a type is expected.
  5. Java remains statically typed; var does not introduce dynamic typing.

Example Proper usage of Var

public class VarExample {
    public static void main(String[] args) {
        var message = "Hello, Java 10";   // String inferred
        var numbers = List.of(1, 2, 3);   // List<Integer> inferred

        for (var number : numbers) {
            System.out.println(number);
        }

        var map = new HashMap<String, Integer>();
        map.put("Age", 25);
    }
}
Enter fullscreen mode Exit fullscreen mode

Points to Ponder

var number = 3.12; 
// What is the type of number?  
Enter fullscreen mode Exit fullscreen mode

Answer: The compiler infers number as double, not float.

Why double and Not float?

  • In Java, decimal literals are of type double by default, unless you explicitly specify otherwise.
  • To assign a float, you must append an f or F to the literal.

for example:

var number = 3.12f;  // Now the type is float
Enter fullscreen mode Exit fullscreen mode

Some Interesting Facts about var Keyword

  • var is Not Reserved Keyword
  • var can't be used without initialization Unlike regular variables, var must be initialized at declaration because the compiler needs a type to infer.

❌ Invalid Example:

var x;  // ❌ Compilation error: Cannot use 'var' without an initializer
Enter fullscreen mode Exit fullscreen mode

✅ Valid Example:

var x = 42;  // ✅ Compiler infers int
Enter fullscreen mode Exit fullscreen mode

  • var is Just Syntax Sugar – No Performance Overhead The Java compiler erases var during compilation and replaces it with the inferred type. At runtime, there is no difference in performance between var and explicit types.

📌 Example:

var list = new ArrayList<String>();
Enter fullscreen mode Exit fullscreen mode

✅ After compilation, it becomes:

ArrayList<String> list = new ArrayList<>();
Enter fullscreen mode Exit fullscreen mode

  • var can't have a null Without Explicit Type The compiler cannot infer a type from null, so var must have an explicit value.

❌ Invalid Example:

var x = null;  // ❌ Compilation error: Cannot infer type from 'null'
Enter fullscreen mode Exit fullscreen mode

✅ Valid Example:

var x = (String) null;  // ✅ Explicit cast allows inference
Enter fullscreen mode Exit fullscreen mode

🎯 Conclusion:

The var keyword is a powerful feature that makes Java code more concise while preserving static typing. However, it should be used carefully to maintain code readability and avoid ambiguity.

End

If you have reached till the end, Thanks for giving this article a read.

If you liked this article, drop a like or comment ❤ or maybe share it in your community :) , You can also drop me a follow on X 🐤 or Linked In 👨‍🏫

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more