Java
In this tutorial we will learn about final variables in Java programming language.
final
variableIf the final
keyword is added to a variable then it becomes a constant and its value can't be modified later.
final type varName = val;
Where, varName
is the name of the variable and its data type is represented by type
.
We are assigning a value to the variable represented by val
.
And this is a constant as we are using the final
keyword.
In the following example we are creating an interger variable MULTIPLY
and declaring it final
. We are assigning integer value 100 to it.
Since, we are declaring it as final
so, any attempt to modify its value will give error.
class Example {
public static void main(String[] args) {
// creating a final variable
final int MULTIPLY = 100;
// output
System.out.println("Value of the MULTIPLY constant: " + MULTIPLY);
// the following code will return error
// MULTIPLY = 1;
}
}
Output:
Value of the MULTIPLY constant: 100
If we uncomment the line MULTIPLY = 1;
and re-run our code. We will get the following error.
Main.java:11: error: cannot assign a value to final variable MULTIPLY
MULTIPLY = 1;
^
1 error
In the following example we are creating multiple constants.
class Example {
public static void main(String[] args) {
// creating a final variables
final char CH = 'a';
final byte B = 0;
final short S = 1;
final int I = 10;
final long L = 100;
final float F = 123.45F;
final double D = 123.456;
final String STR = "Hello World";
// output
System.out.println("Value of the CH constant: " + CH);
System.out.println("Value of the B constant: " + B);
System.out.println("Value of the S constant: " + S);
System.out.println("Value of the I constant: " + I);
System.out.println("Value of the L constant: " + L);
System.out.println("Value of the F constant: " + F);
System.out.println("Value of the D constant: " + D);
System.out.println("Value of the STR constant: " + STR);
}
}
Output:
$ javac Example.java
$ java Example
Value of the CH constant: a
Value of the B constant: 0
Value of the S constant: 1
Value of the I constant: 10
Value of the L constant: 100
Value of the F constant: 123.45
Value of the D constant: 123.456
Value of the STR constant: Hello World
ADVERTISEMENT