- It is a non-access modifier
- Static keyword can be applied to an instance variable or method.
- Applying to an instance variable makes that variable as a class variable.
- Both primitive and reference variable can be marked with static keyword
Consider the code,
- The content of the primitive variable is the actual value.
- The value of the primitive variable cannot be changed once initialized.
- The content of the reference variable is reference to the object in
- Final parameter variable can’t be modified within the method i.e.) cannot reassigning a new value to the variable.
- A method can have any number of final parameters
- All local variables can only be marked with final non-access modifier with default access modifier. Trying to use any other access or non-access modifier will result in a compiler error.
- A final static variable must be definitely initialized either
- during declaration also known as compile time constant or
- in a static initialize (static block) of the class in which it is declared otherwise, it results in a compile-time error.
- It should be assigned only once before constructor exits. i.e.) Assigned
The value of a final instance variable is not necessarily known at the compile time i.e.) during declaration.
- during declaration (compile time constant)
- inside constructor
- inside initialization block
- A final variable – value cannot be changed once initialized and attempt to change the value will result in a compiler error.
- Provides us security and thread safety
- If your object is accessed by multiple threads, and you don’t declare
- A final method cannot be overridden by subclasses.
- It prevents unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class
- private and static methods are always implicitly final, since they
- You can declare an entire class final — this prevents the class from being sub classed.
Trying to extend a class that is marked as final will result in compiler error.Accordingly, many of the Java
- Final class prevents inheritance.
- The final keyword is a non-access modifier.
- It can be applied to a class, method(both instance and static) and variable(instance, static, local and parameter).