Java var
✅ var Keyword in Java
The var keyword was introduced in Java 10 to allow local variable type inference, meaning Java will automatically detect the data type based on the value assigned.
👉 You do NOT specify the type, Java determines it for you.
🔹 Example
🔍 How Java Infers Types
| Example | Inferred Type |
|---|---|
var name = "John"; |
String |
var age = 25; |
int |
var price = 5.99; |
double |
var active = true; |
boolean |
🚫 Rules and Restrictions for var
| Rule | Allowed? |
|---|---|
| Must be initialized at declaration | ✔ Required |
| Can be used only in local variables (inside methods) | ✔ Yes |
| Cannot be used for class fields / instance variables | ❌ No |
Cannot assign null without a type |
❌ No |
| Cannot be used in method parameters or return types | ❌ No |
📌 Examples of Invalid Use
❌ No value means type cannot be inferred:
❌ Cannot assign null without type:
❌ Not allowed as method return type:
🧠 Good Use Case Example
✔ Best Practices
| Good Use | Not Recommended |
|---|---|
| When type is obvious | When type becomes confusing |
| Makes code cleaner | Reduces readability if overused |
Example where var helps readability:
🎯 Summary
-
varhelps write shorter, cleaner code. -
It is used only for local variables inside methods.
-
Type must be obvious from the assigned value.
-
Feature available from Java 10 and later.
