Search code examples
staticfinal

Please tell me the difference b/w below three declaration-


Please tell me the difference b/w below three declaration-

  1. private static int i=10;
  2. private static final int j=10;
  3. private final int k = 10;

Solution

  • Short answer:

    Final: you cannot change the var after the declaration.

    Static: the variable is associated with a class not with instances

    private static int i=10;        // belongs to the class
    private static final int j=10;  // belongs to the class and it's unchangeable 
    private final int k = 10;       // it's unchangeable 
    

    Long Answer:

    Final: Define an entity once that cannot be changed nor derived from later. More specifically: a final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression. All methods in a final class are implicitly final.

    Static: Used to declare a field, method, or inner class as a class field. Classes maintain one copy of class fields regardless of how many instances exist of that class. static also is used to define a method as a class method. Class methods are bound to the class instead of to a specific instance, and can only operate on class fields. (Classes and interfaces declared as static members of another class or interface are actually top-level classes and are not inner classes.)