The static keyword can be used in 4 scenarios
- static variables
- static methods
- static blocks of code
- static nested class
Let's look at static variables and static methods first.
Static variable
- It is a variable which belongs to the class and not to object (instance).
- Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
- A single copy to be shared by all instances of the class.
- A static variable can be accessed directly by the class name and doesn’t need any object.
- Syntax:
Class.variable
Static method
- It is a method which belongs to the class and not to the object (instance).
- A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
- A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
- A static method can be accessed directly by the class name and doesn’t need any object.
- Syntax:
Class.methodName() - A static method cannot refer to
thisorsuperkeywords in anyway.
Static class
Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
Side note:
main method is
staticsince it must be be accessible for an application to run before any instantiation takes place.
final keyword is used in several different contexts to define an entity which cannot later be changed.
A
finalclass cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes arefinal, for examplejava.lang.Systemandjava.lang.String. All methods in afinalclass are implicitlyfinal.A
finalmethod can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.A
finalvariable can only be initialized once, either via an initializer or an assignment statement.
It does not need to be initialized at the point of declaration, this is called ablank finalvariable, but in this case:- A
blank finalinstance variable must be assigned at every constructor of its class. - A
blank finalstatic variable must be assigned in a static initializer in its class.
- A
Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
The static keyword can be used in 4 scenarios
- static variables
- static methods
- static blocks of code
- static nested class
Let's look at static variables and static methods first.
Static variable
- It is a variable which belongs to the class and not to object (instance).
- Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
- A single copy to be shared by all instances of the class.
- A static variable can be accessed directly by the class name and doesn’t need any object.
- Syntax:
Class.variable
Static method
- It is a method which belongs to the class and not to the object (instance).
- A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
- A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
- A static method can be accessed directly by the class name and doesn’t need any object.
- Syntax:
Class.methodName() - A static method cannot refer to
thisorsuperkeywords in anyway.
Static class
Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
Side note:
main method is
staticsince it must be be accessible for an application to run before any instantiation takes place.
final keyword is used in several different contexts to define an entity which cannot later be changed.
A
finalclass cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes arefinal, for examplejava.lang.Systemandjava.lang.String. All methods in afinalclass are implicitlyfinal.A
finalmethod can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.A
finalvariable can only be initialized once, either via an initializer or an assignment statement.
It does not need to be initialized at the point of declaration, this is called ablank finalvariable, but in this case:- A
blank finalinstance variable must be assigned at every constructor of its class. - A
blank finalstatic variable must be assigned in a static initializer in its class.
- A
Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
final - The value assigned to the variable cannot be changed.
static - Even in different class instances, compiler will allocate the same memory location to the variable which it had assigned no matter how many instances of that class. The value can be changed.
My question is: Why is the final keyword not allocating the same memory location to the variable, if the value cannot change?
Let us have different instances of a class and still we will have the same value in the variable as it has been declared as final.
Why do we need to write static final then, it could have been done via final only, am I missing on thinking some cases?
If someone can please clarify?
Videos
Can a final variable be static in Java?
What are the best practices for using final and static in Java?
How do final and static affect inheritance in Java?
No difference at all. According to 8.3.1 - Classes - Field Modifiers of the Java Language Specification,
If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.
For fields, the said production lists the modifiers in this order:
@Annotationpublicprotectedprivatestaticfinaltransientvolatile
And for methods:
@Annotationpublicprotectedprivateabstractstaticfinalsynchronizednativestrictfp
They are the same. The order of modifiers is not significant. And note that the same rule applies in all contexts where modifiers are used in Java.
However, most Java style guides recommend/mandate the same specific order for the modifiers. In this case, it is public static final.
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.
variables are declared in methods, and used as some kind of mutable local storage (
int x; x = 5; x++)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 parametersfinal. 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!).fields define the mutable state of objects, and are declared in classes (
class x { int myField; }).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!).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 ofxwithnew 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 ofxwith 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).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).
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".
Please correct me if I am wrong, and explain where my understanding is incomplete.
From what I've read both static and final are keywords. If you make a variable or method static, it would only be accessed by the class itself and not by an instance of the class (object). A static class would be useful if it was nested inside another class and you didn't want an instance of the outer class to access the inner class.
If you make a variable final, then it is initialized once and not changed. A final class can't be subclassed, and a final method can't be overwritten. If a variable is static final, then it cannot be changed and it can only be accessed by the class itself and not an object of the class.
People use static all the time, but why is it useful to limit the access of a method or variable to the class itself and not any instances of it?
In general, static means "associated with the type itself, rather than an instance of the type."
That means you can reference a static variable without having ever created an instances of the type, and any code referring to the variable is referring to the exact same data. Compare this with an instance variable: in that case, there's one independent version of the variable per instance of the class. So for example:
Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);
prints out 10: y.instanceVariable and x.instanceVariable are separate, because x and y refer to different objects.
You can refer to static members via references, although it's a bad idea to do so. If we did:
Test x = new Test();
Test y = new Test();
x.staticVariable = 10;
y.staticVariable = 20;
System.out.println(x.staticVariable);
then that would print out 20 - there's only one variable, not one per instance. It would have been clearer to write this as:
Test x = new Test();
Test y = new Test();
Test.staticVariable = 10;
Test.staticVariable = 20;
System.out.println(Test.staticVariable);
That makes the behaviour much more obvious. Modern IDEs will usually suggest changing the second listing into the third.
There is no reason to have an inline declaration initializing the value like the following, as each instance will have its own NUMBER but always with the same value (is immutable and initialized with a literal). This is the same than to have only one final static variable for all instances.
private final int NUMBER = 10;
Therefore if it cannot change, there is no point having one copy per instance.
But, it makes sense if is initialized in a constructor like this:
// No initialization when is declared
private final int number;
public MyClass(int n) {
// The variable can be assigned in the constructor, but then
// not modified later.
number = n;
}
Now, for each instance of MyClass, we can have a different but immutable value of number.
A static variable stays in the memory for the entire lifetime of the application, and is initialised during class loading. A non-static variable is being initialised each time you construct a new object. It's generally better to use:
private static final int NUMBER = 10;
Why? This reduces the memory footprint per instance. It possibly is also favourable for cache hits. And it just makes sense: static should be used for things that are shared across all instances (a.k.a. objects) of a certain type (a.k.a. class).