A Final variable in java is declared with final keyword. It can represent a member variable or local variable. The final variables represents the constants in java and normally declared with static keyword. As final variables are constants that’s why they are initialised at the time of declaration and can’t be reassigned.
Example
class FinalVariableTest{ //final variable final String website = "w3spoint.com"; public void show(){ //error because value of final variable can't be change. website = "java.com"; System.out.println("website = " + website); } } public class Main { public static void main(String args[]){ //creating object of FinalVariableTest Class FinalVariableTest obj = new FinalVariableTest(); //method call obj.show(); } } |
Output
Main.java:7: error: cannot assign a value to final variable website website = "java.com"; ^ 1 error |
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?
Please follow and like us: