In the previous article, we explored Java Member Access Modifiers (public, private, protected, and default).
In this article, we'll focus on one of the most misunderstood topics in Java:
finalvariables
Many developers know that final means "cannot be changed," but they often get confused about:
- When should a final variable be initialized?
- Why do final instance variables require explicit initialization?
- What happens if a final local variable isn't initialized?
- Can method parameters be final?
- What default values does the JVM provide?
These are also common Java interview questions.
By the end of this guide, you'll have a clear understanding of final instance variables, final static variables, final local variables, and final formal parameters.
What Are final Variables?
A variable declared with the final modifier can be assigned only once.
After it has been assigned a value, it cannot be reassigned.
Example:
public class Customer {
public static void main(String[] args) {
final int customerId = 101;
// customerId = 102; // Compile-time error
System.out.println(customerId);
}
}
Output
101
Step-by-Step Explanation
Step 1
The variable customerId is declared as final.
Step 2
It is initialized with the value 101.
Step 3
Any attempt to assign another value results in a compile-time error.
Step 4
The value remains unchanged throughout its lifetime.
Why Do We Need final Variables?
The final keyword helps us create immutable values.
Some examples include:
- Employee ID
- Invoice Number
- PAN Number
- Aadhaar Number
- Account Number
These values should never change after initialization.
Example:
class Employee {
final int employeeId = 1001;
}
Types of final Variables
Java allows the final modifier on four kinds of variables:
| Variable Type | Can Be final? |
|---|---|
| Instance Variable | ✅ |
| Static Variable | ✅ |
| Local Variable | ✅ |
| Method Parameter | ✅ |
We'll examine each one separately.
Final Instance Variables
An instance variable belongs to an object.
Each object gets its own copy.
Example:
class Customer {
int customerId;
}
If two objects are created:
Customer customerOne = new Customer();
Customer customerTwo = new Customer();
Both objects have independent copies of customerId.
JVM Default Values
For normal instance variables, the JVM automatically assigns default values.
Example:
class Product {
int quantity;
public static void main(String[] args) {
Product product = new Product();
System.out.println(product.quantity);
}
}
Output
0
Step-by-Step Explanation
Step 1
quantity is an instance variable.
Step 2
No explicit initialization is provided.
Step 3
The JVM assigns the default value 0.
Step 4
The object prints 0.
Important Rule
If an instance variable is declared as final, the JVM does not provide a default value.
You must initialize it explicitly.
Incorrect example:
class Product {
final int quantity;
}
Compile-Time Error
variable quantity might not have been initialized
Where Can We Initialize a Final Instance Variable?
Initialization must happen before the constructor completes.
There are three valid places.
1. At the Time of Declaration
class Product {
final int quantity = 10;
}
✔ Compiles successfully.
2. Inside an Instance Initializer Block
class Product {
final int quantity;
{
quantity = 10;
}
}
✔ Compiles successfully.
3. Inside the Constructor
class Product {
final int quantity;
Product() {
quantity = 10;
}
}
✔ Compiles successfully.
Incorrect Initialization
class Product {
final int quantity;
void updateQuantity() {
quantity = 20;
}
}
Compile-Time Error
cannot assign a value to final variable quantity
Why?
The object has already been created.
The initialization window has closed.
Final Static Variables
A static variable belongs to the class.
Only one copy exists regardless of the number of objects.
Example:
class Employee {
static int employeeCount;
}
Every object shares the same variable.
JVM Default Values
Normal static variables receive default values.
Example:
class Employee {
static int employeeCount;
public static void main(String[] args) {
System.out.println(employeeCount);
}
}
Output
0
Important Rule
If a static variable is declared as final, it must be initialized explicitly.
Incorrect:
class Employee {
static final int employeeCount;
}
Compile-Time Error
variable employeeCount might not have been initialized
Where Can We Initialize a Final Static Variable?
Initialization must happen before class loading completes.
Only two locations are allowed.
1. During Declaration
class Employee {
static final int employeeCount = 100;
}
✔ Valid
2. Inside a Static Block
class Employee {
static final int employeeCount;
static {
employeeCount = 100;
}
}
✔ Valid
Incorrect Example
class Employee {
static final int employeeCount;
public static void main(String[] args) {
employeeCount = 100;
}
}
Compile-Time Error
cannot assign a value to final variable employeeCount
Final Local Variables
A local variable exists only inside a method, constructor, or block.
Example:
public class Main {
public static void main(String[] args) {
int totalAmount = 500;
}
}
JVM Default Values
Unlike instance and static variables,
the JVM never provides default values for local variables.
Example:
public class Main {
public static void main(String[] args) {
int totalAmount;
System.out.println(totalAmount);
}
}
Compile-Time Error
variable totalAmount might not have been initialized
Final Local Variables
Declaring a local variable as final does not change this rule.
Example:
public class Main {
public static void main(String[] args) {
final int totalAmount;
System.out.println("Processing Order");
}
}
✔ Valid because the variable is never used.
Example:
public class Main {
public static void main(String[] args) {
final int totalAmount;
System.out.println(totalAmount);
}
}
Compile-Time Error
variable totalAmount might not have been initialized
Important Rule
A final local variable must be initialized before its first use.
Final Formal Parameters
Method parameters behave like local variables.
Therefore, they can also be declared as final.
Example:
class PaymentService {
public void processPayment(final double amount) {
System.out.println(amount);
}
}
What Happens If We Modify It?
Incorrect:
class PaymentService {
public void processPayment(final double amount) {
amount = amount + 500;
}
}
Compile-Time Error
cannot assign a value to final variable amount
Why Use Final Parameters?
They prevent accidental modification of method inputs.
This improves readability and avoids bugs.
JVM Default Values Comparison
| Variable Type | JVM Provides Default Value? | If Declared final
|
|---|---|---|
| Instance Variable | ✅ Yes | ❌ Must initialize explicitly |
| Static Variable | ✅ Yes | ❌ Must initialize explicitly |
| Local Variable | ❌ No | ❌ Still must initialize before use |
| Method Parameter | ❌ Passed by caller | ❌ Cannot be reassigned |
Initialization Summary
| Variable Type | Valid Initialization Locations |
|---|---|
| Final Instance Variable | Declaration, Instance Initializer Block, Constructor |
| Final Static Variable | Declaration, Static Block |
| Final Local Variable | Before first use |
| Final Method Parameter | Value supplied by the caller |
Common Beginner Mistakes
Mistake 1: Assuming Final Variables Receive Default Values
Incorrect:
class Product {
final int quantity;
}
The JVM does not assign default values to final instance variables.
Mistake 2: Initializing a Final Variable Inside a Normal Method
Incorrect:
void initialize() {
quantity = 10;
}
Initialization must occur before object construction finishes.
Mistake 3: Forgetting That Local Variables Never Receive Default Values
Incorrect:
int count;
System.out.println(count);
Always initialize local variables before using them.
Mistake 4: Modifying a Final Method Parameter
Incorrect:
public void calculate(final int number) {
number++;
}
Method parameters declared as final cannot be reassigned.
Best Practices
- Use
finalfor values that should never change. - Prefer
private finalfor immutable object fields. - Initialize final instance variables in constructors when values differ per object.
- Initialize final static variables during declaration unless complex initialization is required.
- Use meaningful names such as
customerId,orderNumber, andinvoiceNumber. - Avoid unnecessary use of
finalon every local variable—use it where it improves clarity.
Interview Questions
1. What is a final variable?
A variable that can be assigned only once.
Why interviewers ask
To verify your understanding of immutability.
Common trap
Confusing "cannot be reassigned" with "object becomes immutable."
2. Can a final instance variable remain uninitialized?
No.
It must be initialized before constructor completion.
3. Where can a final instance variable be initialized?
- At declaration
- Inside an instance initializer block
- Inside a constructor
4. Where can a final static variable be initialized?
- At declaration
- Inside a static initializer block
5. Does the JVM provide default values for final variables?
No.
If an instance or static variable is declared final, it must be initialized explicitly.
6. Can a local variable be final?
Yes.
However, it must still be initialized before its first use.
7. Can method parameters be final?
Yes.
A final parameter cannot be reassigned inside the method.
Quick Memory Trick 🧠
Remember ISLP:
I → Instance → Declaration / Instance Block / Constructor
S → Static → Declaration / Static Block
L → Local → Before First Use
P → Parameter → Provided by Caller
If you remember ISLP, you'll always know where each type of final variable can be initialized.
Key Takeaways
-
finalvariables can be assigned only once. - Java supports final instance variables, static variables, local variables, and method parameters.
- Final instance variables must be initialized before constructor completion.
- Final static variables must be initialized before class loading completes.
- Local variables never receive default values from the JVM.
- Final method parameters cannot be reassigned.
- Choosing the correct initialization location is a common Java interview topic.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)