CodesJava

Easy learning with example program codes

what is final variable in java?


A variable declared with final keyword is known as final variable. It may be member variable or local variable. The final variables are constants in java and they are generally declared with static keyword. As final variables are treated as constants they can’t reassign. They are initialised at the time of declaration.

Example

/**
 * This program is used to show that the value of 
 * final variable can't be change. 
 * @author CodesJava
 */
class Test{
	//final variable
	final int num = 100;
 
	//method for try to change the value of final variable.
	public void show(){
		//error because value of final variable can't be change.
		num = 200;
		System.out.println("Num = " + num);
	}
}
public class FinalExample1 {
	public static void main(String args[]){
		//creating object of Test Class
		Test obj = new Test();
		//method call
		obj.show();
	}
}

Output

Exception in thread “main” java.lang.Error:
Unresolved compilation problem:
The final field Test.num cannot be assigned
at com.codesjava.business.Test.show(FinalExample1.java:15)
at com.codesjava.business.FinalExample1.main
(FinalExample1.java:24)

Java interview questions on final keyword

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki