Where can final variables be initialized?
There are three forms of final variables: class final variables, instance final variables, and local final variables. There is no requirement to initialize a final variable at declaration but it must initialize before using it.
You can only initialize a final variable once.
- For class final variables, the variables can be initialized in either the declaration or static initializer:
class Program {
static final int i1 = 10;
static final int i2;
static {
i2 = 10;
}
} - For instance final variables, the variables can be initialized in the declaration, instance initializer, or constructor:
class Program {
final int i1 = 10;
final int i2;
final int i3;
{
i2 = 10;
}
Program() {
i3 = 10;
}
} - For local final variables, the variables can be initlialized in the declaration or any place after its declaration. The local final variables must be initializd before they are used.
class Program {
void method() {
final int i1 = 10;
final int i2;
System.out.println(i1);
i2 = 10;
System.out.println(i2);
return ;
}
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?