Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, the static and final keywords are often used but serve different purposes. Understanding how these keywords work can help you write more efficient and effective code.
This article will explore the differences between static and final, their uses, and how they affect the behavior of variables and methods in Java.
Final Access Modifier
What is final KEYWORD?
The final keyword in Java is used to restrict the user from modifying variables, methods, or classes. When applied, final makes a variable constant, a method unchangeable, or a class non-subclassable.
Syntax
final int MY_CONSTANT = 10;
final void myMethod() {
// method body
}
final class MyClass {
// class body
}
Examples
Example 1: Final Variable
Java
Java
public class FinalVariableExample {
public static void main(String[] args) {
final int MY_CONSTANT = 100;
// MY_CONSTANT = 200; // This will cause a compilation error
System.out.println(MY_CONSTANT);
}
}
You can also try this code with Online Java Compiler
Here, the display method in the Parent class is marked as final, so it cannot be overridden in the Child class.
Static Access Modifier
What is static Keyword?
The static keyword is used to define class-level variables and methods. Unlike instance variables and methods, static variables and methods belong to the class itself rather than any particular instance of the class.
Shares a single copy across all instances of a class
Usage
Variables, methods, classes
Variables, methods
Inheritance
Cannot be overridden in subclasses
Methods can be called on the class itself
Instance-specific
No
No
Initialization
Must be initialized once
Can be initialized once
Memory Allocation
Memory allocated per instance
Memory allocated once for the class
Frequently Asked Questions
Can a final variable be initialized later?
No, a final variable must be initialized when it is declared or within the constructor if it is a member variable.
Can a static method access instance variables?
No, static methods cannot access instance variables directly. They can only access other static members of the class.
What happens if a final class is subclassed?
It causes a compilation error. A final class cannot be subclassed.
Can static variables be overridden?
No, static variables are not overridden but can be shadowed by local variables or subclass variables.
Conclusion
Understanding the static and final keywords in Java is crucial for managing data and methods within your programs. The final keyword helps in creating constants and ensuring that certain methods or classes remain unmodified. On the other hand, static helps in defining class-level variables and methods that are shared across all instances. By grasping the differences and applications of these keywords, you can write more efficient and controlled Java programs.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.