Blank final variable in java

In java, blank final variable is a variable which is declared with final keyword but not initialised at declaration time. Blank final variables are initialised at the object creation time by constructor and they can’t change after that. Example

class BlankFinalTest{
	//blank final variable
	final String website;
 
	BlankFinalTest(String website){
		this.website = website;
		System.out.println("website = " + website);
	}
}
public class Main {
	public static void main(String args[]){
		//creating object of BlankFinalTest Class
		BlankFinalTest obj = new BlankFinalTest("w3spoint.com");
	}
}

Output

website = w3spoint.com

We will get compile time error, if we try to change the value of blank final variable. Example

class BlankFinalTest{
	//blank final variable
	final String website;
 
	BlankFinalTest(String website){
		this.website = website;
		System.out.println("website = " + website);
		this.website = "java.com";
	}
}
public class Main {
	public static void main(String args[]){
		//creating object of BlankFinalTest Class
		BlankFinalTest obj = new BlankFinalTest("w3spoint.com");
	}
}

Output

Main.java:8: error: variable website might already have been assigned
		this.website = "java.com";
		    ^
1 error

Java interview questions on final keyword

Please follow and like us:
Content Protection by DMCA.com