30. How many ways to initialize for final variable?

How many ways to initialize for final variable?

1. Initialize at the Declaration

You can initialize a final variable at the time of its declaration. This is the simplest way and ensures that the variable is assigned a value when it is created.

Example:

public class FinalVariableExample {
// Initialize final variable at the declaration
private static final int MAX_VALUE = 100;

public static void main(String[] args) {
System.out.println(“MAX_VALUE: ” + MAX_VALUE);
}
}

2. Initialize in a Constructor

You can initialize a final variable within the constructor of the class. This allows you to assign a value to the final variable after the object is created but only once per object construction.
Example

public class FinalVariableExample {
private final int maxValue;

// Constructor to initialize final variable
public FinalVariableExample(int value) {
this.maxValue = value;
}

public void printMaxValue() {
System.out.println(“maxValue: ” + maxValue);
}

public static void main(String[] args) {
FinalVariableExample example = new FinalVariableExample(200);
example.printMaxValue();
}
}

3. Initialize in a Static Block

For static final variables, you can initialize them within a static block. This block runs when the class is loaded, allowing complex initialization for static variables.

public class FinalVariableExample {
private static final int MAX_VALUE;

// Static block to initialize static final variable
static {
MAX_VALUE = 300;
}

public static void main(String[] args) {
System.out.println(“MAX_VALUE: ” + MAX_VALUE);
}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *