Where are static final variables used in java? - java

I am studying java and wanted to know what's the usage of static final variables in application designing. Please provide some examples too.

Uses of a static final variable :
To define a compile time constant value. e.g : The Integer class defines a constant called MIN_VALUE as : public static final int MIN_VALUE = 0x80000000;
To create a non modifiable reference that can be accessed globally : E.g The Singleton pattern using a public static final reference.
When you mark a variable defined in a class as static, it is shared across all the instances of a class. When you mark a variable in a class as final, it can only be initialized once either on the same line as the declaration of the variable or in the constructor of the class. Putting both together, a member static final variable is shared across all instances of a class, must be initialized where it is declared, and cannot be modified once declared.

final means the reference can't be changed once it's set. static means the variable belongs to a class, not a specific instance. This combination of modifiers, especially when used on a primitive or an immutable class (such as String) are often used to represent constants. A classic example would be java.io.File.separtorChar.

You can define constants like
public static final String LANGUAGE = "JAVA"

Related

Java constants and static modifiers

In java, constants as known as keyword (final) with a value that will never change. I have seen some people create constants without declaring a static modifier. My question is, should constants be declared as a static? If so or if not, why?
If you assign a value to the final variable when declaring it, there's no point in it not being static, since each instance would have its own variable having the same value, which is wasteful.
However, if you need an instance variable whose value can only be set once (but different instances may have different values), that variable would have to be final but not static.
For example :
class Person
{
final int id;
public Person(int id) {
this.id = id;
}
}
You will first need to understand what constants do (i.e, what happens when you mark a field / local variable as final.)
When a primitive / String field is marked as final, it becomes a compile-time constant i.e, its value is passed as part of the bytecode itself. Thus its value is not computed / generated at runtime. This gives you a performance benefit.
The keyword static is used to say - this field is NOT unique for each instance of a class. You could have non-static final constants as well. Also, if a method local variable (primitive) is marked as final, it also becomes a constant.
So, No, static has nothing to do with constants. It is a design choice.
Constants with the final keyword will never change.. actually you cannot change the instance this field is referencing, but you can change values inside this instance.
Imagine this example:
class SomeClass {
final Car MYCAR;
...
}
With this code you will not be able to change the reference of MYCAR:
MYCAR = new Car(.....);
But you can do something like:
MYCAR.setPrice(10000);
So yes, there is a point in NOT making this field static if any instance of SomeClass needs to have their own copy of the object MYCAR but you don't want anyone to change the reference of this object.
Whatever you like. I would personally use static. You don't need to create an object when you declare it static. Also you can make a 'constants' file, where you store all constants like. public final static ...
So you basically use static final if it's a 'constant' used by all objects. If not, just make it final and pass it through the constructor.
Technically, the keyword final is enough for a constant since you can't change the value of final variables once assigned.
static should be used if the constant is not tied to a particular object instance.
For example, consider you have a Circle class, and you have a method to calculate area. You need the constant Pi for this purpose. Pi constant does not change from circle to circle. So it makes sense to declare Pi as a static final.
When you use keyword static in a class the all instances of class. i.e. All objects of a class share the same variable where as If you declare a class as final the it cannot be instantiated ( it's object cannot be created ). So if you declare a variable final then it can be assigned value only once.
Let suppose
class CalculateArea {
final static double PI = 3.1417;
/*write rest of the code to calculate area.
the value of PI will remain constant no matter
how many times its object is made
if you try to override the value of `PI` it will raise an error.
*/
}

Why is it possible for objects to change the value of class variables?

By Oracle's definition,
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.
By this definition, it is safe to deduce that a static variable belongs to the class and shouldn't be accessible for modification by any object of the class.Since all objects share it.
So this line from the same definition is a bit confusing:
Any object can change the value of a class variable...
So I tried this code and it prints 45 (although I get a warning saying "Static member accessed via instance reference"):
public class Main {
static int value = 8;
public static void main(String[] args) {
// write your code here
Main main = new Main();
main.value = 45;
System.out.println(value);
}
}
If this was a Student class, and I had a static variable called numberOfStudents, why should one object of that class be allowed to change the value of this class variable?
It's not really that "one object" can - it's just you're in code which has access to that variable, and unfortunately Java allows you to access static members (both variables and methods) as if they were instance members. This ends up with very misleading code, e.g.
Thread t = new Thread(...);
t.start();
t.sleep(1000);
The last line looks like it's asking the newly-started thread to sleep - but actually it'll make the current thread sleep.
This is basically a flaw in Java. The compiler will silently turn code like this into
Thread.sleep(1000);
or in your case
Main.value = 45;
(I believe that in an older version of Java, it would emit code that checked for nullity with the variable you were accessing the static member "through", but it doesn't even do that any more.)
Many IDEs will allow you to flag code like this with a warning or error. I would encourage you to turn on such a feature. If you see existing code like that, change it to use access the static member directly via the declaring class, so it's clear what's going on.
By this definition, it is safe to deduce that a static variable belongs to the class and shouldn't be accessible for modification by any object of the class.Since all objects share it.
No, static field is accessible for modifications, as long the access modifier allows it.
main.value = 45;
The compiler will read this line at compile-time as:
Main.value = 45;
Being able to create a class with static variables and methods so that those variables and methods are shared by all instances or objects created from the class can be very useful, see When to use static methods.
When sharing a static variable in a class between multiple instances or objects created from the class, the synchronized modifier may be required in order to ensure that if the static variable is being modified by objects in more than one thread, that data integrity is maintained, see What does synchronized mean? and also see How to synchronize a static variable among threads running different instances of a class in java.
The final key word, see How final keyword works is used to determine whether a variable is immutable or not. So if you want to have a class static variable that should be immutable or a constant then you can add the final modifier to the definition. However see Java final keyword for variables which explains that the underlying value for a reference may not be immutable in the sense that functional programming means. See also what is meant by immutable as well as Why final keyword is necessary for immutable class.
You can also use modifiers such as public to determine the visibility of variables and methods in a class, see What does public static void mean in Java.
By using modifiers such as final or private the programmer is able to finely tune the visibility and modifiability of variables in class and objects instantiated from the class.
Litle example how the compiler change the object field access to a class field access.
public class A {
static int foo = 25;
static public void main(String[] arg){
B b = new B();
A a = b;
System.out.println(b.foo);
System.out.println(a.foo);
}
}
class B extends A {
static int foo = 60;
}
The output is:
60
25
It also shows that can be confiusing as it have different behaviour as for object fields.
By this definition, it is safe to deduce that a static variable belongs to the class and shouldn't be accessible for modification by any object of the class.Since all objects share it.
No. By this definition, that static variable belongs to the class and is modifiable by any instance of the class. There is no implication that when some variable is shared that it should not be modifiable. Use final if you want that.
If this was a Student class, and I had a static variable called numberOfStudents, why should one object of that class be allowed to change the value of this class variable?
To increment the value in constructor and decrement it in finalizer, for example.
A static variable has a single instance for the whole class that defines it. When an instance is created, an instance of that static variable IS NOT CREATED. There is only one, and that one is freely modifiable by any function without the need for an instance. (unless it is declared final)

Should a private final field be static too?

I was wondering, if I have this field in my class : private final int foo = ..., should I put it in static private static final int foo = ...? Because if it's static, it's common to all the instances of my class, and will never change.
Is there a reason to not put it in static? Or do I have to put it in static?
If every instance of your class should have the same immutable value for foo, then you should make foo final and static. If each instance of your class can have a different (but still immutable) value for foo, then the value should just be final.
However, if every instance of your class should have the same immutable value for foo, then it is a really a constant. By convention, that is typically coded as follows:
private static final int FOO = ...
Note the caps to denote a constant...
if you initiate its value in the constructor then it should not be static like
private final int foo;
public MyClass(int m){
foo=m;
}
because its value depends on entry value.
but if you initiate its value inline like
private final int foo = 100;
then its preferred to be static to have just one instance of it, since the final field will be created on each instance of class; but static will be created once.
A final member can still be set by the constructor: therefore, if each instance of your class can set foo in the constructor and this value should pertain only to that instance, it should only be final, NOT static.
If however, foo is only set at declaration time, it might mean that this is a common value for all instances and you would win a little memory by declaring it static also. Beware though that if foo was not a primitive but a reference member, final only means that the reference can't change, not the content of the object, therefore a final and non static member that is a reference should not automatically be static. You could want one immutable reference per instance of your class, with different object state.
It is a constant and you will not want to have one copy of the variable for each instance of the class,so make it static. Also, if you want to use them from a static method, make it static.
Static variables are those variables which are common for all the instances of a class.If one instance changes it, then value of static variable would be updated for all other instances.
If you do not want this behavior, keep it non-static.
There is a big difference between the two non-access modifiers.
final means your variable can be assigned a value once.
static sets its scope to pertain to the class (rather than an instance or a local context).
There is no reason why they should go together unless by design.
A static final variable is de facto a constant.
For instance, fields declared in interfaces are implicitly public, static and final.
Amongst the usage examples for final, non static fields you can find:
fields declared outside an anonymous class and being referenced inside it
local fields (declared in a method's body) being referenced inside a local class (declared in the same method's body)
etc...

Does it make sense to define a static final variable in Java?

Does this definition make sense ?
private static final String string = "Constant string";
I'm a beginner and I don't understand the difference between final and static...
It makes sense, yes. This is how constants are defined in Java.
final means that the variable cannot be reassigned - i.e. this is the only value it can have
static means that the same value is accessible from each instance of the class (it also means it can be accessed even without an instance of the class where it is declared)
(private here means this constant is accessible only to the current class (all of its instances and its static methods))
Yes, it makes sense - this is how constants are usually defined in Java.
final means that you cannot change the variable to a different String.
static means that there is only one copy of the reference, shared between different objects of that class. (reference)
Normal code-convention is that constants are named in uppercase with underscores between words, so I would say:
private static final String CONSTANT_STRING = "Constant string";
is more common.
Final means the value can't change (it's "const"), whereas static means it's a property of the class itself, rather than of an instance of the class. So yes, that kind of definition makes sense, and indeed is very common. Final constants like this tend to be static too, as there's little point in having them as instance properties as they can't change.
it's an old question, but i will add an information here for someone who find out this post(like me :)).
Yes it makes sense for a class member to be static and final, but it's nonsense if the variable is declared static in a method(a compile-time error launches).

Final variables accessibility

Why can't Final variables be accessed in a static variables.
At the compile time they are simply substituted directly substituted with their values
so, they should be allowed to use even in static methods
why is this restriction???
static = in the class.
final = doesn't change it's value (but it is of each instance if it's not static).
By examply you can do:
public class Weird
{
private static long number = System.getTimeInMilis();
private final long created = System.getTimeInMilis();
}
Each time you create a Weird object it will contain a different value for created.
But the value of Weird.number will be the time when the class was loaded.
Not all final variables are compile time constants. Only static final variables can be substituted by compiler as compile-time constants. final modifier in certain cases is only used to ensure const-correctness.
And static methods cannot access non-static variables as those variables can have different values for different instances of the same class.
If you're asking why a static method cannot access a final instance variable (on the [incorrect] assumption that final member variables are always set to literal or constant values in the code), its because different instances of a class can have different values for the same final instance variable (which can be set, for example, via the constructor). A static method has no knowledge of any particular instance of the class, and could only access static final variables.

Categories