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.

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 an object, it’s always created in the Heap space.

Garbage Collection runs on the heap memory to free the memory used by objects that don’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 the execution of a thread. They contain method-specific values that are short-lived and references to other objects in the heap that is 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 the method ends, the block becomes unused and becomes available for the 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; // Line 5
	} // Line 9

	private void foo(Object param) { // Line 6
		String str = param.toString(); //// Line 7
	} // Line 8


The below image shows the Stack and Heap memory with reference to the 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 the execution of the program.

  • As soon as we run the program, it loads all the Runtime classes into the Heap space. When the 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 the 3rd line, it’s created in heap memory and stack memory contains the reference for it. A similar process occurs when we create Memory object in the 4th line.
  • Now when we call the foo() method in the 5th line, a block in the top of the stack is created to be used by the foo() method. Since Java is pass-by-value, a new reference to Object is created in the foo() stack block in the 6th line.
  • A string is created in the 7th line, 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 the 8th line, 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 ends the execution of the program.

Difference between Java Heap Space and Stack Memory

Based on the above explanations, we can easily conclude the 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.



  1. Pallavi says:

    Hello Sir,
    Is there any way I can download these interview question and answer in pdf format? All Questions from core java to Heap and stack memory!… Let me know if there is a way!

  2. Paik says:

    Thank you for your article
    I have a question.
    I wonder if xxxx.toString() automatically registers value itself to String Pool.
    I remember another column in some where,,, it explained that
    if we want to use xxxx.toString() often, we need to add itern() method to that value
    like this : xxxx.toString()

    1. paik says:

      like this : xxxx.toString() -> xxxx.toString().intern()

  3. unnamed says:

    very nicely explained thanks!

    1. Sangraam Patwardhan says:

      Hey, I have a doubt :
      If the object obj is created on the heap, then for the purpose of this example, we could also directly access obj in the foo() method without allocating a separate object param right? I understand we’ll need to include param if there are more than one objects but here since there’s only one object we could do the same thing without param also right?
      Awesome explanation, by the way!

      1. Omid says:

        No, not really.
        The object itself is stored in the heap memory of course but the variable that refers to this object is a local variable that is stored inside the `main` method.
        Basically, the scope of this variable is Method and as you might know, a variable with method scope is only accessible within the body of the method that is being declared.
        In this example when the call to the `foo` method happened, the variable `obj` is set as the argument of the method to simply send the memory address of the object that this variable is pointing to.
        Now the `foo` method also has the memory address of the object (made a reference to it) and it can interact with it as well.

        Hope that does make sense.

  4. sinthujan says:

    Thanks a lot, sir.
    can you please explain,
    when a static variable comes in it loads at the class area. Where is the class area?

    1. Sumit sharma says:

      All static things take memory in Method Area.

  5. VISHAL PUNIR says:

    How does heap space look like during polymorpohism in java specially in case of upacasting?

  6. JIT says:

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

    1. Venkatesh.E says:

      Object.toString() returns a string value with “classname” + hashcode. So “java.lang.Object@xxxxxxxx” is a string and hence it is stored in ‘String Pool’.

  7. M. Manna says:

    Hi Pankaj,

    Very nice explanation and logical. Makes sense.

    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?

  8. 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?

    Gopi Reddy

  9. 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?
    for(int i=0; i< 1000000; i++)
    int x = 0;
    //rest of code using 'x' variable
    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.

  10. 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?

  11. Pallavi Singh says:

    Very well explained. Crisp.

  12. Rahul Modi says:

    Thanks Pankaj !!!

  13. 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.

    1. Venkatesh.E says:

      GC doesn’t run at any specific interval and its execution is totally random. The simple rule of GC is, it looks for the Objects in heap/String Pool which doesn’t have any references at the time of GC scan. If in-case GC runs just after foo() methods returns, the string inside the string pool which ‘str’ was holding/referencing will be garbage collected.

      Others objects are not GC as the program terminates after main() ends.

  14. Jheisson says:

    Excellent. Thanks, man!!

  15. 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:

      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

  16. 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.


  17. Ahmed Hassan says:

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

  18. 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”

  19. purna says:

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

  20. 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.

  21. zari says:

    thanks . it is the best one

  22. Muqthar says:

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

  23. Divyansh says:

    Fantabulous explanation Sir …Kudos!

  24. 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 when stack destroyed every object in heap garbage collection or not?

  25. jose says:

    Well Explained, Thank you

  26. shivangi jain says:

    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.

  27. Arun Kumar Unique says:

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

  28. Maryam says:

    That was really good and clear. Thanks!

  29. Mouaad says:

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

  30. 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.

  31. Atul says:

    really, good Artical

  32. Neetu Kumari says:

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

  33. Saishav says:

    Concise and well explained. Good job!

  34. Sathvik says:

    Good Article .Thank you ):

  35. Samrat says:

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

  36. nileshD says:

    thank you very much for such wonderful article.

  37. 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?


    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 .

  38. bulent says:

    thank you

  39. user says:

    Thank you!

  40. Bhargava says:

    Nicely explained

  41. LW says:

    The video is excellent, thank you!

  42. Satheesh R says:

    Looking like a charm.

  43. 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();

    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.

  44. 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?

  45. Vijay Jetti says:

    Simply Superb,

  46. Mohamad Ali Al-aaraji says:

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

  47. Alex says:

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

  48. sonal balekai says:

    super explanation than q

  49. Wing says:

    Very nice and clear! Thanks a lot!

  50. Helal Uddin says:

    very well explained

  51. Sana Shaikh says:

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

  52. Harsh Mudgal says:

    Nice Article and you explained it well.

  53. Kamesh B says:

    Great article.

    1. Java Reader says:

      Great post .Thanks

  54. 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.

  55. Needa says:

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

  56. lova says:

    Very Nice Explanation .. Thank you

  57. Jitendra Nandiya says:

    Very nice Example……good

  58. chandan says:

    nice tutorial


  59. Parjanya Roy says:

    Great explanation .

    I feel the following link would complete this topic.

    1. Hardik Doshi says:

      Good reference.

  60. 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).

  61. Rajat says:


  62. 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.

  63. Murugesh says:

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

  64. Narendar says:

    Its very nice explanation.

  65. Eric Wang says:

    Thank you !

  66. 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

  67. 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.

  68. Ajay says:

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

  69. Sailaja Gudala says:

    Wonderful explanation

  70. Saurabh says:

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

  71. Jun Hua says:

    Great explanation!

  72. Gafoor says:

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

  73. 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…

  74. Prabhat Kumar says:


    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.

  75. Nagaraju says:

    Good work boss..

  76. 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

  77. rungrengreng says:

    Thank for your great work! This is interesting!

  78. 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.

  79. Dheeraj says:

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

  80. 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.

  81. 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.

  82. Sumant Dharkar says:

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

  83. Selvakumar Esra says:

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



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

  84. Sarvesh Singh says:

    Good work!?
    Thank you….☺

  85. Farhan says:

    This is good explanation.

    Can you give explanation on this involving array manipulation?

  86. Sid says:

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


  87. Ram says:

    Excellent Boss !!! clear explanation

  88. CS Student says:

    Well done! This really helped me.

  89. Pratap says:

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

  90. 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();

    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.

  91. Lucian says:

    Very good explanation . Keep doing a great job !

  92. Jinesh says:

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

  93. 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

  94. arun says:


    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:


          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.

  95. varun says:

    very good explanation. keep it up!

  96. Rangrao Patil says:

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

  97. Akanksha says:

    Very well explained

  98. Krishna says:

    Awesome explanation, thank you so much.

  99. selvi says:

    thnks a lot

  100. satyam says:

    simplicity makes this article awesome

  101. 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.

  102. Amit says:

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

    where memory is get stored….on heap??

      1. cc10123 says:


        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.

  103. 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.

  104. shneha says:

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

  105. Subrahmanyam says:

    Very nice and useful Information.. Thanks a lot 🙂

  106. YangFang says:

    Very well! I learn o lot form this passage!

  107. Arjun says:

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


  108. Huy says:

    Thanks man, you made my day 😀

  109. Suraj Shrestha says:

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

  110. 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);
    System.out.println(“i outside method = ” + i);
    System.out.println(“u AFTER method call = ” + u);


    private static void test1(List u) {
    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”);
      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.

  111. Upir says:

    Nice video, thanks !

  112. Pieter says:

    Very well explained, thanks!

  113. Prabhath says:

    Nice Article.

  114. 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.

  115. Sudhakar says:

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

  116. 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.

  117. 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) {
    } 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

  118. Vishnu says:

    Nice artical , greate and simple explanation .

  119. 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 !

  120. 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!

  121. Dmitry says:

    Thanks for your articles. They are very usefull!

  122. 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.

  123. Sorrowfull Blinger says:

    Awesome ! best place to brush up concepts !

  124. 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?

  125. 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.


Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content