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

ExampleInferred Type
var name = "John";String
var age = 25;int
var price = 5.99;double
var active = true;boolean

🚫 Rules and Restrictions for var

RuleAllowed?
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:

var x; // Error ❌

❌ Cannot assign null without type:

var data = null; // Error ❌

❌ Not allowed as method return type:

var getValue() { // Error ❌
return 10;
}

🧠 Good Use Case Example



βœ” Best Practices

Good UseNot Recommended
When type is obviousWhen type becomes confusing
Makes code cleanerReduces readability if overused

Example where var helps readability:



🎯 Summary

  • var helps 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.

You may also like...