✅ What is a Variable in Java?
A variable is a named memory location that stores a value. Variables allow programs to store, retrieve, and manipulate data.
⚡ Syntax of Variable Declaration
data_type variableName = value;
✅ Types of Variables in Java
Java variables can be categorized based on where they are declared and how they behave:
Variable Type | Description |
---|---|
Instance Variables | Declared inside a class but outside any method. Each object has its own copy. |
Static Variables (Class Variables) | Declared with the static keyword inside a class but outside methods. Shared across all instances of the class. |
Local Variables | Declared inside a method or block. Only accessible within that method/block. |
Final Variables (Constants) | Declared with the final keyword. Value cannot be changed once assigned. |
1️⃣ Instance Variables
An instance variable is tied to a specific object. Each object created from the class has its own copy.
Example:
public class Car {
String color; // Instance variable
public Car(String color) {
this.color = color;
}
public void displayColor() {
System.out.println("Car color: " + color);
}
}
public class TestCar {
public static void main(String[] args) {
Car car1 = new Car("Red");
Car car2 = new Car("Blue");
car1.displayColor(); // Output: Car color: Red
car2.displayColor(); // Output: Car color: Blue
}
}
2️⃣ Static Variables (Class Variables)
A static variable belongs to the class, not any particular object. All objects share the same static variable.
Example:
public class Counter {
static int count = 0; // Static variable
public Counter() {
count++; // Increments shared count
}
public static void displayCount() {
System.out.println("Total objects created: " + count);
}
}
public class TestCounter {
public static void main(String[] args) {
new Counter();
new Counter();
Counter.displayCount(); // Output: Total objects created: 2
}
}
3️⃣ Local Variables
A local variable is declared inside a method and accessible only within that method.
Example:
public class LocalVariableExample {
public void displaySum() {
int a = 5; // Local variable
int b = 10;
int sum = a + b;
System.out.println("Sum is: " + sum);
}
public static void main(String[] args) {
LocalVariableExample obj = new LocalVariableExample();
obj.displaySum(); // Output: Sum is: 15
}
}
👉 Local variables must be initialized before use.
4️⃣ Final Variables (Constants)
A variable declared as final
cannot be modified after initialization.
Example:
public class FinalVariableExample {
final int DAYS_IN_WEEK = 7; // Final variable
public void displayDays() {
System.out.println("Days in a week: " + DAYS_IN_WEEK);
}
public static void main(String[] args) {
FinalVariableExample obj = new FinalVariableExample();
obj.displayDays(); // Output: Days in a week: 7
// obj.DAYS_IN_WEEK = 10; // ❌ Compilation error: Cannot assign a value to final variable
}
}
✅ Variable Naming Naming Conventions Rules
Proper naming conventions help make the code readable, maintainable, and consistent with community standards
1️⃣ Rules for Variable Names
- Can contain letters, digits, underscores
_
, and dollar signs$
. - Must not start with a digit.
- Cannot use reserved keywords (e.g.,
int
,class
,public
). - Should be meaningful and descriptive.
Valid Examples:
int age;
double salaryAmount;
String userName;
boolean isAvailable;
✅Recommended Naming Style (Camel Case)
Type | Example |
---|---|
Instance / Local Variable | userName , totalAmount , isAvailable |
Class Variable (Static) | Usually written the same as instance variables, but constants use uppercase letters and underscores: MAX_VALUE |
✅ Variable Scope and Lifetime
Variable Type | Scope | Lifetime |
---|---|---|
Instance Variable | Throughout object lifetime | Exists as long as the object exists |
Static Variable | Throughout class lifetime | Exists as long as the class is loaded |
Local Variable | Within method/block | Temporary – destroyed after method execution |
Final Variable | Same as its type (instance, local, or static) | Fixed value once initialized |
✅ Difference Between Instance Variables and Class Variables in Java
➔ Instance Variables
An instance variable is a variable declared inside a class but outside any method, constructor, or block.
Each object (instance) of the class has its own copy of the instance variable.
✅ Example of Instance Variables
public class Car {
String color; // Instance variable
public Car(String color) {
this.color = color;
}
public void displayColor() {
System.out.println("Car color: " + color);
}
}
public class TestCar {
public static void main(String[] args) {
Car car1 = new Car("Red");
Car car2 = new Car("Blue");
car1.displayColor(); // Output: Car color: Red
car2.displayColor(); // Output: Car color: Blue
}
}
👉 Key Points:
- Each
Car
object has its owncolor
. - Changing
car1.color
does not affectcar2.color
.
➔ Class Variables (Static Variables)
A class variable is declared using the static
keyword inside a class but outside any method.
There is only one copy shared by all objects of the class.
✅ Example of Class Variables
public class Counter {
static int count = 0; // Class (static) variable
public Counter() {
count++; // Increment shared count
}
public static void displayCount() {
System.out.println("Objects created: " + count);
}
}
public class TestCounter {
public static void main(String[] args) {
new Counter();
new Counter();
new Counter();
Counter.displayCount(); // Output: Objects created: 3
}
}
👉 Key Points:
count
is shared across all instances.- Every time a
Counter
object is created, the samecount
variable is updated.
✅ Comparison Table
Feature | Instance Variable | Class (Static) Variable |
---|---|---|
Belongs to | Instance of class | Class itself |
Memory Allocation | Each object has its own copy | One shared copy in memory |
Access Modifier | Accessed via object | Accessed via class or object |
Example | car1.color | Counter.count |
Use Case | Stores object-specific properties | Tracks class-level information (e.g., object count) |
Since Java 10, you can use
var
instead of explicitly specifying a type, allowing the compiler to automatically infer the variable’s type based on the assigned value.
🚀 Java 10 Local Variable Type Inference (var
)
Java 10 introduced an exciting new feature called Local Variable Type Inference using the var
keyword. This allows the compiler to automatically infer the type of a local variable based on the value it is assigned, making the code cleaner and easier to read
✅ What Is var
in Java 10?
- The
var
keyword tells the compiler to infer the variable type automatically from the right-hand side expression. - It helps reduce boilerplate code by removing the need to explicitly write the type when it is obvious from the context.
- Important Restriction:
var
can only be used for local variables inside methods, not for instance variables, method parameters, or return types.
✅ How Does var
Work?
The compiler analyzes the type of the assigned value and infers the correct type during compile-time.
Syntax:
var variableName = value;
1️⃣ Simple Example:
public class VarExample {
public static void main(String[] args) {
var num = 10; // Inferred as int
var message = "Hello Java"; // Inferred as String
var pi = 3.14; // Inferred as double
System.out.println("Number: " + num);
System.out.println("Message: " + message);
System.out.println("Pi: " + pi);
}
}
👉 The compiler infers:
num
→int
message
→String
pi
→double
2️⃣ Working with Collections:
import java.util.ArrayList;
public class VarWithCollection {
public static void main(String[] args) {
var list = new ArrayList<String>(); // Inferred as ArrayList<String>
list.add("Apple");
list.add("Banana");
for (var item : list) { // Inferred as String
System.out.println(item);
}
}
}
✅ Why Is Type Inference Useful?
- ✅ Reduces Boilerplate Code: No need to explicitly write repetitive types.
Less Boilerplate Code
Before Java 10:
String message = "Hello, World!";
int number = 100;
With var
:
var message = "Hello, World!";
var number = 100;
- ✅ Improves Readability: Especially when working with complex generic types.
Example Before Type Inference :
HashMap<String, List<Integer>> map = new HashMap<>();
Example With Type Inference:
var map = new HashMap<String, List<Integer>>();
- ✅ Keeps Type Safety: Unlike dynamically typed languages (e.g., JavaScript), Java ensures that the type is determined at compile time.
⚠️ Limitations of Type Inference
Limitation | Reason |
---|---|
Cannot be used without initialization | Compiler cannot infer the type if no value is provided. |
Cannot be used for method parameters or return types | Method signatures must be explicit for readability and clarity. |
Limited to local variables | Fields and method parameters still require explicit types. |
✅Cannot be used without initialization
var number; // ❌ Compilation Error – must initialize the variable
✅Cannot be used for method parameters or return types:
public var getValue() { // ❌ Invalid<br>return 10;<br>}
✅Can only be used in local scope (inside methods, loops, blocks), not as fields in a class.
public class VarExample {
// int number = 10; // Valid: Explicit type as class field
// var number = 10; // ❌ Compilation Error: Cannot use 'var' here
public void demonstrateVar() {
var message = "Hello, Type Inference"; // ✅ Local variable using 'var'
var count = 100; // ✅ Local variable with inferred int type
System.out.println(message); // Output: Hello, Type Inference
System.out.println(count); // Output: 100
}
public static void main(String[] args) {
VarExample example = new VarExample();
example.demonstrateVar();
}
}
🎯 Summary
Variables are the building blocks of Java programs. Understanding their types, scope, lifetime, and usage helps you write clean, maintainable, and efficient code. Proper use of instance, static, local, and final variables gives flexibility while controlling data flow within your program.