JAVA : What is a Final variable in Java?
SDET Automation Testing Interview Questions & Answers
We will be covering a wide range of topics including QA manual testing, automation testing, Selenium, Java, Jenkins, Cucumber, Maven, and various testing frameworks.
JAVA : What is a Final variable in Java?
In Java, a final variable is a variable whose value cannot be changed once it is assigned. It is a constant and acts as a read-only variable. Once a final variable is assigned a value, it cannot be reassigned or modified.
Here are some key points about final variables in Java:
1. Declaration and initialization: A final variable must be initialized at the time of declaration or within the constructor of the class. Once initialized, its value cannot be changed.
2. Keyword: The `final` keyword is used to declare a variable as final.
3. Naming convention: By convention, the names of final variables are written in uppercase letters with underscores to separate words (e.g., `MAX_VALUE`, `PI`, `DEFAULT_TIMEOUT`).
4. Usage: Final variables are often used to define constants, such as mathematical or configuration values, that should not be modified during the execution of a program.
5. Accessibility: Final variables can have different access modifiers (e.g., public, private, protected, or default) to control their visibility and access from other classes.
6. Instance and local final variables: Final variables can be declared as instance variables (non-static) or local variables. Instance final variables have a separate value for each instance of a class, while local final variables are specific to a method or a block of code.
7. Effect on references: If a final variable holds a reference to an object, the object's internal state can still be modified. However, the final variable itself cannot be reassigned to a different object.
Here's an example that demonstrates the usage of final variables in Java:
public class Example {
// Final instance variable
private final int count = 10;
// Final local variable
public void printMessage() {
final String message = "Hello, world!";
System.out.println(message);
}
// Final parameter
public void updateValue(final int value) {
// value = 20; // Cannot modify the final parameter
System.out.println("Value: " + value);
}
public static void main(String[] args) {
final int constant = 100;
System.out.println("Constant: " + constant);
Example example = new Example();
System.out.println("Count: " + example.count);
example.printMessage();
example.updateValue(50);
}
}
In the above example, `count` is a final instance variable, `message` is a final local variable, and `value` is a final method parameter. The `constant` variable is a final local variable in the `main` method.
Final variables provide immutability and help in writing code that is easier to understand and maintain. They also help in ensuring that certain values remain constant throughout the execution of a program.