Friday 21 February 2014

final variables

final is used to create two types of constants
    1. Creating final constants
    2. Creating final reference variables

1. Creating final constants.
Below post discussed about the final constants
http://selflearningjava.blogspot.in/2014/02/keyword-final.html

2. Creating final reference variables
When you assign an object to final reference variable, then the reference variable points to the same object, the object can change its state, I.e, its values. Assigning some other object or reference to the final reference variable is not allowed.

Example
class FinalReferenceEx{
  int width, height;

  public static void main(String args[]){
    final FinalReferenceEx ref1 = new FinalReferenceEx();

    ref1.width = 100;
    ref1.height = 200;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);

    ref1.width = 200;
    ref1.height = 300;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);
  }
}
   
Output
Width is 100 height is 200
Width is 200 height is 300

As you observe the output, the final reference variable is allowed to change the properties of the object that it is pointing. But it is not allowed to refer other object.

Example
class FinalReferenceEx{
  int width, height;

  public static void main(String args[]){
    final FinalReferenceEx ref1 = new FinalReferenceEx();

    ref1.width = 100;
    ref1.height = 200;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);

    ref1.width = 200;
    ref1.height = 300;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);

    ref1 = new FinalReferenceEx();
  }
}

I am trying to assign a new object to the final reference variable ref1, which is not acceptible, so compiler throws below error.

FinalReferenceEx.java:16: error: cannot assign a value to final variable ref1
ref1 = new FinalReferenceEx();
^
1 error

The same applicable for Arrays also, since Arrays also reference types.

Some Points to Remember

1. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

2. What is blank final variable in Java ?
Blank final variable in Java is a final variable which is not initialized while declaration, instead they are initialized on constructor or initializer blocks or static initialization blocks.

Related Links

final keyword                                                 final classes and methods                                                 Home

No comments:

Post a Comment