Question

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;
Était-ce utile?

La solution 2

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.)

Autres conseils

C'mon. Just read what each keyword means:

static means "associated with a class rather than instances"

final is more complex - context dependent.

http://javamex.com/tutorials/synchronization_final.shtml

private static int i=10;  // i is associated with class; mutable
private static final int j=10; // j is associated with class; immutable
private final int k = 10; // k is associated with instances; immutable

It's sometimes helpful to think of "static" in a similar way to "global". So the differences are the following:

  1. private static int i = 10; // this means that all instances of a class will share the same variable i and whatever its current value is. E.g., Thing A and Thing B are instances of class Thing. If A modifies the variable i, then it will be modified for B as well.
  2. private static final int j = 10; // this means that all instances of the class will share the same value for j just like number 1. Additionally, you cannot change the value of j. It is a constant, immutable.
  3. private final int k = 10; // this means it's a constant.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top