Saturday, July 6, 2013

Final keyword in JAVA.Can be used with variables,methods and classes:

Final is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java.
Final variables are often declare with static keyword in java and treated as constant. Here is an example of final variable in Java

public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error

Final methods can not be overridden in subclasses.Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.
 
Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes.

Benefits of final keyword in Java

1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.
2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.
3. Final keyword allows JVM to optimized method, variable or class.

Important points on final in Java

1. Final keyword can be applied to member variable, local variable, method or class in Java.
2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration.

5. Only final variable is accessible inside anonymous class in Java.

6. Final method can not be overridden in Java.

7. Final class can not be inheritable in Java.

10. All variable declared inside java interface are implicitly final.

12. Final methods are bonded during compile time also called static binding.

13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:

private final List Loans = new ArrayList();
list.add(“home loan”);  //valid
list.add("personal loan"); //valid
loans = new Vector();  //not valid

No comments:

Post a Comment