Integer and Integer Array storage on stack/heap - java

I'm curious to know how Integer and Integer Array are stored on the stack/heap in java, is there a link someone could point me to? Or could someone explain it to me please.
Update 1:
and how does this affect the way an integer and an integer array are passed as arguments to methods in Java.
Thank You

Whenever you declare a variable within a local scope(a method) it gets put on the stack.
That is: Type myVariable will push space for a new variable onto that methods stack frame, but it's not usable yet as it's uninitialized.
When you assign a value to the variable, that value is put into the reserved space on the stack.
Now here's the tricky part. If the type is primitive, the value contains the value you assigned. For example, int a = 55 will literally put the value 55 into that space.
However, if the type is non primitive, that is some subclass of Object, then the value put onto the stack is actually a memory address. This memory address points to a place on the heap, which is where the actual Object is stored.
The object is put into the heap on creation.
An Example
private void myMethod()
{
Object myObject = new Object();
}
We're declaring a variable, so we get space on the stack frame. The type is an Object, so this value is going to be a pointer to the space on the heap that was allocated when the Object was created.

Variables contains only references to this objects and this references stored in stack in case of local variables, but data of objects the point to stored in heap.
You can read more, for example, here: link

method variables are stored in Stack. Objects , in the other hand are stored in the Heap as the image below demonstrates it.
That's why if you get StackOverFlowException, that means you have declared too many variables in a method or you are calling too many methods in a recursive call. And if you get Java Heap Space Error, that means you are creating more objects than you do.
For Stack and Heap explanation, I recommend this link

Related

Java- Where does the variable name or Identifier gets stored, Stack or Heap?

Where does the identifiers or variable name gets stored in java? I understand that objects get stored in heap and variable gets store in heap or stack depending on the type and scope of variable. Can we debug or write any program to confirm it?
Thanks & Regards
Names of fields are stored as part of the class metadata, in formerly-PermGen now-Metaspace.
Array elements don't have names, only numbers. (Cue Patrick McGoohan.)
Names of method and constructor parameters and local variables and handler parameters are stored only in the debug-symbols info in the classfile, if that option is selected. They aren't needed by the JVM because the compiler has mapped them to stack-frame slot numbers used in the bytecode.
Variable names are stored in "method area" (which is part of the permgen.) along with other class meta-data.
There is a special area to hold class meta-data called method area. This is part of permgen (which was in heap before java 8) now it has been moved to metaspace
Variable names are stored in method area of permanent generation. Object are always stored in the Heap, but object reference stored in the stack.

Primitives vs Objects in Java

I'm trying to do some practice for an exam and need some help (did I do them correctly? If not, why?) on these problems about java primitives and java objects. These are all true or false.
The following variable declaration is a reference to an object which is dynamically allocated and stored in the heap: int x = 7;
False, because it is pass by value since int is primitive
The following variable declaration is a reference to an object which is dynamically allocated and stored in the heap: Integer x = 7;
True, because it is referencing an object stored on the heap
If you pass the variable ‘x’ as declared in (1) to a method, that variable is passed by reference, and its value may be modified by the called function.
False,because Java only does pass by value
If you pass the variable ‘x’ as declared in (2) to a method, a copy of that
variable is created in the heap, and passed to the function, so that the function’s object
reference is pointing to a distinct place in memory.
True, because variable is in the stack but it is pointing to a place in the heap
Thank you all for the help.
(4) is false for two reasons:
"a copy of that variable is created in the heap" is false. Only objects are on the heap. The local variable in a function is not on the heap. The value of that variable is simply passed, i.e. copied into the stack frame of the called function.
"the function’s object reference is pointing to a distinct place in memory." is false. The function's reference will point to the same place in memory. That's the point of passing -- the value of the variable inside the function is the same as the value that was passed. The value of a reference is where it points.
4) If you pass the variable ‘x’ as declared in (2) to a method, a copy
of that variable is created in the heap, and passed to the function,
so that the function’s object reference is pointing to a distinct
place in memory.
Okay, this can be a little sketchy. If dealing with objects, you are not creating a copy of the object and passing the copy to the method. You are creating a copy of the reference to the object, and passing that over by value.
Actually there is a reason 2 is wrong - but its probably not the reason the person who set it expects.
Integer x = 7;
Will get turned into:
Integer x = Integer.valueOf(7);
Which will re-use a cached value for all integers in the range -128 to +127 inclusive. (It may reuse them for other values too).
So you will get a reference to an object which is present in the JVM implementation dependant cached storage for common Integer values.
False because Integer is an object. So you will be passing just the reference to the object address in the function. It is standard in Java.

What exactly is null in Java memory [duplicate]

This question already has answers here:
What is null in Java?
(14 answers)
Closed 9 years ago.
If I declare some string variable like
String str = null;
Is there memory allocated for variable str?
If allocated, how many bytes will be allocated?
If not allocated, how does the JVM know that there is some variable called str been declared?
If allocated and if there is null value inside the memory, then what exactly is the representation of null in binary?
When you do something like:
String str = null;
The only thing allocated is a reference to a string (this is analogous to a string-pointer in languages which contain pointer-types). This reference is a 32 or 64 bit variable (depending upon your hardware architecture and Java version) which resides on the stack (probably, depending upon the exact context in which your declaration is placed).
No memory should be allocated for the null itself, because null is not actually a valid object instance. It is simply a placeholder that indicates that the object reference is not currently referring to an object. Probably it is simply the literal value 0, such that assigning an object reference to null is equivalent to setting a pointer type to NULL in C/C++. But that last bit is conjecture on my part.
Null is the value of a reference that is not bound to an object.
Space is allocated for the reference variable itself, regardless of its value. Null is merely a value that fits within this space.
To answer each question for the specific example.
Yes, there is space allocated for the variable str.
The size of the memory allocated for the reference variable is probably four bytes.
It is allocated, and the JVM follows the instructions of the compiled code to access it.
It doesn't matter.
Take a look at this Java IAQ (infrequently asked question) "Is null an object?".
To answer your questions:
Only memory to store the reference is allocated
The java standard doesn't specify how much memory a reference takes up (although, in practice it is usually 32 or 64 bits depending on your JVM - although some JVMs try to beat this)
The memory representation of null doesn't matter, since you can't do bit level operations on it (or assign it to anything that isn't a reference)
Java works on references. Think of String str=null as you have pointer in C, but not exactly pointer.
Now internal representation dependes upon the JVM. It is not easy to calculate the size of reference. The implementation differs per JVM so there is no point extracting that low level info.
After doing this line:
String str = null; // or String str;
Only a reference of type String is allocated into the stack. null means that you don't assign any value (object) to the reference str into the heap.

Local variable of type string is stored on stack or heap?

I have two local variables in a method as follows,
int i=10;
String test="test";
As far as i know as these variables are local to only a specfic method,these should be stored on a stack,will the string type is also stored on a stack?
The variable itself (the reference to the String instance) will be stored on the stack.
The String instance (which contains the char[] with the actual data) will usually be stored in the heap. It is up to the JVM to optimize this, though. It could be a String from the permgen pool, or if escape analysis is done (and the String is guaranteed to not leave the local scope), it might choose to allocate it on the stack as well.
This is the case for all objects and arrays. Only primitives are different (because they are passed around as value, not as a reference to a data structure allocated elsewhere).
The stack frame will contain the value of the int and the (reference) value of the String. The object that the String reference value points (e.g. the thing that represents the string's characters, length and so on) to will be stored in the heap.
(It is probably easiest to explain this in a picture ... if someone could contribute a link ...)
As stated above, the reference will be on the stack. In Sun's JVM, the actual data would be stored in the perm gen area (since the String in question is a String literal), and would also be added to a weak HashMap which resides on the heap. This is the behavior for interned Strings in the Sun JVM.

Steps in the memory allocation process for Java objects

What happens in the memory when a class instantiates the following object?
public class SomeObject{
private String strSomeProperty;
public SomeObject(String strSomeProperty){
this.strSomeProperty = strSomeProperty;
}
public void setSomeProperty(String strSomeProperty){
this.strSomeProperty = strSomeProperty;
}
public String getSomeProperty(){
return this.strSomeProperty;
}
}
In class SomeClass1:
SomeObject so1 = new SomeObject("some property value");
In class SomeClass2:
SomeObject so2 = new SomeObject("another property value");
How is memory allocated to the newly instantiated object and its properties?
Let's step through it:
SomeObject so1 = new SomeObject("some property value");
... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as:
String tmp = new String("some property value");
SomeObject so1 = new SomeObject(tmp);
// Not that you would normally write it in this way.
(To be absolutely accurate - these are not really equivalent. In the original the 'new String' is created at compile time and is part of the .class image. You can think of this as a performance hack.)
So, first the JVM allocates space for the String. You typically don't know or care about the internals of the String implementation, so just take it on trust that a chunk of memory is being used to represent "some property value". Also, you have some memory temporarily allocated containing a reference to the String. In the second form, it's explicitly called tmp; in your original form Java handles it without naming it.
Next the JVM allocates space for a new SomeObject. That's a bit of space for Java's internal bookkeeping, and space for each of the object's fields. In this case, there's just one field, strSomeProperty.
Bear in mind that strSomeProperty is just a reference to a String. For now, it'll be initialised to null.
Next, the constructor is executed.
this.strSomeProperty = strSomeProperty;
All this does is copy the reference to the String, into your strSomeProperty field.
Finally, space is allocated for the object reference so1. This is set with a reference to the SomeObject.
so2 works in exactly the same way.
Determining Memory Usage in Java by Dr. Heinz M. Kabutz gives a precise answer, plus a program to calculate the memory usage. The relevant part:
The class takes up at least 8 bytes. So, if you say new Object(); you will allocate 8 bytes on the heap.
Each data member takes up 4 bytes, except for long and double which take up 8 bytes. Even if the data member is a byte, it will still take up 4 bytes! In addition, the amount of memory used is increased in 8 byte blocks. So, if you have a class that contains one byte it will take up 8 bytes for the class and 8 bytes for the data, totalling 16 bytes (groan!).
Arrays are a bit more clever. Primitives get packed in arrays, so if you have an array of bytes they will each take up one byte (wow!). The memory usage of course still goes up in 8 byte blocks.
As people have pointed out in the comments, Strings are a special case, because they can be interned. You can reason about the space they take up in the same way, but keep in mind that what looks like multiple copies of the same String may actually point to the same reference.
Points to remember:
When a method is called, a frame is created on the top of stack.
Once a method has completed execution, flow of control returns to the calling method and its corresponding stack frame is flushed.
Local variables are created in the stack.
Instance variables are created in the heap & are part of the object they belong to.
Reference variables are created in the stack.
Ref: http://www.javatutorialhub.com/java-stack-heap.html

Categories

Resources