Java Heap Space vs Stack – Memory Allocation in Java

Filed Under: Interview Questions

Sometime back I wrote a couple of posts about Java Garbage Collection and Java is Pass by Value. After that I got a lot of emails to explain about Java Heap Space, Java Stack Memory, Memory Allocation in Java and what are the differences between them.

java heap space, stack vs heap, java memory model, java memory management

You will see a lot of reference to Heap and Stack memory in Java, Java EE books and tutorials but hardly complete explanation of what is heap and stack memory in terms of a program.

Java Heap Space

Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space.

Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory

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.

Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method.

As soon as method ends, the block becomes unused and become available for next method.
Stack memory size is very less compared to Heap memory.

Heap and Stack Memory in Java Program

Let’s understand the Heap and Stack memory usage with a simple program.


package com.journaldev.test;

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

}

Below image shows the Stack and Heap memory with reference to above program and how they are being used to store primitive, Objects and reference variables.

java memory management, java heap space, heap vs stack, java heap, stack vs heap

Let’s go through the steps of execution of the program.

  • As soon as we run the program, it loads all the Runtime classes into the Heap space. When main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
  • We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
  • Since we are creating an Object in line 3, it’s created in Heap memory and stack memory contains the reference for it. Similar process occurs when we create Memory object in line 4.
  • Now when we call foo() method in line 5, a block in the top of the stack is created to be used by foo() method. Since Java is pass by value, a new reference to Object is created in the foo() stack block in line 6.
  • A string is created in line 7, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
  • foo() method is terminated in line 8, at this time memory block allocated for foo() in stack becomes free.
  • In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also the program ends at this line, hence Java Runtime frees all the memory and end the execution of the program.

Difference between Java Heap Space and Stack Memory

Based on the above explanations, we can easily conclude following differences between Heap and Stack memory.

  1. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  2. Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  3. Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
  4. Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
  5. Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
  6. We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
  7. When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  8. Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

That’s all for Java Heap Space vs Stack Memory in terms of java application, I hope it will clear your doubts regarding memory allocation when any java program is executed.

I have made a video tutorial for java heap space and stack memory, you should watch it to clarify any doubts.

References:
https://en.wikipedia.org/wiki/Java_memory_model
https://blogs.oracle.com/jonthecollector/presenting-the-permanent-generation

Comments

  1. JIT says:

    what is java.lang.object@57?
    why is it in String pool .

  2. M. Manna says:

    Hi Pankaj,

    Very nice explanation and logical. Makes sense.

    https://stackoverflow.com/questions/57380797/cannot-reach-a-temp-table-using-java-sql-statement-object-passed-as-a-map-value

    In this problem, what would you say has happened for memory allocation?

    a) new HashMap() means a new object in the heap. and stack has reference to it.
    b) put(key,value) means the value of the reference to the object.

    However, it seems the object cannot reach certain memory references if retrieved from within the HashMap. Would you be able to shed some light on that?

  3. Gopi Reddy says:

    Hi pankaj,

    As per above explanation ,you said that inside method local variables and data will be stored in stack but if created an object inside a method where will it store. is it store in stack or heap because its a local object?

    Regards,
    Gopi Reddy

  4. DamianPL says:

    What would be more efficent, declaring variable inside loop or outside? How Java handles this? Outside but once seems to be better, right? But is it really?
    Example1:
    for(int i=0; i< 1000000; i++)
    {
    int x = 0;
    //rest of code using 'x' variable
    }
    Example2:
    int x = 0;
    for(int i=0; i< 1000000; i++)
    {
    //rest of code using 'x' variable
    }

    1. Ranjit Sah says:

      Both ways of declaring are same because once the variable is initialized in for loop first statement it will not initialize again so when next iteration happened it will check the third statement in the loop and modify the value and then check the second statement for validation.

  5. Dmitrii says:

    As far as I understand both stack and heap memory stored in the RAM and difference is only in kind of interaction with that memory: random access with heap and LIFO with stack. Is it true?

  6. Pallavi Singh says:

    Very well explained. Crisp.

  7. Rahul Modi says:

    Thanks Pankaj !!!
    Kudos

  8. abhinav says:

    Hi Pankaj,
    can you please explain when the objects created(Like : obj,mem and str) will be eligible for garbage collection and after which line number.

  9. Jheisson says:

    Excellent. Thanks, man!!

  10. DSingh says:

    “Whenever we create any object, it’s always created in the Heap space.” – The opening statement itself is wrong. Read about escape analysis performed by the java compiler. Objects can be created on stack to prevent the overhead of running garbage collector later on.

    1. Rajni says:

      Hi
      I have one question. Let’s say heap memory error we got then how to fix it and what should do for error don’t come

  11. developer learn says:

    Hi, how the Stack (which works as LIFO) behaves when you have multi threads,
    in which different methods can be called at the same time.

    Thanks!

  12. Ahmed Hassan says:

    That was amazing man, thanks and keep on posting these amazing posts.

  13. Robert Zamberg says:

    “Stack memory size is very less compared to Heap memory” ?
    Could have been phrased a lot better. Try:
    “Stack memory is much smaller than Heap memory”

  14. purna says:

    add like, favorite,useful buttons to the articles on this site

  15. TianSirk says:

    Thanks for the excellently simple explanation.
    Is it possible to create a post on how this (respective) concept works in Python and/or JavaScript?
    Just from curiousity to compare this aspect of those highly popular languages.

  16. zari says:

    thanks . it is the best one

  17. Muqthar says:

    Very good article. I am fan of Journaldev website. Do we have mobile app for this?

  18. Divyansh says:

    Fantabulous explanation Sir …Kudos!

  19. veeresh chary says:

    sir one doubt about this one.stack memory hold the reference of the object when it is destroyed no object reference for object which is present in heap memory.so when stack destroyed every object in heap garbage collection or not?

  20. jose says:

    Well Explained, Thank you

  21. shivangi jain says:

    hi,
    well explained but I have a doubt “how static variable and methods get memory”. in stack only primitive variable and reference of the object get stored than how static get called.
    please reply.

    1. arun says:

      Specifically static stored inside pemgen :
      Perm Gen and used to store class structure (runtime constants and static variables) and code for methods and constructors.

  22. Arun Kumar Unique says:

    The best ever explanation of types of memory in java. Explained clearly in a layman language. Thanks, a lot sir.

  23. Maryam says:

    That was really good and clear. Thanks!

  24. Mouaad says:

    Really interesting and very good and clear explanation. Thanks a lot.

  25. Tom says:

    Hi! I tried a little example, however, I get zero, and not 9*4. Could you explain why?

    Integer v = 4;
    Integer b = 9;
    Integer x = 0;

    integerMet (v, b, x);

    System.out.println(” x after integerMet:” + x);

    static public void met (int a, int b, int c){

    c = a*b;

    }

    1. Bangerboi says:

      You declare c as an int in met()s signature, resulting in x being casted to a primitive int.
      The value of the integer x is being given to c, but not the reference.

    2. Abhi1111 says:

      Here u passing the copy of variable x to c, it will remain same in parent method.
      Since integer X reference is not changed , whatever your assigning you are assigning to int c.

  26. Atul says:

    really, good Artical

  27. Neetu Kumari says:

    Easy going approach of explanation…fantastic really!! cleared the doubt..

  28. Saishav says:

    Concise and well explained. Good job!

  29. Sathvik says:

    Good Article .Thank you ):

  30. Samrat says:

    Wonderful article with detailed way of explanation. Easy to understand.

  31. nileshD says:

    thank you very much for such wonderful article.

  32. yubo says:

    Hi PANKAJ,

    thanks for your article! One question, in the fourth bullet point walking through the example:

    “Now when we call foo() method in line 5, a block in the top of the stack is created to be used by foo() method. Since Java is pass by value, a new reference to Object is created in the foo() stack block in line 6.”

    For non-primitive data type, java pass it by reference instead of pass by value right?

    Thanks

    1. Prateek says:

      Even for non-primitive data types, value of (reference)variable (i.e the address/pointer to object on Java heap) is copied between method calls .

  33. bulent says:

    thank you

  34. user says:

    Thank you!

  35. Bhargava says:

    Nicely explained

  36. LW says:

    The video is excellent, thank you!

  37. Satheesh R says:

    Looking like a charm.

  38. mdr says:

    Sir propably i understand you wrong but you said:
    “Any object created in the heap space has global access and can be referenced from anywhere of the application”

    but when i run this code:

    {
    Cat cat1 = new Cat();
    cat1.meow();
    }
    cat1.meow();

    I get out of scope error

    1. Deepak Dhaka says:

      HI Mdr,

      In this case, the error out of scope came because the scope of cat1 is now lost { the property of stack}
      and the object of cat is created in Heap, is now eligible for Garbage Collection,
      By Saying “Any object created in the heap space has global access and can be referenced from anywhere of the application” means anything that is created in Heap is not per Thread bases.

  39. Tal says:

    Hi. Thank you for the great explanation.
    I have a question please:

    Given the following class:

    Class MyClass{

    public int count;
    public int getCount();
    public void incCountBy1();

    }

    Suppose we have only one thread that uses increment method and many threads that uses get method.
    How much time can it take from setting the value to first read?
    Can it take even 1 sec??

    Thanks a lot!

    1. Pankaj says:

      That depends on what is going on inside the method, also is it synchronized to make sure no dirty-read operation happens?

  40. Vijay Jetti says:

    Simply Superb,

  41. Mohamad Ali Al-aaraji says:

    Thanks a lot,you just saved me from getting lost *_*

  42. Alex says:

    Please, can u explain in more detail item 8 , that says Java stack is faster than heap

  43. sonal balekai says:

    super explanation than q

  44. Wing says:

    Very nice and clear! Thanks a lot!

  45. Helal Uddin says:

    very well explained

  46. Sana Shaikh says:

    Wooooow…..well explained…Short and sweet…Thanks alot

  47. Harsh Mudgal says:

    Nice Article and you explained it well.

  48. Kamesh B says:

    Great article.

    1. Java Reader says:

      Great post .Thanks

  49. chandrashekhar says:

    class Demo{
    public static void main(String[] args)
    {
    Demo d=new Demo();
    }

    my question is how many memory allocate for object in heap

    1. Krishna Choudhary says:

      Just one object in heap, and one reference variable in stack.

  50. Needa says:

    This is super helpful!! Thank you so much for the video!
    Really good explanation sir!!

  51. lova says:

    Very Nice Explanation .. Thank you

  52. Jitendra Nandiya says:

    Very nice Example……good

  53. chandan says:

    nice tutorial

    thanks

  54. Parjanya Roy says:

    Great explanation .

    I feel the following link would complete this topic.

    https://www.mkyong.com/java/find-out-your-java-heap-memory-size/

    1. Hardik Doshi says:

      Good reference.

  55. Lukasz says:

    wow, I’m impressed, looks like one of the best examples I’ve seen so far (and I’ve seen quite a few).

  56. sanjay says:

    Thanks pankaj that was very useful. I have related question if you could help. I have a PatriciaTrie list that holds item but there is not limit to the no of item . so when the item size is huge it throws Java heap error . there no way to increase it any more using -Xms am-Xmx . the only thing is that should be cached and proper message to be shown to the user (now it gives me a internal error which is not useful to the user). But the problem is i am not able to catch this exception. Any suggestions.

  57. Murugesh says:

    if we declare a variables in static method then wether it stores on heap or stack. Please explain me.

  58. Narendar says:

    Its very nice explanation.

  59. Eric Wang says:

    Thank you !

  60. Santhosh says:

    Hi Pankaj,

    Its very nice explanation you have given. But I have small query about below code,

    public class MemoryMgmt {
    static Integer a = new Integer(12);

    public static void main(String[] args) {
    Integer b = new Integer(12);
    int c = 12;
    System.out.println(“a==b “+(a==b));
    System.out.println(“b==c “+(b==c));
    System.out.println(“a==c “+(a==c));

    }

    }
    Can you please explain the memory allocation, where those variables are stored in memory.

    1. Tamil says:

      It’s very easy to understand. can you please notify which one is best? Stack or Heap

  61. fred says:

    Very good!

    1. Sanjeev says:

      Stack memory is static, and heap memory is dynamic.(then read properly what is written)
      Second -_ why a method always contain 2 stack, if that method has no body.
      Third– difference between iload and aload. How it is used in stack.
      If any one plz explain.

      1. Sanjeev says:

        In Java variable is always pass by reference not value.

        1. Miroslav Manchev says:

          No, it is always pass by value. In some cases value is a primitive and in some cases value is a reference to an object.

  62. Ajay says:

    Thanks Pankaj. You explained a lot in less time and easy manner.

  63. Sailaja Gudala says:

    Wonderful explanation

  64. Saurabh says:

    Superb Explain Pankaj…… After a long time now i got the proper answer HERE…. Hats Off to you

  65. Jun Hua says:

    Great explanation!

  66. Gafoor says:

    The way explained is easily grasp difference between Heap Space vs Stack – Memory.
    thanks for publishing this article.

  67. LittleLion says:

    String s1=new String(“hello”);
    As I know two objects will be created..but interviewer asked to prove..Pls help me out @pankaj..

    1. Rakesh says:

      java creates an object xyz in memory and then a x object which has the ingredients of object xyz. Then xyz is destryed (lost). So at the end we created 2 object but now we have one !

      1. Roy says:

        Rakesh, thank you for the excellent article.
        For LittleLion’s example, is the way bellow explained correctly or not?

        String s1 = new String(“Hello”);
        “Hello” is a String literal, so JVM creates “Hello” Object and put into the String pool (String interning).
        Then use “Hello” to create another String Object and put into Heap. (String Object).
        Thats why two object created.

        Is this right?

        1. Sridam biswas says:

          yes! Roy you are right!…there is a pool of strings in JAVA by named PermGen .first JVM check that pool for literal(one object) if it is present then it will return to the object(another) by creating new operator..that is the way of string creating object…

  68. Prabhat Kumar says:

    Hi

    Thanks for this awesome brief about heap and stack memory.

    [Based on the above explanations, we can easily conclude following differences between Heap and Stack memory.

    Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.]

    Question: Block for main thread always exists. So as per me stack memory is used only by one thread of execution is not totally correct. Please explain me if I am wrong.

  69. Nagaraju says:

    Good work boss..

  70. Reddeppa Kande says:

    Nice article. a small suggestion in diagram.. can you write steps 1,2,3… so that when step 7 occurs where is the flow can be easily referred for beginners

  71. rungrengreng says:

    Thank for your great work! This is interesting!

  72. Jim Mehta says:

    I watched the video. It’s excellent. But I have a question about who collects Stack Memory? Refrences will always be in the Stack and as soon as the refrence goes out of scope object is available for the Garbage collection but what happens to the refrence memory in the stack?

    1. andrey says:

      Stack frame memory gets deallocated automatically when method exists, because it’s get popped from the stack.

  73. Dheeraj says:

    Hi ,
    What is about
    String args[] variable.
    Will this reference variable will not be listed in stack of main method.

  74. Mrs Afzal says:

    I want to ask how we can elaborate using stack memory and heap memory that two methods are accessing to the same object means (This Reference and Other References to the same object at method level). The purpose is that we want to see the dependencies between two methods using same data.

  75. Melwin says:

    Where would the references to an Object which is an instance variable be stored. For eg.

    Class Memory{
    Memory mem = new Memory();
    public Memory(){
    }
    }

    So, where would be the “mem” reference be stored as it is not tied to any code/method.

    1. Satishchandra Singh says:

      It would be stored in the heap along with all the other contents (instance primitive variables) in the heap.

  76. Sumant Dharkar says:

    where an object and its reference will create for all type of inner classes ?

  77. Selvakumar Esra says:

    Java is both *Pass by value* and *Pass by reference*

    why

    baloon.setColor(“Red”);

    changed the value of color to “Red” when printed in main() method?

  78. Sarvesh Singh says:

    Good work!👍
    Thank you….☺

  79. Farhan says:

    This is good explanation.

    Can you give explanation on this involving array manipulation?

  80. Sid says:

    Loved the way you have written this article. Excellent. Understood the concept.

    Thanks,
    Cheers

  81. Ram says:

    Excellent Boss !!! clear explanation

  82. CS Student says:

    Well done! This really helped me.

  83. Pratap says:

    How much memory is allocated in heap for String ?
    for example if i define String name; in class

  84. Sushant says:

    Hello Pankaj,

    Above explanation of memory allocation is very nice and useful. But I am still confused for following scenario :

    Class A {

    public A(){..}
    public void test(){…}
    public void test1(){..}
    }
    class B extends A {
    public B(){…}
    public void test(){..}
    public void test2(){..}
    }

    now in main method I am creating object in this way :

    A a = new B();
    a.test();
    a.test1();
    a.test2();

    so how memory allocation will work ?

    Thanks in Advance.

    1. mista says:

      that is not going to compile cause class A doesn’t have test2() method.

  85. Lucian says:

    Very good explanation . Keep doing a great job !

  86. Jinesh says:

    Thanks a lot, very well framed. Easy & Simple to understand

  87. Swapnil Suhane says:

    Great work..written in simple way to understand it 🙂
    You can add some advanced level theory also later to make this article perfect like…static/non static context etc

  88. arun says:

    Hi,

    I have one question. i faced this question in one of the interview,

    String s1=new String(“abc”);
    String s2=new String(“abc”);
    int a=10;
    int b=10;
    if a==b is true then why
    s1==s2 is false

    1. Pankaj says:

      1. int is not an object, java handles primitive data types differently, reducing memory footprint by caching the variables, something like String Pool.
      2. String is an object, when new operator is used then a new variable is created rather than checking in String Pool to find some already existing one.

      Based on above points, I think you can clearly see the reason behind the program output.

      1. Niraj says:

        StringBuilder sb1 = new StringBuilder(“Niraj”);
        StringBuilder sb2 = new StringBuilder(“Niraj”);
        System.out.println(“sb1.equals(sb2) “+(sb1.equals(sb2)));

        Then why this is give “false”

        1. Alex says:

          That gives ‘false’ because you are comparing two unique StringBuilder objects, not the actual String values. If you changed your code to this:

          sb1.toString().equals(sb2.toString())

          That should give you ‘true’. Remember, when you have an object (like String) it has an object reference (or ID) as well as an actual “value”. If you compare the object references, you will find they are different, even if the object values are the same.

  89. varun says:

    very good explanation. keep it up!

  90. Rangrao Patil says:

    What is the stack memory allocated to each java program?.
    What is the size of stack memory?

  91. Akanksha says:

    Very well explained

  92. Krishna says:

    Awesome explanation, thank you so much.

  93. selvi says:

    thnks a lot

  94. satyam says:

    simplicity makes this article awesome

  95. Shambhu says:

    You mentioned stand alone program. So My question is once application finish executing, what will happen to String pool, it will be memory or it will remove from heap?

    1. Pankaj says:

      Once application is finished executing, JVM terminates and all the memory is released to OS.

  96. Amit says:

    Nice Article
    my doubt is
    class Memory{
    Memory memory=new Memory();
    }

    where memory is get stored….on heap??

      1. cc10123 says:

        Heap.

        The Memory object would always be created on the heap, regardless of where its reference lives. In your example, the memory (small ‘m’) reference is also on the heap, because it exists as part of the Memory class which is on the heap.

  97. z6qc@yahoo.com says:

    not all objects allocated in Heap ! but static ones ,
    you created Memory and Object instances in a static context so the variables in that context created in heap !
    if you create them in foo method stack memory will be used ,
    please correct this big wrong article!!!

    1. Pankaj says:

      i have no idea what you are talking here.

      1. PriyaYT says:

        We mean that in foo(Object param)
        here param is a local variable of type Object in foo() so it won’t get space in heap but according to ESCAPE ANALYSIS(by java 6e14) that param will be treated similar to those local variables of primitive types in foo() and gets space in stack and not in heap.!!

        Will you please clear this out Sir.
        Thank You.

        1. Anirban Pal says:

          You are right…but escape analysis is not always possible, In this trivial case it was easy for the compiler to find out.

  98. shneha says:

    easily i got understand by reading this… thanks to clear my doubt

  99. Subrahmanyam says:

    Very nice and useful Information.. Thanks a lot 🙂

  100. YangFang says:

    Very well! I learn o lot form this passage!

  101. Arjun says:

    Thanks dude. Thanks for explaining it neat and clear.. (y)

    cheers!

  102. Huy says:

    Thanks man, you made my day 😀

  103. Suraj Shrestha says:

    Nice Article, I have one question. Do we have separate stack memory for each Thread we create?

  104. Java is not only “Pass by Value”, it’s also “Pass by Reference” which depends if primitives are passed or reference objects (the name implies it). If Java would be purely “Pass by Value“, the following program

    public class Test {
    public static void main(String[] args) {
    Integer i = 2;
    System.out.println(“i initialized = ” + i);
    List u = new ArrayList(Arrays.asList(“1”, “2”, “3”));
    System.out.println(“u before method = ” + u);
    test(i);
    test1(u);
    System.out.println(“i outside method = ” + i);
    System.out.println(“u AFTER method call = ” + u);

    }

    private static void test1(List u) {
    u.add(“blah”);
    System.out.println(“u inside method = ” + u);
    }

    private static void test(int i) {
    i = i + 1;
    System.out.println(“i inside method = ” + i);
    }
    }

    …would not print

    u inside method = [1, 2, 3, blah]
    […]
    u AFTER method call = [1, 2, 3, blah]

    1. Purnendu Dutta says:

      In the test(int i) method, when i is being printed its the local variable value which is a copy of i in main(), coming back in main() when i is printed the value still remains same hence its PassByValue.

    2. Miroslav Manchev says:

      In both cases it’s pass by value. In case of ‘i’, value of ‘i’ is copied in the method ‘test()’. In case of ‘u’, value of ‘u’ which is a reference, is copied in method ‘test1()’. Check this code:

      public static void main(String[] args) {
      List list = Arrays.asList(“One”, “Three”, “Five”);
      passByReferenceTest(list);
      System.out.println(list); // n1: What is printed here?
      }

      private static void passByReferenceTest(List list) {
      list = Arrays.asList(“Two”, “Four”, “Six”); // n2
      }

      If pass by reference was possible then the assignment at line n2 would have changed the list reference in main() and therefore “Two”, “Four”, “Six” would have been printed at line n1. Pointers in C behave like that.

  105. Upir says:

    Nice video, thanks !

  106. Pieter says:

    Very well explained, thanks!

  107. Prabhath says:

    Nice Article.

  108. Vel says:

    I have a doubt in static reference and static primitive.
    public static A a = new A();
    public static int b = 5;

    where ‘a’ reference and ‘b’ primitive live (stack or heap). When it will eligible for garbage collection.

  109. Sudhakar says:

    Crisp, Clear and to the point…great article. keep rocking!!!

  110. Alalonks says:

    If it were truly “pass by value” as in the case with c++ then it would be a copy/clone of the object. Calling the foo() method would not affect the blue balloon color value in the main method. But in the example it does because it is “referencing” the memory space in the heap and changing the value. Much like you would when “passing by reference”.

    However, I also see the point of how the value is used (as if a copy/clone were passed in) in the swap method. The manipulation of the balloon colors in the swap method does not affect the balloons variables in the main method. Its almost like its “pass by reference or value”.

    In either case the presentation was awesome as well as the write up. Thanks for your efforts.

  111. Arfeen says:

    Thank you for sharing this article.

    One point i have to raise here. regarding “int i = 1”. Not sure if this is because of “escape analysis” or something else like “interning”. But what i tested it goes to “Heap”.

    Following is my test:

    package immutable;

    public class Immutable_One {

    private int i = 2;

    public int get() {
    return i;
    }
    }


    package immutable;

    public class Immutable_Two {

    private int j = 2;

    public int get() {
    return j;
    }
    }


    package immutable;

    public class ImmutableTest {

    public static void main(String[] args) {

    Immutable_One immutable_One = new Immutable_One();
    int i = immutable_One.get();

    Immutable_Two immutable_Two = new Immutable_Two();
    int j = immutable_Two.get();

    if (i == j) {
    System.out.println("Equal");
    } else {
    System.out.println("NOT Equal");
    }
    }
    }

    The result comes “Equal”.

    1. Tanzy says:

      Its basically because of the caching.
      If we open the Integer class, you can see that value between -128 to 127 are cached.
      In the above program if you put any value outside of the range, you will the desired behavior.

      So as per my thought- What Pankaj mentioned in picture “int i = 1” as part of stack, that must be re-corrected and move it to heap area which can be shared among all thread.

    2. cc10123 says:

      I don’t see how this is a valid test. You’re comparing the value of two primitives, which is a straight up comparison of their values. No references involved at that point. For a better test, make i and j Integer objects, and return Integer objects. Than you’ll see the caching behavior that Tanzy mentions.

      1. Michael says:

        Agree. He is just comparing primitive values, 2 == 2 returns true.

        He should try something like this:

        Integer a = Integer.valueOf(2);
        Integer b = Integer.valueOf(2);
        System.out.println(a.equals(b)); // comparing values
        System.out.println(a==b); // comparing references

        Integer c = new Integer(2);
        Integer d = new Integer(2);
        System.out.println(c.equals(d)); // comparing values
        System.out.println(c==d); // comparing references

  112. Vishnu says:

    Nice artical , greate and simple explanation .

  113. Abhishek Thakur says:

    This is a very nice explanation of Stack and Heap Memory and their differences. I wish you could write a bit about instance variables and static variables. Well Done !

  114. i_know_nothing says:

    Thanks a lot Pankaj.
    This article is very great!

    Can You write a article about Thread-Safe? Because I don’t know Why a global variable is not-thread-safe.

    I reseach very much about it. I use “new” operation but a global variable in that class, it’s not Thread-Safe.

    Thanks in advance!

  115. Dmitry says:

    Thanks for your articles. They are very usefull!

  116. Shaik says:

    On the public static void main(String[] args) – Does the memory for args[] allocated in heap space but the reference is allocated in Stack – Is my understanding correct?

    1. Pankaj says:

      Yes, it’s String array.. hence Object, so stored in Heap memory. However main method contains the references in stack memory.

  117. Sorrowfull Blinger says:

    Awesome ! best place to brush up concepts !

  118. kanaga says:

    This is very useful. Thanks for your great work. public static void main(String[] args) – what about args? It is stored in stack right?

  119. pk says:

    what about static methods and static variables? are they stored in stack or heap memory?

    1. Sankar says:

      class structure and static variables are stored in a separate memory pool area known as Method Area.

    2. johnsonjeven says:

      Static Variables are stored in HEAP. Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap.

      http://net-informations.com/java/cjava/memory.htm

      John

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages