Java constants and static modifiers - java

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.
*/
}

Related

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

Final attribute of a final datatype?

What happens when I declare something like:
public static final String forma = "Rectangular";
Isn't it redundant? Being String a final class, what would it change not setting forma as final? For static, I think it is not making any change.
final make sure reference is not assigned to new value.
If you don't make it final, it is valid to assign some other value to forma (or) you can do some operation on Rectangular and assign results back to forma
See String is a final class,and final keyword makes references final not object final.
Final object means it can't be altered but final reference means it can't be assigned to another object after first assignment.
Being final means you can not modify the object String s="hello", "hello" is the string object and it cant be modified, but about s if its a non-final reference and i do thing like:s=s.concat("bing") then, "hello" is taken can concatenated with "bing" object and then assigned to s means "hello" and "bing" objects are not modified they lost their references and non-final reference s is now referring to a new object "hellobing".
I surely wanna help you more if you find this interesting.
For object-types 'final' modifier means that REFERENCE to this object cannot be changed, not it's value!
Isn't it redundant?
No, it is not redundant. It is constant. Every keyword of this statement has meaning. final make it immutable, static make it class variable and public make it globally accessible.
The final keyword is heavily overloaded, and means very different things in different contexts:
On fields and local variables, it indicates that the content of a reference cannot be changed. (This is different from immutability.)
On classes, it indicates that the class cannot be subclassed.
On methods, it indicates that the method cannot be overridden in subclasses.

Java Code Static Final variable usage

I've got two classes below. Both have one variable 'reply' with a getter. There is no setter method for this variable. Only difference is in ClassOne, the variable is static final.
So whats the difference and which one is preferred?
public class ClassOne {
private static final String reply = "Success";
..
public String getReply() {
return reply;
}
// no setter
}
and Class 2
public class ClassTwo {
private String reply = "Success";
..
public String getReply() {
return reply;
}
// no setter
}
UPDATE 1:
What I want to know is that when there is no setter for a variable, should the variable be declared as static final for optimization? or does it not matter?
should the variable be declared as static final for optimization?
final certainly, not only for optimization but for clarity and because it can make your object immutable, which is always a good thing to have.
static completely changes the nature of the field and has nothing to do with the existence of setters: do you want only one instance of that field, or do you need one per instance of your class?
Non static example: a Person has a name, which is a constant (for a given person = per instance), so you can use a non static final field, which you only set once when creating a new Person:
private final String name;
Static example: Whenever you don't have a name for a Person, you want to use a default value - that is a global constant which is shared among all persons that don't have a name and you can use a static final field:
private static final String NO_NAME = "John Doe";
When you set the variable as final, you are telling everybody (the compiler, the runtime) that it cannot be changed. This can help a lot with optimizations like inlining all of the occurrences of the variable with its value.
When you have a constant string which can not be changed, you should make it a static final string.
Static means that less memory is needed for instance of the class, because the instances don't need individual copies.
Final allows some optimizations and thus makes your program faster.
There are few things good to know:
final variables can be checked by compiler that they are not accidentally changed.
references to non-static variables are contained in instance so there is small needless memory consumption in addition
static variables are shared across all instances of the same class, so you can be sure that all instances work with the same value
final static variables, especially the Strings are linked in compilation time so they need not to be dereferenced at runtime from the field. Due to that it cannot be changed even by the reflection, because such field is not used at runtime.
Setting the reference to final ensures you can't change the reference. Note however that if the object referred to is mutable then you could still change that (not in this instance, since Strings are immutable).
I normally make fields final and initialise them in the constructor. By favouring immutability my classes are easier to debug and are more likely to be safe in threaded environments. It's easier to remove the immutability constraint than add it.
I also do this for method arguments. Rarely (ever) do I want to change a method argument, and making them final will catch inadvertent assignments.
I try not to use static except for final constants. Unless it's something like a logger, I don't really want one instance per class, and (of course) this doesn't work in the case of multiple classloaders. It's also getting close to the singleton anti-pattern, and this impacts on easy testing and (potentially) threading.
The fact that you make the variable static means that a single instance of that variable will be shared among all the instances of ClassOne, as the variable is bound to the class itself, not to its instances. Apart from any JVM optimisations, you'll have a single instance of reply for every instance of ClassTwo.
First one is Constant you need to know value of it at compile time.
private static final String reply = "Success";
second is just simple member variable. So any case first one is preferred since second one will create value for each object.
Assuming that you intended **private final String reply** in second case
A final variable 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 a "blank final" variable.
In second case you can also declare and initialize it in constructor
private final String reply;
You can read more about it here

difference between final and static variables with reference to their use in innerclass

this is regarding final variables in inner class, but instead of declaring variable as a final if we declare variable as static out side the method ,assuming that the method is static. Then what is the difference between declaring as static outside method or final inside method to be accessed in innerclass. will they make any difference or they function similarly. Which one is the best one to use. I will be waiting for reply.
Thanks in Advance
static variables will keep their value across different instantiations of the inner class. Lets say you declare a static variable in inner class A and assign it the value 1 and then in the method call increment its value to 2. When another instance of this inner class is created it will have the value of A as 2.
In case of final variables you can assign the value only once when declaring (in your case i.e., declaring inside a method). What compiler does as a result of this is that it inlines the value i.e., wherever you this variable the variable is replaced with its value (since you cannot change its value).
I suggest using final variable wherever possible. but static has its won needs and usage depends on usage scenario.
Final variables are instance variables, whose values cannot be changed after it is initialized ( either in the c'tor or while declaring ).
But Static variables belongs to a class. This 'll be shared amoung all instances. So when you change the value of a static variable in an instance it gets reflected in all the instances.

Categories