Is a final variable instantiated everytime - java

When we have a final instance variable of a class, is it instantiated for each object created of the class or just created once and referred?
And what is the case if the final variable is a local class variable??

The final modifier simply indicates that the variable can be assigned once and never again. It has no impact on the instantiation; the rules are the same as for normal variables. All the final modifier does is prevent the value being assigned a second time.
Examples below.
private final List myList = new ArrayList();
The list will be instantiated each time this is run, i.e. each time the enclosing class is instantiated.
public void bob() {
final List myList = new ArrayList();
}
The list will be instantiated each time this is run, i.e. each time the method bob is invoked.
private static final List MY_LIST = new ArrayList();
Again, the list will be instantiated each time this is run. As this is also a static field initializer, this code will be run when the class is first loaded. So, for simplistic programs, this will be run once -- in scenarios where multiple class loaders are in play (e.g. app-servers etc), however, this will be run once each time the class is loaded in a new class loader.

Final variables is instantiated for each instance of the class. The values once assigned to them may not be changed. These variables may be initialized once, either via an initializer or an assignment statement.
What you are referring to are the static variables. These variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.
Taking these two together, you can have a static final variable for the class. This basically means that the value assigned to the variable once assigned is constant and that it would be attached to a class rather than an instance of the class.

Instance variables, class variables, and local variables are used to refer to three different things, so calling a variable an "instance variable of a class," or "local class variable" is confusing.
An instance variable belongs to an object. Whether it's final or not, space is allocated in every instance for it. If it's final, a value must be assigned during construction, and the variable can be assigned only once.
A class variable belongs to the class as a whole. There's only one variable, regardless of the number of objects of that class, and all instances can refer to it. Declaring a variable as static means that it belongs to the class. Like instance variables, a static class variable can be declared final. Then it must be assigned a value once and only once when the class is initialized.
A local variable is declared within a method, and the variable occupies space in the method stack frame—although that variable may hold a pointer to an object in the heap. Local variables can be final, which means they can be assigned only once. Also, if a local variable is final, it can be referenced by inner classes instantiated in the method.

Variables are not the ones that are instantiated. Classes are instantiated. Variables are initialized. Instance variables must be initialized by the time the the object is constructed and if they are final you won't be able to reassign values to them. If it's an instance variable then each instance of the class will have it's own copy, otherwise if it's static then there will be only one copy which will belong to the class itself.

Related

Is a static data member inherited in Java?

Will a static variable from the parent class be inherited as is to the child class, or will a new variable be created?
For example, should a static counter variable of class A and class B extends A give the same value (if we have not defined a new counter for class B) ?
No, Static variable does not behave like non-static variables. If you change value of static variable with one of the inherited class it will effect all other inherited class data.
Cause static variable is created only once. Even though you are creating multiple objects the static variables are not created again and again. They are created at starting time of execution and stored. When ever you access static variable you will get same variable.
i.e
if you are accessing as B.count or C.count you will get same variable.
So you are having only one variable then you can't maintain count separately for two objects in single variable.

Java - Is it ok to instantiate class objects inside class? [duplicate]

Why can we access a static variable via an object reference in Java, like the code below?
public class Static {
private static String x = "Static variable";
public String getX() {
return this.x; // Case #1
}
public static void main(String[] args) {
Static member = new Static();
System.out.println(member.x); // Case #2
}
}
Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.
If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.
If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.
The reason that it is allowed is that the JLS says it is. The specific sections that allows this are JLS 6.5.6.2 (for the member.x cases) and JLS 15.11.1 (in both cases). The latter says:
If the field is static:
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a class variable initializer (§8.3.2) or static initializer (§8.7), then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
Why are these allowed by the JLS?
Frankly, I don't know. I can't think of any good reasons to allow them.
Either way, using a reference or this to access a static variable is a bad idea because most programmers are likely to be mislead into thinking that you are using an instance field. That is a strong reason to not use this feature of Java.
In your first and second cases you should reference the variable as x or Static.x rather than member.x. (I prefer Static.x.)
It is not best practice to reference a static variable in that way.
However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.
This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.
static variables are otherwise called as class variables, because they are available to each object of that class.
As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.
The instance object could always refers to static members as it belongs to class which global(shared) to its instances.
This logically makes sense although it is not interesting practice. Static variable is usually for enforcing single declaration of variable during instantiation. Object is a new copy of Class with other name. Even though object is new copy of class it is still with characteristics of the (uninstantiated) Class (first invisible instance). Therefore new object also has that static members pointing to the original copy. Thing to note is: New instance of StackOverflow is also StackOverflow.

What is the difference between class variables and member variables in Java

There is not much to explain. The title is enough to explain the question. I got this on an interview today.
What are class variables and member variables in Java?
Thank you!
As Zhuinden said they probably meant static variables instead of class variables. For member variables, an instance of the class is needed in order to access the variable. For example if I had a class Foo, and it had a member variable int bar, the only way I could access it is by doing something like
Foo foo = new Foo();
doSomething(foo.bar);
However, if I have bar was a static variable, that means that I can access it even though I don't have an instance of the object. I would access it like this:
doSomething(Foo.bar)
without having to create an instance of Foo.
See here
A member variable is one per object, every object has its own copy of instance variable while a class variable is one per Class, every object of that class shares the same class variable..
A class variable also called as static variable is initialized when the JVM loads the class probably take an example static block if there is no main method in your program while this is not the case with your member variables.
Class variables should be used when you don't want to have copy for each instance while
member variables should be used when you want separate copy for each instance of object.
From point of garbage collection class variables have a long life as class variables are associated with the class and not individual instance.
class variables are cleaned up when the ClassLoader which hold the class unloaded. This is very rare..while in case of member variables they get cleaned up when the instance is cleaned up. Hope this helps.

When will I use a Class Variable in Java v.s an Instance Variable?

Here is a generic class that I have defined, what I would like to know is when I am creating more specific classes for instance a CAR class when would I use a Class Variable? My personal understanding of a class variable is that a single copy of a class variable that has been declared in a class will be declared using the keyword static, and that each object that has been instantiated from the class will contain a single copy of the class variable.
An instance variable allows each instance of a class / object that has been created from the class to have a separate copy of the instance variable per object?
So an instance variable is useful for defining the properties of a class / data-type e.g a House would have a location, but now when would I use a class variable in a House object? or in other words what is the correct use of a class object in designing a class?
public class InstanceVaribale {
public int id; //Instance Variable: each object of this class will have a seperate copy of this variable that will exist during the life cycle of the object.
static int count = 0; //Class Variable: each object of this class will contain a single copy of this variable which has the same value unless mutated during the lifecycle of the objects.
InstanceVaribale() {
count++;
}
public static void main(String[] args) {
InstanceVaribale A = new InstanceVaribale();
System.out.println(A.count);
InstanceVaribale B = new InstanceVaribale();
System.out.println(B.count);
System.out.println(A.id);
System.out.println(A.count);
System.out.println(B.id);
System.out.println(B.count);
InstanceVaribale C = new InstanceVaribale();
System.out.println(C.count);
}
}
My personal understanding of a class variable is that a single copy of a class variable that has been declared in a class will be declared using the keyword static, and that each object that has been instantiated from the class will contain a single copy of the class variable.
No. It's not that "each object will contain a single copy". A static variable is associated with the type rather than each instance of the type. The instances don't have the variable at all.
There's exactly one variable (assuming you're only loading it from one classloader) however many instances of the type there are. No instances? Still one variable. A million instances? Still one variable.
Static variables are mostly useful for constants or constant-alikes - things like loggers, or "the set of valid prices" etc. Things which don't change over the course of the application. They should almost always be final in my experience, and the type should be an immutable type (like String). Where possible, use immutable collections too for static variables - or make sure the variable is private and that you never mutate the collection within the class.
You should avoid using static variables to store global changing state. It makes code much harder to test and reason about.
Static variables are used to store values that are shared between all instances of the class.
If this is not the case, it should be an instance variable.
1. Every object of the class will have its own copy of Instance Variable,its One per Object.
2. But static variable will be shared by all the objects of the class, its One per Class.
3. Now i will give 2 example where these two will have importance.
Instance variable:
Consider a Gaming Program, then each player will have different Name, Scores, Weapons-power, Stage reached, etc.....
Static variable:
Consider a Banking program, where each client will be given an Id, which is greater and unique than the previous one, so static variable will be apt for this.

When are static variables initialized?

I am wondering when static variables are initialized to their default values.
Is it correct that when a class is loaded, static vars are created (allocated),
then static initializers and initializations in declarations are executed?
At what point are the default values are given? This leads to the problem of forward reference.
Also please if you can explain this in reference to the question asked on Why static fields are not initialized in time? and especially the answer given by Kevin Brock on the same site. I can't understand the 3rd point.
From See Java Static Variable Methods:
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.
Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.
What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.
In case of inner classes, they can not have static fields
An inner class is a nested class that is not explicitly or implicitly
declared static.
...
Inner classes may not declare static initializers (§8.7) or member interfaces...
Inner classes may not declare static members, unless they are constant variables...
See JLS 8.1.3 Inner Classes and Enclosing Instances
final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.
final class Demo
{
private final int x;
private static final int z; //must be initialized here.
static
{
z = 10; //It can be initialized here.
}
public Demo(int x)
{
this.x=x; //This is possible.
//z=15; compiler-error - can not assign a value to a final variable z
}
}
This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.
Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.
See:
JLS 8.7, Static Initializers
JLS 12.2, Loading of Classes and Interfaces
JLS 12.4, Initialization of Classes and Interfaces
The last in particular provides detailed initialization steps that spell out when static variables are initialized, and in what order (with the caveat that final class variables and interface fields that are compile-time constants are initialized first.)
I'm not sure what your specific question about point 3 (assuming you mean the nested one?) is. The detailed sequence states this would be a recursive initialization request so it will continue initialization.
The order of initialization is:
Static initialization blocks
Instance initialization blocks
Constructors
The details of the process are explained in the JVM specification document.
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(when the Classloader load the class for the first time) .
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
Starting with the code from the other question:
class MyClass {
private static MyClass myClass = new MyClass();
private static final Object obj = new Object();
public MyClass() {
System.out.println(obj); // will print null once
}
}
A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.
Now back to initializing the class: obj is made a reference to a new real object, and we're done.
If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.
The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.
The static variable can be intialize in the following three ways as follow choose any one you like
you can intialize it at the time of declaration
or you can do by making static block eg:
static {
// whatever code is needed for initialization goes here
}
There is an alternative to static blocks — you can write a private static method
class name {
public static varType myVar = initializeVar();
private static varType initializeVar() {
// initialization code goes here
}
}

Categories

Resources