Final variable is a constant in java. Once you create and initialize then you can not change its value.
Syntax of Final Variable
final type varName = value;
type is any data type in java.
varName is any valid identifier in java. It is a variable name.
value is an optional. You can initialize variable by assigning its value.
Example of Final Variable
Example 1 : Program that illustrates final variable use in java using dayInWeek variable
class FinalVariableDemo
{
public static void main(String[] args)
{
//Once created and initialized, its value can not be changed.
final int dayInWeek = 7;
//Below statement will not compile. you can not change value of dayInWeek variable.
//dayInWeek = 6;
System.out.println("Number of days in a week = " + dayInWeek);
}
}
Output
Number of days in a week = 7