✍️ "Just because you can use var, doesn't mean you should."

☕ Short and Sweet Java Tip #5: Java's var Keyword

Introduced in Java 10, the var keyword lets you declare local variables without specifying the type explicitly:

var list = new ArrayList<String>();

Clean, right? But don't overdo it.

💡 When to Use var — ✅ Good Examples

✅ When the type is obvious from the right-hand side

var map = new HashMap<String, Integer>();
var user = new User("Sam", "Developer");

Clean, right? But don't overdo it.

💡 When to Use var — ✅ Good Examples

✅ When the type is obvious from the right-hand side

var map = new HashMap<String, Integer>();
var user = new User("Sam", "Developer");

✅ Cleaner ✅ No redundancy ✅ Still readable

✅ In enhanced for-loops:

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

It's concise and expressive.

🚫 When to Avoid var — Bad Examples

❌ When the type is not clear at all

var x = doSomething();  // What is x??

This slows down code understanding — especially for new devs or reviewers.

❌ With primitives where type matters

var num = 5; // Is it int? long? double?

It's easy to lose track of what's actually being declared.

🧠 Rule of Thumb

If the type is obvious and improves readability — use var.

If it hides intent — stick with the explicit type.

📌 Pro Tips

  • var works only for local variables, not fields, parameters, or return types.
  • var still creates a strongly typed variable — the compiler infers the type at compile time.
  • You can still use IDE shortcuts (Cmd + Hover or Ctrl + Hover) to view inferred types.

✅ Summary

None