Saturday, January 4, 2014

final in Java

Keyword final is used to represent constants. Final is a versatile in a way that it can be used with variable, method and class. To be more precise it can be applied to instance variables, local variables, instance methods, class methods and class itself.

Final Variable

Final variable is a constant and can be assigned value only once. If we need to declare a constant at instance level i.e. a constant pertaining to an individual instance, we can create final variable at instance level.
We can create an uninitialized final instance. Later it can be initialized in variety of ways.
  1. We can initialize it at the time of declaration.

      public class FinalVariableDemo {
           private final int TARGET=52;
           private int achieved;
     }
  
     2.       We can initialize it in the constructor method. Variable will be initialized when an instance is created.

       public class FinalVariableDemo {
            private final int TARGET;
            private int achieved;
            public FinalVariableDemo(){
                 TARGET=25;
           }
           public FinalVariableDemo(int target){
                 this();
                 this.TARGET=target;
         }
    }

      We need to be careful to initialize final variable in one of the constructors and not in both IF one constructor is making a call to another constructor.

        public FinalVariableDemo(int target){
                this();
                this.TARGET=target; // this line is a compiler error
        }

       Java compiler will not allow it and will flag compiler error.

  1. Another place where final variable can be initialized is an anonymous block in the class.
public class FinalVariableDemo {
    private final int TARGET;
    private int achieved;
    {
        TARGET=50;
    }
}
Anonymous block is executed before the constructor is called. If we want to initialize final variable in an anonymous block, we should not initialize it in the constructor.

Note : final instance variable must be initialized before object creation.

public class FinalVariableDemo {
    private final int TARGET;
    private int achieved;
    public static void main(String[] args) {
        FinalVariableDemo anInstance= new FinalVariableDemo();
        anInstance.TARGET=34; // this is an error
    }

Whereas Local final variables can be initialized at the time of declaration.

public class LocalFinalVar {
    public static void main(String args[]){
        final int X=25;
       System.out.println("x ="+X);
  }
}

Or it can be initialized just before its first use.

public class LocalFinalVar {
    public static void main(String args[]){
        final int X;
        X=25;
       System.out.println("x ="+X);
    }
}
                                                                                                                                              ...to be contd

By Nancy
@11:27 am 01/05/2014

1 comment:

  1. I would be cautious about suggesting that "final is used to represent constants". Yes, it works that way with primitive types, but it's important to recognize that where a reference type is in use, final only means that you cannot refer to a different object, not that the object's contents, and therefore its "value", is unchanging. That's a remarkably common misunderstanding in my experience, which would be good to call out.

    Also, as a side note, using final to call out values that "should not" be changed is a potentially useful form of enforced-documentation-in-code. If your design expects this variable to remain the same, mark it as such, so the next programmer cannot so easily make the mistake of changing it.

    Finally, it used to help the compiler to perform optimizations when values that would never be changed were labeled as final. I'm fairly sure, however, that the Java 8 compiler recognizes unchanging values anyway now, and will apply any available optimizations regardless. Might not hurt, however :)

    ReplyDelete