In: Computer Science
BIG JAVA
CH4: Understand the proper use of constants
Question:
What is the purpose of keyword final? Explain what happens when you use it and give an example.
In Java, "final" is a keyword, used along with a variable. The main aim of final keyword is to create some sort of constraint, for the above.
In a variable, final is placed as a prefix, which, in a way, makes that variable's value constant. This means that oncea variable is "final", during it's declaration and initialization, it means that it's value is fixed, final and cannot be changed later on in it's lifetime.
If, in any part of our code, there is an attempt made to modify the value of this constant, it will give an compilation error, i.e. it cannot be modified. Let's take a look at an example that show how it is declared, instantiated and what happens if there's an attempt to modify it's value.
Example:-
public class Finalconst { //public class FInalConst created,
containing constant
final int mynum=5; //constant munum declared, using
"final" keyword
void changeval(int x)
{
mynum=x; //changeval functtion,
attempts at changing value of constant number
}
void printval() //function to print the value of
mynum
{
System.out.println(mynum+"\n");
}
public static void main(String args[])
{
Finalconst f=new Finalconst();
//Object o class Finalconst created
f.printval(); //Printing the value
of our constant
f.changeval(9); //Changing the
value of constant to 9
}
}
Output:-