This question already has answers here:
Difference between Static and final?
(11 answers)
Closed 4 years ago.
Suppose a class contains a final variable. Why is new space allocated for final variable every time an object of the class is created even though its value can't be changed? Why its memory allocation is not like a static variable?
Consider this example:
public class Example {
public final int someNum;
// constructor
public Example(int n) {
someNum = n;
}
}
Here in this example, every object of this class might have a different value for someNum, even though it is a final variable. Therefore new space must be allotted for every instance of the class.
While you can't assign a new value to a final variable, each instance of the class can have a different value, so each instance needs to allocate its own memory for its own member.
For final variables in Java, it is not necessary to assign a value when declared. A final variable can be assigned value later, but only once. As a different value can be assigned it needs different memory allocation.
Related
This question already has answers here:
What is the difference between constant variables and final variables in java?
(4 answers)
Closed 2 years ago.
I'm a newbie learning Java currently being introduces do the switch/case construct. The book I'm reading uses the following example:
int eingabe = 256;
final byte einKleinesByte = 2;
final char einKleinerCharacter = 'c';
final short einKleinesShort = 500;
switch(eingabe) {
case einKleinesByte:
case einKleinerCharacter:
case einKleinesShort:
The explanation is that these 3 constant are defined with the help of the keyword final, which is essential, because variables cannot be used for the cases.
My question is, what is the difference between final byte einKleinesByte = 2; and byte EIN_KLEINES_BYTE = 2; as they are both defined as constants?
Thanks for the help!
The main difference between final variable and a constant (static and final) is that if you create a final variable without static keyword, though its value is un-modifiable, a separate copy of the variable is created each time you create a new object. Where a constant is un-modifiable and have only one copy through out the program.
They are not both defined as constant. You can easily change the value of the byte EIN_KLEINES_BYTE. You are using the snake uppercase standard which is usually used to define constant but in reallity, there is nothing that stops you from changing the value of this variable. Only the keyworld final would prevent that.
// would work fine
int MY_CONSTANT = 2;
MY_CONSTANT = 3
// Will throw an error
final int myConstant = 2;
myConstant = 3
// recommended
static final int MY_CONSTANT = 2
byte EIN_KLEINES_BYTE is not a constant, it can be overwritten.
final byte EIN_KLEINES_BYTE can't be, that is a constant.
a final variable can not be reassigned. For primitive types, or for unchangeable types, this means that they are constant in value.
For most objects, it doesn't. You can change the state (value) of those objects, but you can't change the object itself for another.
Just by putting a variable name in upper case, does not make it a constant.
EDIT: if you want a final variable to be the same for the entire application, you'll have to declare it as static, as well.
final simply means that the value, once assigned, can not be changed or reassigned
concerning constants, i would refer you to this question
This question already has answers here:
Java, What is the difference between assigning null to object and just declaration
(2 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Why is it possible to declare a variable without an initial value?
(8 answers)
Closed 3 years ago.
I'm currently doing the mooc java course and I'm not able to understand why exactly we need to include new Random() part after declaring a new new variable randomVar with the class type Random?
private Random randomNum = new Random(); // Why this?
private Random randomNum; //Instead of this?
In Java there is no implicit calling of constructors. In your example, the variable will either be non-initialized or initialized to null (such as when declaring a class field). ie:
void foo() {
Random r; // r never gets initialized
}
...
class Foo {
Random r; // gets initialized to null
}
If you want to get an instance of an object, then new must be called somewhere, either directly during the variable declaration, or by assigning it from another variable which was already instantiated.
This question already has answers here:
Does initialized java array go onto stack or heap?
(2 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
Is the following code safe in Java? My concern is due to the fact that in function f() variable arr is allocated on stack and as such is deallocated upon leaving the scope but is still referred to outside the scope.
public class Main {
public static class Array {
public final int[] arr;
public Array(int arr[]) {
this.arr = arr;
}
}
public static Array f() {
int arr[] = {1, 2, 3};
return new Array(arr);
}
public static void main(String[] args) {
Array a = f();
System.out.println(a.arr[0]);
System.out.println(a.arr[1]);
System.out.println(a.arr[2]);
}
}
In f you create variable arr which is an int array and then construct an Array object which ends up having a pointer to that same primitive int array.
Function f then ends returning the Array object - the variable arr goes out of scope but the memory location it points to is still referenced by the Array object being returned so the memory location cannot be garbage collected. The return value is then assigned to variable a of your main method meaning that the memory that arr originally pointed to still cannot be garbage collected until the main method ends. This is shown by the fact that the values of what was originally called arr are output as part of the main function
Short answer, yes this is safe to do. Memory is garbage collected when nothing is left pointing to it / when it is no longer referenced
It's safe because java uses references to track it. Even when arr goes out of scope in f, data is still referenced by a. Garbage collector will not clean it in the time it takes for the return value to be assigned, either.
On a side note, try to avoid using the same name both as local variable and field.
This question already has answers here:
Where is allocated variable reference, in stack or in the heap?
(4 answers)
Closed 5 years ago.
please let me know where does my static reference, static primitive, object reference , object itself and method itself along with class information is stored.
*please let me know who does this memory management?
*please let me know what gets stored in permgen place?
*please specify the storage space(heap or stack) which will be allocated for all the object references,object, primitive data (for both static and non-static types) for the following program.
package training;
public class Memory {
static int var =1;
static String s="hi";
static Threadtutorial th;// this is another class in the same project,consider this an object.
static Threadtutorial tt = new Threadtutorial();
int are =2;
int d;
static float value;
public static void main(String[] args) {
// TODO Auto-generated method stub
int a;
int b=1;
Threadtutorial th;// this is another class in the nsame project,consider this an object.
Threadtutorial tt = new Threadtutorial();
final int var =1;
value=8;
}
void somemethod(){
int ne=3;
String something;
Object ref;
Object dereee= new Object();
}
static void another(int b){
int c=b;
Object ref2;
Object der= new Object();
}
}
Where things are conceptually per the JLS is one thing and deterministic, where they are physically in the JVM is another and varies with circumstances.
The easy part is where things are conceptually. Type definitions including method areas, space for static fields, and other type-level information are in the class area of heap. Method arguments and other method control information live on the stack as methods are invoked. Instances live on the heap.
Physically those things can live in various places at different times or even disappear altogether. Member variable values might live for a while on the stack or in registers while the rest of the object is not even in memory. Method calls might vanish altogether. The runtime interpreter/compiler combination has wide leeway in how it handles program logic.
Have you actually tried researching your question? What have you come up with?
I have scenario like this
public class Test{
static int a;
int b;
public static void main(String[] args){
Test t1 = new Test();
Test t2 = new Test();
}
}
What will be the variables in object t1 and object t2?
As per my understanding since variable a is a static variable it will be both in object 1 and object 2.
And b will be created separate copy for both the objects.
But when I assign a value to variable b ie(int b=1) and call it like System.out.println(t1.b), System.out.println(t2.b)
Instead of getting an error I am getting 1 as output from both the objects.
Why is that?
As per my understanding since variable a is static variable it will be both in object 1 and object 2.
No. It's not in either object. It exists without reference to any particular instance at all. Although Java allows you to refer to it "via" a reference, e.g. int x = t1.a; you shouldn't do so. You should instead refer to it via the class name (test.a in your case - although you should also start following Java naming conventions) to make it clear that it's static.
And b will be created separate copy for both the objects.
Yes.
But when I assign a value to variable b ie(int b=1) and call it like System.out.println(t1.b), System.out.println(t2.b) Instead of getting an error I am getting 1 as output from both the objects.
Well that's because you've basically given it an initial value to assign for each new object. That's entirely reasonable. There are still two independent variables:
t1.b = 2;
t2.b = 3;
System.out.println(t1.b); // Prints 2
System.out.println(t2.b); // Prints 3
Static variables are class members that are shared among all objects. There is only one copy of them in main memory. Static variables are created at run time on Heap area.
In case of yours...
int b = 1;
it's an assignment at class level, making 1 the default value for variable b(In normal case default value is 0). hence when you print it, its gives you the ans as 1 not error.
int b = 1; //initialized b to 1 for all obj of class Test
System.out.println(t1.b); // Prints 1
System.out.println(t2.b); // Prints 1
No, a static variable is not an instance variable but a class variable.
That's, every instance of this class shares the same reference of those variables.
Take a look at Understanding Class Members
Here a is static variable and b is instance or non-static variable.
For static variable, only one copy is created for all objects, where as for instance variable, one copy is created for each object.
Here when b=1, for every object of that Test class, one copy is created and it can access it through its object name. So output will be 1.
Of course that is exactly what it should output.
If you assign say,
int b=1;
that assignment is at class level, making 1 the default value for variable b.
However, if you assign like this:
t1.b=1;
that will assign 1 to only the copy of variable b in object t1.
Try it.
static variables are class variables. static variable are stored in static memory.
static variables are created to access inside main() method.
The static variables can be accessed by their class name, if they are present in outside class.
class sv {
static String name = "abc";
}
public class staticvariable {
static int t;
public static void main(String[] args) {
System.out.println("static variable is - "+t);
System.out.println(sv.name);
t=100;
System.out.println(t);
}
}