Friday, February 19, 2016

[Java] Heap and stack in memory

Heap and stack are managed by JVM, programmer cannot access the operations.

Stack is faster than Heap, but the data in stack should has a certain size and life time.
Data in Stack can be shared by several stacks and several threads.

Heap is more dynamic : size of data can be allocated dynamically, the compiler does not need to know the life-circle. Disadvantage is should be allocated in run time , read/write slower.

Stack : is for storing the local variables and method calling
Heap: is where the variable refers to (the object created)

See original image
ex :

public class Memory {
    public static void main(String[] args) { // Line 1
        int i=1; // Line 2
        Object obj = new Object(); // Line 3
        Memory mem = new Memory(); // Line 4
        mem.foo(obj); // Line 5
    } // Line 9
    private void foo(Object param) { // Line 6
        String str = param.toString(); //// Line 7
        System.out.println(str);
    } // Line 8
}
 
 


Stack -- > java.lang.stackOverFlowError
Heap --> java.lang.OutOfMemoryError

Tow types of data in Java :
Primitive type :  int, short,  long, byte,  float, double, boolean, char (no String!!)
This type of data is defined like : int a =5; long b = 255l; named  Automatic Variable . For example, the  Automatic Variable 3, we know it's size and we know its life circle(in the code block), so we store them in stack :
1 it's faster
2 it can be shard
ex :
int a= 3; int b=3; b=2;

int a=3; ---> compiler want a Automatic Variable 3, it cannot find in the stack, so , it created a 3;
int b=3; ----> compiler can reuse the 3 created last step.
 b= 2; ---> compiler create a 2 and refer the b to this 2. so the a is still 3.

 Class types : classes, like : Integer, Object...use new to create an object
 All these objects are stored in HEAP , object is created dynamically (create when you need)
String is special:
String s = "string";
the compiler will try to find if we have already "string"    in the run time constant pool:
ex :
String str1="abc";
String str2="abc";
System.out.println(str1==str2);//true
 
True for "==" means they have the same address (equals() is for testing values)
So String is immutable! when you change its value, JVM has created a new String in the String pool.

String str1="abc";
String str2=new String("abc");
System.out.println(str1==str2);//false!!! str2 is in heap, str1 is in string pool



No comments:

Post a Comment