Yes. We can initialise blank final variable in java, only in constructor but it should be a non-static blank final variable.
Example with non static variable:
class BlankFinalInitialization{ //blank final variable final String courseName; BlankFinalInitialization(String courseName){ this.courseName = courseName; System.out.println("courseName = " + courseName); } } public class Main { public static void main(String args[]){ //creating object of BlankFinalInitialization Class BlankFinalInitialization obj = new BlankFinalInitialization("MCA"); } } |
Output:
courseName = MCA |
Example with static variable:
class BlankFinalInitialization{ //blank static final variable static final String courseName; BlankFinalInitialization(String courseName){ this.courseName = courseName; System.out.println("courseName = " + courseName); } } public class Main { public static void main(String args[]){ //creating object of BlankFinalInitialization Class BlankFinalInitialization obj = new BlankFinalInitialization("MCA"); } } |
Output:
Main.java:6: error: cannot assign a value to final variable courseName this.courseName = courseName; ^ 1 error |
Note: Static blank final variable can be initialized with static block
class BlankFinalInitialization{ //blank static final variable static final String courseName; static { courseName = "MCA"; System.out.println("courseName = " + courseName); } } public class Main { public static void main(String args[]){ //creating object of BlankFinalInitialization Class BlankFinalInitialization obj = new BlankFinalInitialization(); } } |
Output:
courseName = MCA |
Java interview questions on final keyword
- what is final in java?
- What is final variable in java?
- What is final method in java?
- What is final class in java?
- What is blank final variable in java?
- What is static blank final variable in java?
- What is final parameter in java?
- Can we initialize blank final variable in java?
- Can we declare the main method as final?
- What is the use of final keyword in java?
- Can we change the state of an object to which a final reference variable is pointing?
- Difference between abstract method and final method in java?
- Can we change the value of an interface field?
- Can we declare constructor as final in java?