The final keyword is a non-access modifier used in different contexts. It can be used in different contexts
- To create a constant variable
- To prevent overriding the method
- To prevent inheritance in classes
The value of the final variable remains constant it cannot be changed so final variables must be used only for the values that we want to remain constant throughout the execution of the program.
Initializing a final variable
We must initialize a final variable, otherwise compiler will throw a compile-time error. A final variable can only be initialized once, either via an initializer or an assignment statement. There are three ways to initialize a final variable
- A common method is to initialize a final variable when it is declared. A final variable is called a blank final variable, if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.
- A blank final variable can be initialized inside the instance-initializer block or the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, compile-time error will be thrown.
- A blank final static variable can be initialized inside the static block.
Usecase
Output:
- Final class cannot be inherited, as final classes cannot be extended
- Cannot make a class immutable without making it final.
Usecase for the final class
Output:
static is a non-access modifier applicable for the following
- blocks
- variables
- methods
- nested classes
To create a static member which can be a block, variable, method, or nested class, a static keyword is used .static makes your program memory efficient
Static variable
- When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level.
- Static variables are executed in the order they are present in a program.
- All instances of the class share the same static variable
Static block
- Static blocks are executed only once while loading in the memory and order they are present in a program.
- A static block is also called a static initialization block
Static method
When a method is declared with the static keyword, it is known as a static method. The most common example of a static method is the main( ) method.
Methods declared as static have several restrictions
- They can only directly call other static methods.
- They can only directly access static data.
- They cannot refer to this or super.
Static nested classes
We cannot declare top-level classes with a static modifier but can declare nested classes as static. Such types of classes are called Nested static classes
Usecase
Output: