Final Variables

Final Variables

final variable is basically declared by the final keyword , It makes impossible to reinitialize that variable once it has been initialized with an explicit value.

object reference variable is basically a reference variable marked final can\'t ever be reassigned to refer to a
different object.When the data is in the object form and we would like to modified but the reference variable can not be changed , we can also say like we can use final reference to modify the object it refers to, but we can\'t modify the reference variable to make it refer to a different object.there are no final objects, only final references.

 A reference variable\'s value in other words, the bit pattern the variable holds is not an object,A reference variable holds bits that represent, in a platform-dependent format, a way to get to an object.

We can see in this code :
class FinalTest{
final int x; // Will not work unless x is assigned in the constructor
public void showFinal() {
System.out.println(\"Final x = \" + x);
}
}

Attempting to compile the preceding code gives us the following:
%javac FinalTest.java

FinalTest.java:2: Blank final variable \'x\' may not have been
initialized. It must be assigned a value in an initializer, or in
every constructor.
final int x;
1 error

 If we would like to declare an instance variable as final, but don\'t give it an explicit value at the time we declare it, the variable is considered a blank final. The final instance variable can stay blank only until the constructor completes.

class FinalTest{
final int x; // Will work because it\'s initialized in the constructor
public FinalTest() {
x = 28; // Whew! The compiler is relieved that we took care of it
System.out.println(\"Final x = \" + x);
}
}

declaring an object reference variable as final:
import java.util.Date;
class TestClass {
final Date d = new Date();
public void showSample() {
d.setYear(2001); //Altering Date object, not d variable, so it\'s OK
}
}

By:UMANG
Date:2025-02-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related Java Subjective Links

Java Subjective interview questions and answers for experienced and fresher