Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is final in Java?

Final Static Variable

  • If the value of a variable is not varied from object to object such type of variable not recommended to declare as the instance variable. We have to declare those variable as class level by using the static modifier.
  • In the case of instance variable for every object, a separate copy will be created. But in the case of static variables, a single copy will be created at the class level and shared by every object of that class.
  • For static variable is not required to perform initialization explicitly, JVM will always provide default values.
  • If the static variable declared as final then compulsory we should provide explicitly otherwise we will get compile time error and JVM won’t provide any default values.
  • A final variable can only be initialized once.
  • Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized.

Rules

  • For final static variables compulsory we should perform initialization before class loading completion i.e. The following are varies places are this:-
    1. At the time of declaration
    2. Inside static block
  • These are only possible places to perform initialization for final static variables if we are trying to perform initialization anywhere else then we will get compile time error.

Final Local Variable

  • Sometimes to meet a temporary requirement of the programmer we have to declare variables inside a method of block or constructor such type of variables is called local variables or temporary variable or stack variables or automatic variables.
  • For local variables JVM won’t provide any default values compulsory we should provide initialization explicitly before using that local variable i.e. If we are using then it is not required to perform initialization for local variables.
  • Even though the local variable is final before using only we have to perform initialization i.e. If we are not using then it is not required to perform initialization even though its final.
  • The only applicable modifier for the local variable is final. By-mistake if we are trying to apply any other modifier then we will get compile time error.
  • If we are not declaring any modifier then by default its default but this rule is applicable only for instance and static variable but not for local variables.
Tags:  , , , , , , , , , ,

Leave a Reply

Your email address will not be published.