Initialize blank final variable in java

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