40

Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to define a protocol behavior for the implementing class which implies that the class that implements (inherits) an interface must incorporate all of the members of that interface.


I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?


A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?

The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.

public static void main(String args[])
{
    final int a=0;  //ok

    int b=1;  //ok

    static int c=2;  //wrong

    final static int x=0;  //wrong
}
5
  • 9
    static fields can only belong to a Class, hence the compiler error. final means a variable can never be changed after the first initialization. Commented Nov 4, 2011 at 5:34
  • @EJP, ah, perhaps I'm mistaken then. Nevermind! Commented Nov 4, 2011 at 5:40
  • @bdonlan In fact interface variables were specifically mentioned as an anti-pattern in Effective Java. Commented Nov 4, 2011 at 5:42
  • @EJP, yep. My lack of Java experience shows :) Are only static finals allowed, or does it also permit instance variables? Commented Nov 4, 2011 at 5:43
  • @bdonlan any variable declared in an interface is implicitly both static and final. If you don't even know that I suggest you shouldn't be posting your guesses here. Commented Nov 4, 2011 at 9:04

7 Answers 7

124

You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.

Anyways, these are the concepts you are mixing up:

  • variables
  • final variables
  • fields
  • final fields
  • static fields
  • final static fields

The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).

Let's try to rapidly describe them.

  1. variables are declared in methods, and used as some kind of mutable local storage (int x; x = 5; x++)

  2. final variables are also declared in methods, and are used as an immutable local storage (final int y; y = 0; y++; // won't compile). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final. Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).

  3. fields define the mutable state of objects, and are declared in classes (class x { int myField; }).

  4. final fields define the immutable state of objects, are declared in classes and must be initialized before the constructor finishes (class x { final int myField = 5; }). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).

  5. static fields are shared among all instances of any class. You can think of them as some kind of global mutable storage (class x { static int globalField = 5; }). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } }, here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x()). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).

  6. final static fields are global constants (class MyConstants { public static final double PI = 3.1415926535897932384626433; }).

There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.

Finally, there are also other keywords that might be used with fields, like transient, volatile and the access levels (public, protected, private). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).

Sign up to request clarification or add additional context in comments.

3 Comments

@Bruno - How is FizzBuzz implemented using final variables and final fields. Can you explain. Thank you.
@rtindru, hint: think about a class that has a method that recursively creates a new instance of the same class and recursively calls that same method. Quite contrived, but doable.
Looks fine to me! I'd just add final to both parameters on the constructor and the variables (which won't affect the code, but strictly make all data immutable). Also, I'd add private to the fields. But this all is just very minor details, your implementation is fine! Good job :)
29

Static members are those which can be accessed without creating an object. This means that those are class members and nothing to do with any instances. and hence can not be defined in the method.

Final in other terms, is a constant (as in C). You can have final variable inside the method as well as at class level. If you put final as static it becomes "a class member which is constant".

2 Comments

You can have final field inside the method -- a field cannot be declared inside a method. That would be called a final variable.
I think these are used as interchangeable - docs.oracle.com/javase/specs/jls/se7/html/…
1

I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?

Use a final static when you want it to be static. Use a final (non-static) when you don't want it to be static.

A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?

Design decision. There's just no way to answer that without asking James Gosling.

The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.

Because it violates the rule you just described.

Comments

1

final keyword simply means "this cannot be changed".It can be used with both fields and variables in a method.When a variable is declared final an attempt to change the variable will result to a compile-time error.For example if i declare a variable as final int x = 12; trying to increment x that is (++x) will produce an error.In short with primitives final makes a value a constant. On the other hand static can only be applied with fields but not in methods.A field that is final static has only one piece of storage.final shows that it is a constant(cannot be changed), static shows it is only one.

Comments

1

In Java, a static variable is one that belongs to class rather than the object of a class, different instances of the same class will contain the same static variable value.

A final variable is one that once after initialized ,after the instantiation of a class (creation of an object) cannot be altered in the program. However this differ from objects if a different value is passed post creation of another object of the same class.

final static means that the variable belongs to the class as well as cannot be change once initialized. So it will be accessible to the same value throughout different instances of the same class.

Comments

0

Just to add a minor information to @Bruno Reis 's answer, which I sought to complete the answer, as he spoke about important condition to initialize final fields before constructor ends, final static fields must also be initialized before before static blocks' execution finishes.

Comments

-1

You cannot declare static fields in static block, static fields can only belong to a class, hence the compiler error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.