memory allocation of a variable in java? - java

suppose i have a code snippet like this:-
class A {
void help() {
Help helper = new Help();
}
}
in the above case, the object reference helper will be allocated memory in the stack.
now if i have a case like this
class A {
Help helper = new Help();
}
in this case, helper will not be allocated memory inside of a stack frame(I am sure of that).
will it behave like an instance variable and will be allocated space inside of an object on heap.

This type of declaration is only located to your instance. the helper attribute will be assigned each time you instanciate you Class A.
It is definitely an instance variable. it goes in the heap
In order to separate the instance and the variable you can use static attribute. Then it is linked to the class so it goes in the code segment.

Yes, You are correct. In the second case, the Help object will behave as an instance variable of the class.
When you declare the object inside the function, stack memory is used up (local variables). Whereas for instance variables ,heap memory is used.

Yes, in the second case the memory will be allocated to object helper as soon as the object of class A will be initialized but in the first case the memory will be allocated on the stack to the function named void help() and will be destroyed as soon as the function ends because helper object is a local variable to this function.

There is a difference between object and reference variable. For example:
//Here 'helper' is the reference variable
Helper helper = new Helper ();
Whenever we create any object (new Helper()), it’s always created in the Heap space and it's reference (helper) in the Stack space.
Java Stack memory is used for execution of a thread. They contain
method specific values that are short-lived and references to other
objects in the heap that are getting referred from the method.
(Source: https://www.journaldev.com/4098/java-heap-space-vs-stack-memory#java-stack-memory)
So the two objects are stored in the heap but their two reference variables are stored in different stacks.

Related

Using new keyword without defining variable in java

The following code is used to create an object of a class within a variable:
ClassName obj = new ClassName();
But what if we do not create any variable and just type the following?
new ClassName();
When I used it, there was no error. But what it actually does when no variable is created?
Both methods create an object, but the second method has no name for it.
When you create an instance of the ClassName, the difference between your first method and second method is that for your first method, you can actually access variables and methods within the class.
For example,
ClassName obj = new ClassName();
System.out.println(obj.x);
Where ClassName
class ClassName {
public static int x = 2;
}
The benefit of this approach is you can access the variables within the class. If you used the second approach, then the instance would have no name, so you wouldn't be able to access the variables.
new ClassName() calls a special method called a constructor and, like any method, it returns a value1. The value that it returns is an instance of ClassName. You can choose to assign that value to a variable, or not, just as you can do with the return value of any method. So you simply need to decide whether you need to assign the returned value to a variable, or not. If you do, then you need the first statement, namely:
ClassName obj = new ClassName();
And if you don't need to assign the returned value to a variable, then you can use:
new ClassName();
1 - a method can return void which means it doesn't actually return a value
To answer to your question I think is useful to see how objects are managed by JVM during execution.
All java objects reside in a JVM area called heap and can ( note that this is not mandatory ) be pointed by one or more variables.
The variables that hold references to objects reside on another area of JVM called stack.
Every time an instruction like new SomeClass(); is executed a new object is allocated on that area. When the heap area becomes full, garbage is collected and during the garbage collection objects that are no longer pointed by a variable are cleared in order to free space on heap for new objects.
What is the difference between your two instructions?
1- ClassName obj = new ClassName();
It allocates a new object on heap that is pointed by the obj variable on stack.
2- new ClassName();
It just allocates a new object on heap with no variables on stack that point to it.
When can be useful to use the second approach?
According to this, using the second approach could be useful if you want just to allocate a new object on heap without using it through a variable for example to test memory management on your program. Actually the second approach is used when you want to create a "one-shot" object and use a method or a variable of it in the same instruction improving the garbage collector efficiency and avoiding unexpectedly get an OutOfMemoryError exception like:
using once time an object variable:
System.out.println(new ClassName().x)
or
executing once time an object method:
new ClassName().evaluateResult();
NOTE: In this specific case you probably could evaluate instead to make a static method on the class.
Another usage can be to put new elements on a collection as follow:
final List<ClassName> objectList = new ArrayList<>();
for(int i=0; i<10; i++){
objectList.add(new ClassName());
}
You can may ask: What happens instead to objects that are pointed by
at least one variable like ones created with first approach?
All references that are held in a variable are naturally dropped when the variable goes out of scope so they became eligible for garbage collection automatically ( according how their scope is managed on code ).

Instance created inside of a Method

I have not been able to find any reliable literature on this but i'm curious as to where an object is stored if its created inside of a method ? on the stack or on the heap in java 8?
public class A {}
.
.
.
public class B {
public void test(){
A m = new A();
}
}
I know that normally only local primitives, reference variables and function calls are stored on the stack and that objects are stored in the heap
So I'm assuming that one of the following two scenarios is true either
Case 1 : Objects instantiated in a method are as usual stored in the heap with a reference to that object in the stack then when the function finishes the object reference goes out of scope and the object in the heap is then available for garbage collection
Case 2 : Objects instantiated in a method are stored in the stack then are available for garbage collection when function finishes
I strongly suspect its case 1, it wouldn't make sense to store an object in a stack, the only reason I have doubts is because ive come across some literature saying on the stack and others on the heap
Thanks for your feedback ahead of time
The local reference variable is on the stack, and the object is in the heap.
Note that your question title,
Instance declared inside of a Method
is misleading since objects/instances are declared nowhere -- only variables are, and the object created in a method can be placed on fields into a collection, or anywhere it's needed. And so there is no guarantee that the object should be GC'd when the method exits.
All the objects are stored in the heap ... the garbage collector runs whenever there's a lack of memory so it get rid of the objects that are not used anymore and there's no reference to them too.
Your assumption specified in Case 1 is correct. Here is a good source on memory allocation in java.
Java Heap Space vs Stack – Memory Allocation in Java
If they are not immediate "values" (not like an int property in a class object), only their reference values are stored in the stack. their actual values and structures are stored in the heap.
these are stored in the stack as they are;
int i=10;
float f=10.00;
bool b=true;
these will have only references on the stack, they will reside in the heap (any kind of class variable is part of the structure and be created on the heap altogether);
int[] ii={1,2,3};
double[] dd = new double[10];
String s="String!!";
Object o=new Object();
when passed to a method, Values are copied to a new stack variable (unless converted to a reference object). References are also passed to a copycat stack variable, but since they are references, both will redirect to the same object (unless copied to a whole new object manually).
this part might not be of interest in the topic, you decide
In the following code, number is created on the stack and copied to a new stack value for the method, hello created on the heap, passed by reference to s then two strings concatenated on another heap address and it now holds this new address (strings are immutable). The Point object is not immutable as strings, so it can be changed anywhere you referenced it as they are created on the heap to access freely.
class Point{ int x;int y; Point(int x,int y){this.x=x;this.y=y;} }
public class TestClass{
public static void main(String []args){
int number=5;
String hello="Hello";
Point point = new Point(2,4);
Print(number,hello,point);
System.out.println(hello+" "+number+" "+point.x+" "+point.y);
}
public static void Print(int i,String s,Point p){
i+=5;
s+="World!";
p.x+=2; p.y+=2;
System.out.println(s+" "+i+" "+p.x+" "+p.y);
}
}

Does Java allocate memory for class' fields even if they are not initialised yet?

I'm trying to perform a small memory optimisation for my Java game. It is a bit unclear to me how does Java allocate memory when it comes to fields:
public class Test {
private HashMap<String, String> info;
public Test(boolean createInfo) {
if (createInfo) {
info = new HashMap<String, String>();
}
}
}
As you can observe, the HashMap info is initialised if you pass true to Test's constructor.
Does new Test(true) take up more memory than new Test(false)?
Which leads to the more general question:
When you create a field in a class, does Java "reserve" the necessary memory for such field in case it is initialised, or will it do nothing until you actually initialise it?
There is this question: Is memory allocated for unused fields in Java? which seems to be almost exactly what I am looking for, but they seem to be asking what already instantiated fields that are unused, whereas I am asking for uninstantiated fields that may or may not be used.
Does new Test(true) take up more memory than new Test(false)?
Yes.
When you create a field in a class, does Java "reserve" the necessary memory for such field in case it is initialised, or will it do nothing until you actually initialise it?
There are two things here - the HashMap reference, and the HashMap object. Both of them require memory. When a class instance is created, memory is allocated for all its instance variable. In case of int type field, it will allocate 4 bytes, similarly for a reference, it will allocate some memory for that reference (I don't know exactly how much it is). But surely it will allocate memory for the fields.
Then when you initialize the fields in the constructor, the actual HashMap object is created, which will again take up memory to store the object.
The field itself has space for a reference to an object, and that space is allocated when the containing class (Test) is instantiated, even if the value placed in that field is null. Your example code doesn't create an extra object whose reference will go in that field when you pass in false.

Where does class, object, reference variable get stored in Java. In heap or in stack? Where is heap or stack located?

I understand that variables of a method are stored in stack and class variables are stored in heap. Then where does the classes and objects we create get stored in Java?
Runtime data area in JVM can be divided as below,
Method Area : Storage area for compiled class files. (One per JVM instance)
Heap : Storage area for Objects. (One per JVM instance)
Java stack: Storage area for local variables, results of intermediate operations. (One per thread)
PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread)
Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread)
Following are points you need to consider about memory allocation in Java.
Note:
Object and Object references are different things.
There is new keyword in Java used very often to create a new object. But what new does is allocate memory for the object of class you are making and returns a reference. That means, whenever you create an object as static or local, it gets stored in heap.
All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap.
Classes loaded by ClassLoader and static variables and static object references are stored in a special location in heap which permanent generation.
Local primitive variables, local object references and method parameters are stored in stack.
Local Functions (methods) are stored in stack but static functions (methods) goes in permanent storage.
All the information related to a class like name of the class, object arrays associated with the class, internal objects used by JVM (like Java/Lang/Object) and optimization information goes into the Permanent Generation area.
To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems.
All objects in Java are stored on the heap. The "variables" that hold references to them can be on the stack or they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.
The Class objects that define Classes are also heap objects. They contain the bytecode that makes up the class (loaded from the class files), and metadata calculated from that.
The Stack section of memory contains methods, local variables and reference variables.
The Heap section contains Objects (may also contain reference variables).
after short google, I found a link to describe it, yes a youtube video link. ^_^
http://www.youtube.com/watch?v=VQ4eZw6eVtQ
The concept is quite simple :
Instance variables (primitive, Wrapper classes, references, objects (non-static)) - Heap
Local Variables , references - stack
Other data objects like : Class metadata, JVM code, static variables, static object references, static functions etc which earlier used to be in Permgen Space (till Java 7) are now being moved to Metaspace in JAVA 8.
PS : Metaspace is part of native memory, so no need to worry about OOM:Pergem Exeption now.
For more details : https://siddharthnawani.blogspot.com/
Local variables(method variables) + methods live on the stack. While Objects and their instance variable live on the heap.
Now, Reference variable can be local variable(if created inside method) or instance variable(if created inside class, but outside method). So reference variable can be anywhere, either stack or heap.
According to JVM Specification,
The classes and it's own constant pool, i.e static variables are stored in Method Area.
Here class means nothing but bunch of fields, methods and constants, these methods are in the form of instructions are stored in Method Area and can be identified by an address.
Objects are nothing but a filled class template that will be created in Heap Area, but the object reference is created in Stack.
public class Sample{
int field;
static int constant;
public void test(){
int localVariable=10;
Sample samp=new Sample();
}
}
In the example,
sample.class will go to Method Area, that means 'field', 'constant' and method 'test' are allocated in Method Area.
When the execution is started,
The object created by new Sample() will go to Heap but 'samp' is just a object reference which goes to stack and holds the address of object which is present in the Heap
For more information please check this link,
JVM Specification
In Java, a variable can either hold an object reference (s in String s="OOO" holds the reference to the object "OOO") or a primitive value (i in int i=10 holds 10). These variables can either be on the heap or the stack, depending on whether they are local or not and which flavor of the JVM you are using.
In the Java Virtual Machine 8 specification document (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html), the memory organization pertaining to this is as follows.
Every Java thread has its own JVM stack.
It holds local variables and partial results, and plays a part in
method invocation and return.
There may be object references as well in the stack. The
specification does not differentiate between a primitive variable
and a reference variable as long as it is local. This stack is used using
units of data called frames. However,
Because the Java Virtual Machine stack is never manipulated directly
except to push and pop frames, frames may be heap allocated.
Therefore, it is upto the implementation of the JVM specification (like OpenJDK or Oracle), where the frames are located.
Every JVM instance has a heap. The heap is
... the run-time data area from which memory for all class instances and
arrays is allocated.
The actual memory holding the objects' data resides on the heap. The
heap is shared among all the JVM's threads. This also includes object
references which are part of objects ie instance variables.
For example, take the following classes.
class Moo{
private String string= "hello";
}
class Spoo{
private Moo instanceReferenceVariable = new Moo();
public void poo(){
int localPrimitiveVariable=12;
Set<String> localReferenceVariable = new HashSet<String>();
}
}
Here the object being referred to by the variable instanceReferenceVariable
would be on the heap, and hence all the instance variables of this object, like
string, will also be on the heap. Variables localPrimitiveVariable and
localReferenceVariable will be on the stack.
Method Area: The method area is a restricted part of the heap which
... stores per-class structures such as the run-time constant pool,
field and method data, and the code for methods and constructors,
including the special methods used in class and instance
initialization and interface initialization.
Run-time constant pool: This is a part of the method area.
Hope this was able to clarify things.

Java Where do Local variables,Object references,instance variables

I am currently learning the memory concepts of java, the stack and the heap, I know that local variables and method calls lived in a place called stack. and objects lived inside a heap. but what if that local variable holds an object? or has an object reference?
public void Something(){
Duck d = new Duck(24);
}
Does it still live inside a stack? and where do instance variables live? please keep it simple as possible. thank you.
Local variable d (allocated on stack) contains a reference to an object of class Duck. In general objects are allocated on the heap.
Java 6e14 added support for something called 'escape analysis'. When you enable it with -XX:+DoEscapeAnalysis switch, then if JVM determines that an object is created in a method, used only in that method and there is no way for reference to the object to 'escape' that method - that is, we can be sure that the object is not referenced after method completes - JVM can allocate it on stack (treating all its fields as if they were local variables). This would probably happen in your example.
Fields are allocated with the rest of the object, so on the heap or on the stack, depending of escape analysis results.
Object reference variables work. just like primitive variables-if the reference is declared as a local variable, it goes on the stack.else if refrence is instance variable it will go into the heap within an object.

Categories

Resources