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:

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 Use Not Recommended
When type is obvious When type becomes confusing
Makes code cleaner Reduces readability if overused

Example where var helps readability:

var studentMap = new HashMap<String, ArrayList<Integer>>();

🎯 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *