I followed the link static and final in java to understand the difference between static and final but found one difference that static variables can be reinitialized while for final we cannot do so why can anyone help me with an example? Static members can be changed through static method , does that meant re-initialization, please let me know my understanding is correct or not?
-
2ugh, these are two very strange keywords to compare since they are totally different. just look up one of them at the time and read about them. [final](https://en.wikipedia.org/wiki/Final_(Java)) and [static](https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) – Jack Flamp Aug 17 '18 at 07:04
-
2I really don't get why you want to list the differences between them. It's like asking "What's the difference between apples and concrete?". What's the reason for the comparison? – Christian Seifert Aug 17 '18 at 07:07
-
I was about to say apples an oranges... but @perdian nailed the analogy – shinjw Aug 17 '18 at 07:12
3 Answers
static
and final
mean totally different things.
static String s = "Hello";
This means that there is only one instance of that variable shared between all instances of the class.
final String s = "Hello";
This means that you cannot change the value of s
after it is first set.
You can also have static final
!
static final String s = "Hello";
Now you have both, there is only one and it will never change.

- 64,482
- 16
- 119
- 213
A property of the final keyword is that it ensures that a variable cannot change state after it has been initialized. It forces the user to initialize when it is declared or in a constructor.

- 437
- 1
- 4
- 12
It is 2 completely different keywords with different functionalities:
"static" - a class variable shared to all instances of that class, not to a specific instance. You can modify in any place you want(depending on the context).
"final" is a type or variables that you can assign only once, and cannot modify it's reference, but from other side, you can modify the contents of the referenced object.
Combining this 2 keywords you may get some interesting results:
- "final static" you can define a constant - accessible from any instance and not modifiable reference.
Hope this helps you understanding.

- 353
- 1
- 9