Final attribute of a final datatype? - java

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.

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

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

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

Why must a final variable be initialized before constructor completes?

Why must a final variable be initialized before constructor completes?
public class Ex
{
final int q;
}
When I compile this code I get error like this
err:variable q might not have been initialized
The official reason is that it is defined by the Java Language Specification 8.3.1.2:
A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
A blank final is a final variable whose declaration lacks an initializer (i.e. what you describe).
The value of a final variable can only be set once. The constructor is the only place in the code for a class that you can guarantee this will hold true; the constructor is only ever called once for an object but other methods can be called any number of times.
Because final prevents you from modifying variables, but it has to be initialized at some point, and the constructors is the right place to do so.
In your case, it would be called a blank final because it is not initialized when declared.
A final variable must be initialized at the declaration or in a constructor.
If it has not been initialized when the constructor returns, it may never be initialized, and may remain an uninitialized variable. The compiler cannot prove it will be initialized, and thus throws an error.
This Wikipedia excerpt explains it well:
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. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases. (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.)
The final keyword applied to a field has one of two effects:
on a primitive, it prevents the value of the primitive from being changed (an int can't change value)
on an object, it prevents the "value of the variable", that is, the reference to the object, from being changed. That is to say that, if you have a final HashMap<String,String> a, you will only be able to set it once, and you won't be able to do this.a=new HashMap<String,String>(); again, but nothing keeps you from doing this.a.put("a","b"),s since that doesn't modify the reference, only the content of the object.
The final modifier prevents your from changeing the variables value, hence you have to initialize it where you declare it.
The language specification contains specific guarantees about the properties of final variables and fields, and one of them is that a properly constructed object (i.e. one whose constructor finished successfully) must have all its final instance fields initialized and visible to all threads. Thus, the compiler analyzes code paths and requires you to initialize those fields.
If an instance variable is declared with final keyword, it means it can not be modified later, which makes it a constant. That is why we have to initialize the variable with final keyword.Initialization must be done explicitly because JVM doesnt provide default value to final instance variable.Final instance variable must be initialized either at the time of declaration like:
class Test{
final int num = 10;
}
or it must be declared inside an instance block like:
class Test{
final int x;
{
x=10;
}
}
or
it must be declared BEFORE constructor COMPLETION like:
class Test{
final int x;
Test(){
x=10;
}
}
Keep in mind that we can initialize it inside a consructor block because initialization must be done before constructor completion.
Final modifier does not allow to change your variable value. So you need to assign a value to it at some place and constructor is the place you have to do this in this case.
The moment the constructor completes execution, the object is 'open for business' - it can be used, its variables can be accessed.
The final keyword on a variable guarantees that its value will never change. This means, if the value is ever read, you can be sure that the variable will always have that value.
Since the variable can be accessed (read) at anytime after the execution of the constructor, it means it must never change after the constructor has executed - just it case it has been read.
Thus, it must, by then, have been set.

Why declare a reference to an instance of a final class as being final?

What is significance of second line :
public final class A {}
final A obj1=new A();
If A is a already immutable, why would one possibly want to make obj1 final? (just to make it stick to a unique memory reference? ).
final in the first line means that the object is closed for extension...i.e. you can't subclass it.
final in the second line means you can't reassign the variable.
First, A is not immutable of you just declare it final.
Then, final variables cannot be changed. If obj1 is a field this enforces mutability (unlike the final class).
If it is a local variable it means you can safely use it in anonymous classes (otherwise the compiler can't be sure it won't get change sometimes before/while the anonymous class body is executed)

Categories