Podcast Lookup

Java Memory Management Explained | Stack, Heap, Method Area & Program Counter

The Java Developers Hub

  • December 3, 2026
  • 1 h 4 min
  • Episode 21
Episode page
About this episodeUnderstanding Java memory management is essential for becoming a skilled Java developer. Every Java application uses different memory…
Understanding Java memory management is essential for becoming a skilled Java developer. Every Java application uses different memory areas to store objects, manage method execution, and keep track of program instructions.
In this episode, we take an in-depth look at the Java Runtime Data Areas, exploring how the JVM organises and manages memory during application execution.
You'll learn how Stack Memory, Heap Memory, Method Area, and the Program Counter (PC) Register work together to support Java applications. We'll also explore how memory allocation and execution differ across these areas.
Whether you're a beginner progressing into advanced Java concepts or an experienced developer preparing for technical interviews, this tutorial will help you understand what happens inside the JVM when Java programs run.

Transcript

From the publisher

This transcript comes from the podcast’s own feed, shown as the publisher wrote it.

Java Memory Management Explained | Stack, Heap, Method Area & Program Counter

00:00—
  1. Speaker 1

    Yes, so let's start. Welcome back Coder Army to our Java series. And today we are going to read a very interesting topic, Memory Management in Java. Till now we were writing normal programs, but we didn't worry about how things would be stored inside. We just discussed about heap memory and stack memory. We never went into its depth. So today in this video, we will go into every memory's depth and understand how it is and what it does. Right, you will enjoy it a lot. And again, this is very important from an interview perspective. And whenever you write an application in the real world, then your application becomes more optimized due to memory management. So let's quickly start this. Yes, so let's talk about memory management. Before that, First of all, why do we need memory to run a program? It's obvious that whenever we write our source code in our program, we will declare a lot of variables, use them, create objects. If you are creating an object, then one object is created in your heap memory, which is a real object. The reference variable of that object is again and stack memory, otherwise it will be covered in variables. Apart from all these, when you write your classes, right? Now imagine when you create an object, the class data, the methods, these are also stored somewhere, right? So basically, the metadata of the class level, where is it stored? Right? We will be able to fetch what all objects are stored in our class etc. So, we will have to store so many details somewhere, right? We will need memory for that. So, if we talk about how JVM uses memory. So, it uses memory in three ways. To allocate one memory, we can allocate a variable in it. For example, if we write int x equal to 4 in our code, Right? So what we are saying is that I have to declare an x variable whose value is 4. So somewhere in our memory, x variable will be made. Its value will be assigned in 4. So here it helped in allocating memory. Apart from this, you can also talk about a user-defined data type. Let's say you wrote student s1 equal to new student. So this means that you are telling JVM that I have to declare a student type object in heap memory. Its reference variable which will be s1 will be in stack memory. We have seen this many times. So somewhere our JVM works to allocate memory. Right? Apart from this, it works to use the existing memory. Right? Which we can write update as well. What does it mean? Like if I say, here if I wrote int x equal to 4, then if I write in this statement, let's say x equal to x plus 1. So what I'm saying is, go to memory, Where ever your x is stored, bring that and increment 1 in it. So let's say x stored 4 here, I am asking you to fetch it, you fetched x, you increased the value from 1, so your value became 5, and then you stored 5. Right? This must be the same work. So we can use the memory or update it, which is our existing memory. And apart from this, we can also delete or de-allocate the memory. What does de-allocate mean? See, it's a simple meaning. As I made a new student here, Imagine that if I have a heap memory in which I made an object of a student, right? So when I made this object, I used it. After that, I don't need this object anymore. So there must be some way that I will tell JVM to de-allocate it or to free it. Okay? I don't need this. If you want to store something else and memory is limited, then you can use it. Right? We call that de-allocate. Or we can say free the memory. So our JVM does these three things with memory. Allocate, helps to use it, and de-allocates our use. Now, if we talk about the core problem, which was in the languages before Java, like C, C + +, but Java improved it, that was manual memory management. If you come from the background of C, C + +, you must already know what manual memory management is. Those who don't know, let me tell you. In C, C + +, if you declared an object in heap, if you created an object in heap, then it was your responsibility to de-allocate or free this object. Let's say you use a keyword like free or ptr, and you write a code like this, then it means that CC + + used to force you to de-allocate the memory manually. You will allocate it yourself using new keywords, but you will also have to de-allocate it yourself using delete keywords or free keywords etc. But Java thought that this is very error prone. If you give the responsibility to the user to de-allocate the same memory, then this will be very error prone. It will happen many times that the user forgets to de-allocate the memory, or he de-allocates the memory quickly, or something is lying in the memory, let's say it is a very large object, it is an object of 1 MB, and it is lying in the memory, let's say many such objects are created in the memory, and we have not de-allocated it, our heap memory will be full. So it creates a lot of problems when you give the responsibility to the developer to de-allocate the memory. So Java said, no, I won't do that. I will bring a very interesting concept of garbage collection. So basically Java said, I will give JVM one more responsibility of garbage collection. You just write your code, focus on your logic, De-allocating or freeing the memory is my responsibility. Right? So basically JVM will take care of which object I want to free and which object I don't want to free. Right? Now obviously this will happen in heap memory because objects are created there. We will see that in depth. But what I mean to say is that JVM takes the responsibility of de-allocating the memory. As a developer, this is not your responsibility. Now, many people have this doubt in Java that if in Java, the work of memory de-allocation, basically the work of memory management is handled by JVM itself and the developer doesn't need to do anything, then why do we have to study about memory management? So basically, why memory management? And look, it has a very simple answer. Even though JVM will handle the work of memory management itself, but it is in your hands to write a good optimized code. Look, we don't have infinite memory in Java, right? So it's not like that, no matter how much memory you consume, our Java code will run very optimistically, right? So, Java has some limited memory. You have to use that. And while using that, you have to write a good code. Now, the meaning of memory management is that Java can free the memory itself. Let's say, you don't let the memory get free. What does it mean? You imagine that what you did? You created an object in a heap memory. Let's say something like this. Okay? Now this object is very big, let's say it takes a space of 4MB. And if there are many objects like this, then you know how much memory you are consuming. Now think, when will any garbage collection clear this memory? When you stop using this object. But if any reference variable, let's say S, is pointing it at a time, then Java's garbage collection will feel that it is still being used. It can't delete it on its own, right? Then if you call anything on S, it will be destroyed. Let's say this S is a student object and it has two fields. Let's say one is name and let's say one is roll number. So you can use this S to call s.name or s.roll number. Right? So Java can't clear it by itself until you remove these references. Right? There should be a time when no one is pointing it as a reference. Then only the garbage collection will be able to clear it. Right? So it is very important to learn memory management in Java too. So that you can write good code. You can avoid memory leakage. Memory leakage is also there in Java. Some people think that there is no memory leakage in Java. Let's say you made a list. Let's say list of students. And you call it list equal to new ArrayList. This is how you made a list in Java. Now imagine that you add elements to this list. You add list.add once. Then add the list. Right? And you keep reusing this list. How many number of times? Obviously your list will keep growing. In your heap memory. This list type object. It will consume a lot of memory. It can be 100 MB. Or it can be 200 MB. It can consume a lot of memory. Right? And it will keep growing. Now you assume. You never remove the reference of this list. Right? You have used it. But till now it is in memory. It is surrounding you. Right? Or it can be in main method. So it will never end. Until the program is done. In that case, it will keep leaking the memory, your heap will keep getting full and at some point you will get out of memory error. So we have to understand when we have to de-reference the memory so that we can clear the garbage collection of Java. We will see this in depth. Apart from that, imagine if you don't write a good memory optimized code, then your performance gets degraded. See, I told you that Java has a garbage collection called GCG. And what does it do? It works to clear such unused objects that are stored in the heap memory. Such objects that you have allocated but you don't need them anymore. Need means that there is no reference variable that points them. So according to Java, these are free objects. They can be cleared to make space in the memory. If you were of C, C + +, you would have done it yourself. But Java says that I have a garbage collection, so I will do it. Okay. Imagine that the garbage collection runs in the heap memory to clear the objects. How frequently will it run? Let's say it runs once every 2 seconds. It depends on the heap memory but hypothetically it runs once every 2 seconds. So whenever it runs, it will slow down your normal program flow. Obviously, Java's garbage collection is also a program, right? It also needs resources to run. So your normal flow of the program will be slow. So imagine, the more garbage collection runs in your program, the slower your program will be. And when does garbage collection run again and again? When you make a lot of useless objects. Because you have to clear Java again and again. And if you don't write a good optimized code, then you can get out of memory error. This error comes in your heap. Apart from this, there is one more stack overflow error. This error comes in your stack memory. If your stack gets full, then you will get stack overflow error. If your heap memory gets full, then you will get out of memory error. These errors can also come. We will see when it can come. But what I mean to say is that you have to write memory optimized code so that your memory leakage does not happen, performance does not degrade and you do not get all these errors. So basically JVM just tells you that I will help you to manage your memory But your job is to write memory friendly code If you don't write memory friendly code then JVM won't be able to help you Now let's see that the memory in JVM How is it divided? In which parts is it divided? How many parts of memory are there? First and foremost, why is memory divided in parts? If we think from the first thought principle, then why can't we call a huge chunk as memory? And store everything in it? Variables, objects, class definitions, everything. If we store everything in it, then what is the problem? Why do we have to divide different parts of memory? Now think in common sense. JVM is managing millions of objects at a time in thousands or even in big applications. It is managing multiple threads. If we talk about multi-threading code, then it is managing multiple threads. There are some such variables or objects which are long-lived. Long-lived. Right? Basically, they are going to stay in memory for a long time. Some are very temporary. So, basically, we have different types of data to store. They have different requirements. If we put everything in one memory, it will cause a lot of chaos. To clear our temporary variables, garbage collection will have to be run again and again But for long lived variables, slow run will have to be done But if we run them again and again, then our program will be slow overall Why would we want our garbage collection to run again and again for long lived variables? So what we did was split memories into chunks We said a very big memory should be for different parts and different responsibilities And we can decide what will be stored in it So that everything runs optimally Now if we see the overall picture of memory How is memory divided in java So there are 4 types of memory in java One is our heap memory We have heard about this many times One is our method area We will discuss about this One is our stack memory We have heard about this many times. Stack memory. And one is our program counter. So let's call it program register, it is basically memory. PC. Okay. So we have four types of memory in Java. Heap, method area, stack memory and program counter. Apart from this, there is another one, native method stack. Native method stack but we don't use it that much. It is generally used when our Java code interacts with another language like C, C + +, interacts with its code etc. So you can ignore it now. Mainly we talk about the four types of memory in our program. Heap, method area, stack memory and program counter. Now the interesting thing is that in our program, the heap and method area, these two memories are thread share. It means that the memory of the heap and the memory of the method area share threads. So if you make multiple threads, T1, T2, T3, all of them will share this memory. All of them will have the same resource. And the stack and program counter that we have, This is thread-specific. Every thread has its own memory. Right? So, as we know, local variables or instance variables are stored in the stack. We have talked about this many times. So, you can imagine that we don't have to lock them. When we talk about multi-threading, So there will be no race conditions because every thread has its own stack and its own program counter. But every thread has the same method area and same heap. So we have to make them thread safe. Our objects in general which are stored in the heaps, they share all the threads. So if our object is a critical resource, then we will have to lock it, we will have to put a locking mechanism, we will see all this in multi-threading. But now you must have got an idea of how our memory is rewired, which thread is shared and which thread is specific. Now let's see these memories one by one, it is very interesting. First of all, we have seen our heap memory many times. What is a heap memory? It's a huge chunk of memory in which all our objects are stored. So whenever you create an object using a new keyword, where will that object go? Into the heap memory. So let's say we created an object here, let's say we created another object here, another object here, etc. So this is a huge chunk of memory, a very big memory from all the other memories. And here we store all the objects. And we know, interestingly, that our garbage collection, garbage collection, It works on this memory itself. So our garbage collection GC optimizes this heap memory and frees it. It never works on the stack, method area or on our program counter. It works in our heap memory. We will see the architecture of this in depth. But first let's take an overview of the whole memory. Second is our method area. We haven't talked much about this yet. So what is method area? Now look, Method area is a very special memory because it stores metadata or you can say any class level blueprint or its metadata. What does it mean? Imagine you made a class, let's say you made a class student. So this method area will store the name of this class. Right. Like its class name is student. Okay. Who does it inherit? So, it doesn't inherit anyone. So, by default, it inherits our object class. Okay. Which interfaces does it implement? So, right now, it doesn't implement any interface. But, let's say, if it does, then we will get details about it. Which methods are there in this? So, if it has methods m1, M1, M2, what are the parameters of those methods? What are the variables declared in those methods? Apart from this, the definition of all these methods, Basically, if we talk about definition, then what is their return type? Okay? On which data type do they work? Their complete bytecode, now obviously, as it is, bytecode is not written here. Bytecode and a little JIT compiler, which compiles your language and converts it into a machine code, so a little bit of that also happens here. Okay? So, whatever our code is, and we know that all our code in Java is in classes. So, let's say class A, all its code. The entire metadata or blueprint of that class is stored in our method area. Now, why do we need this? Why do we need to store all this information? Obviously, you think, you have written a code. When your code runs, you know that the entry point of your code is the main method. Your code starts calling from the main. Now, the main will make different objects. Let's say, it made an object of a student, S1. So, we have to create a new object of student type. But how will Java see this object of student type? Basically, the class student that you have created, the blueprint of the class that you have created, that what is the name of the class, who it inherits, who it implements, All the methods and definitions are stored in your memory. But when it comes to RAM, which part of the memory will be stored? That memory is called method area. And when JVM interacts with a class, it first loads that class in the method area. Basically, the definition of that class and all the metadata of that class goes to the method area. Apart from this, when we studied static variables, we discussed that all the static variables that we have, and what are static variables? The ones that you write in an object, but they are not part of the object. They are class specific. So all the static variables go to the method area. Why to the method area? Because they can't go to the heap. Instance variables go to the heap, which are part of the object. And they are the same for all the objects. They are part of the class. So where the class will be stored, our static variables will also be stored. So static variables also go to our method area. Apart from this, the methods that we talked about here, basically our student method, m1 method, m2 method, all this will also go to our method area memory. Apart from this, no matter what method it is, whether it is an instance method, basically you call it through an object, or our static method that is class specific both methods are stored in the method area method is never stored in any object we saw this in the object class that only instance variables are stored in the object so let's say if you have made an age and a roll number as two instance variables in the student then they will be stored in the object age and roll number in the heap memory but if you have made any methods in this let's say m1 and m2 these will not be stored in the heap memory these will be stored in the method area So we store all the useful information about any class in the method area. Apart from this, we have our stack memory. Now look, stack memory is just like our stack data structure, last in first out. Ifo follows. So you can imagine it as if this is our stack memory. And what do we store in it? We store whatever our current method is running in it. That's why we call it by another name and say execution memory. Execution memory. So whatever current method is being executed. We make a stack frame of it. So let's say we have some code written. And first of all main method is being executed. So I will say this is a stack frame of main method. So I can call it main frame. And in this main method, let's say I write my main method here. This is my void main method. Imagine my code will be like this. And let's say I declare some local variables in it. I declare int a equal to 5, int let's say b equal to 7, something like this. And all these local variables will also go inside my stack memory, let's say b equal to 7, something like this. Right? We know and we will see this in depth also that what we store in our stack memory We store whatever current method is being executed So let's say main is being executed so we put main Now let's say main called another method let's say main called method m1 So as soon as main calls m1, we will push m1 in the stack. So we will understand that this is our current method which is being executed. Now let's say m1 calls m2. So we will push m2 in the stack. And we will understand that our current method is being executed. When m2 completes its work, then where will it go back to m1? So we will pop m2 and we will come back to our m1. So you can see last in first out. So the one we will put in last will come out first. This is our stack data structure which is implemented in the same way. And this is our stack memory which uses the stack data structure and works as an execution memory. Now we are going to see in depth how our stack memory works. But now we are just taking an overview of all types of memory. Now if we see all the memory, then the program counter is very simple. We generally call it PCB. And what does it do? It stores the current instruction that is being executed. Current instruction. Right? What does it mean? Now imagine that you have a Java code written here. Now you know how your flow of control is in Java code. Right? First your instruction 1 is executed, then instruction 2, instruction 3 and so on. Now unless and until you have not written an if statement or a loop, your instructions keep flowing in this way. Now think, the current instruction on which you are, the one that is being executed, someone has to store that information too, right? That information is stored by our program counter. The current instruction that is being executed, now you know the code of Java, JVM interprets and compiles it using just-in-time compiler. So when it is interpreting into machine code and our code is running instruction by instruction, So, the current instruction that is being executed, we call that, the program counter will store its address. Right? So that whenever it stops executing and comes back, then the program counter will know from where to start again. Now, how it will stop executing, we will see in multi-threading as well. And we will discuss a little bit in this as well. But I hope you have got an overview of all types of memory, that which work it does. Okay? So, basically, if I give you an overview, then heap stores our objects. Stacks store our execution logic, the current method that is being executed. Method area stores all our classes and methods metadata. So all the blueprint of our class goes into a method area. And fourth is the program counter which we call PC. This stores the current instruction address that is being executed. So if we see from an example and bring all the things together. So let's say I have written a code. So imagine I have a class public class let's say demo and this will have my main method. So I am not writing the whole thing like public static void main is written here, string arguments are written here. Something like this and here I declare some variables. Let's say I declare a variable int x equal to 5. And let's say I represent my user defined data type let's say student s1. equal to new student something like this and let's say I change something in this s1 so let's say s1. name is equal to aditya so I change something in this now we have to work on this program that which thing which variable will be stored in which memory ok so let's see it once Now as soon as you write your code, you will compile your code Now to compile, you write the command javac demo.java As soon as you write, you know that the demo.java file will be converted to demo.class in a bytecode file And your code will be compiled Now we have compiled the code, to run it we write javademo As soon as we write this, our code will start running As soon as our code starts running, what happens first? We don't have any classes data in our RAM We have stored our code in a file which is demo.java And its bytecode is stored in demo.class Something like this Now let's see what will happen internally. The first step will be that our JVM will start. So as soon as you run, our JVM will start. This should be the first step, right? Because Java is a virtual machine in which our code runs. Our code doesn't run directly on the operating system. It runs in a virtual machine, JVM. So first of all, JVM starts. And after that, we do class loading. Okay. So, let's assume that Java uses a class loader from inside. This is a completely different concept. What does it do through a class loader? It finds multiple classes and loads them in its memory. So, we won't go into this much. Let's assume that there is a class loader from inside. First of all, it will search the demo.class file. Demo.class is demo.java. Its bytecode is demo.class. It will search the demo.class file. After that, it will read the bytecode of the demo.class file. And it will load it in the method area of our memory. I told you that we load any class in the method area. So first of all, we read the demo.class file and then load it in the method area. So I can write, let's say, create method area entry. So I made an entry in the method area. So let's say I make an entry here. This is my method area. Let's say this space. Okay. Now what will I do in this? I will write useful information about my class in this. So let's say what is the name of our class? It is demo. Who does it inherit? It inherits object class. What are the methods in it? There is only one method in it. Public static void main. Okay. So I will write all this information in my method area. So let's say first of all I will write class is demo. And let's say I write, who is its parent? Its parent is object class. Now obviously this information will be represented in a more complicated way if you look at it from the inside. But if I say a big conceptual, then its class information, parent information, let's say method information, So I will say that it has a main method Which takes which argument? It takes the argument of string type And obviously the bytecode information of the main method etc. So our method area will store the information of all these metadata And how did the method area get created? See, what happened first? Our JVM got started After that, our class loading happens So our class loader will search demo.class from inside You know that there should be only one public class per file And there is a main method in the same file Right? From where our execution starts So basically it will search the demo.class, read its bytecode and load it in our method area. We have loaded our class here. Now when all this work is done, what will be the third step? Our main method should start executing. So to do that, what will Java do first? I told you that Java code can run in multiple threaded environment. So it can be multiple threads. By default, there will always be one thread. If we write multi-threaded code, then we can make three threads. But if the single-threaded code we were writing till now, there was one thread in it. And we call that thread the main thread in Java. The single thread that Java gives us in the beginning. So Java will create the main thread. Now, as soon as a thread is created, its specific memory should also be created, right? Now, there are two types of memory in the main thread. Our stack space, so the stack of the main thread will be created and its program counter. And the program counter of the main stack will be created. Okay? So, remember what happened till now. Class was loaded in our metadata. After that, the main method had to run. So, what happened before that? Our main thread was created and its both... Our main thread was created And the memory of both of them Which was specific to it Which was our stack space and program counter That was initialized Okay Now when all this is done Then our main method will start executing Okay So first of all what I do I initialize our thread space Basically stack space This was my method area Let's say my stack is made here This is the stack of the main thread. And apart from this, a program counter has been made, PC, which will store the current instruction. So these three types of memory have been made. Apart from this, there will be a heap memory, which must have existed before. So I made four types of memory here. Heap, stack, program counter, and method area. Now, when all these steps have been done, JVM has started, class has loaded, main thread has been made, right? After that, we will start our main function execution. main function. The whole definition of the main function is there in the method area. Now, it is very simple to start its execution. First of all, we know that our stack is our executing memory. So, the current method that is being executed, its frame, which we call stack frame, We insert it in our stack. Right. So as soon as we start executing the main method instruction by instruction. So first of all we will come here. What we will do? We will make the extract trace of the main method. So let's say main frame. So basically I have made a stack frame of the main method. Now what will this stack frame store? All the local variables in our main. So there is one x and one s1. Now s1 is a reference variable but it is also stored in the stack. So we write one is our x. x, its value is undefined till now. One is s1, its value is undefined till now. Right, why undefined? Because we haven't signed its value yet. We haven't reached that line yet, that we can execute it. Right? There is nothing other than x and s1. We are changing this in s1 only. So, that's enough. These variables are initialized here. Okay? So, we have made our method area and our stack space too. Now, the first line we will run is int x equal to 5. Right? Make a variable named x, in which value is 5. So, this is the variable named x. This is the xName variable, I'll add a value of 5 to it, I've stored it. As soon as I've stored it, see my current program counter was on this line, so let's say I call this line 101, if you imagine it like this, then my program counter will store 101, this is conceptual internally, internally it will store its address and it will be done in a different way. But for now, imagine that it has only stored its line number. After that, what will I do? I'll go to my next line, then I'll come here, I'll write it in pencil, then I'll come here, okay? And look, what am I doing in this line? In this line, I'm creating an object using new keyword, new student. So, look, my student type object should be created. Now, what is this student? It's a class itself. So, first, we'll have to load the student class in our method area. Now, we don't go into that, how student class looks like, how we'll load it in method area. We'll see that big example later. But now, assume, like we've loaded this demo class, we'll load the student class in method area first. And after that, a new student name... After that, we will make an object of student type in our heap memory. So this is our student object. How did we make it? Using this new keyword. And as soon as this student object is made, its constructor will run. All its internal variables will be initialized. But the most important part, we make a new student and assign it in S1. And S1 is in our stack space. This means that we will change this as well. Now the question will be there. And S1 will point this object of heap memory. Something like this. Right? This is what we used to show in diagram. That there is S1 in our stack memory which points to the heap memory address. So it is something like this. Okay? So this whole line is executed. After that finally, what we do in our last line? In our last line, we write s1. name equal to aditya. Before that, our program counter must have been updated. Let's say 101 is now 102. Now in our last line, we write s1. name is aditya. Now see, s1. name, where will this name field be? Obviously, this name field will be inside this student class. It means we have a class student and it must have a name filled in it. And we said that the instance variables are stored in the object itself. So what I did is I put the name in the object, student name. Now what I am doing is when I do s1. name, it means I will go to my stack memory, s1. Who is this pointing at? This is pointing at this object. Now as soon as I write a dot, you know what it means. I go and look inside that object and see what's inside it. The name inside it, basically this name, what I have stored in it? Aditya. So basically this name will store our Aditya. Aditya. Right? So, something like this would work. Now, interestingly, if you have seen my string video, then you would know that Aditya itself is a non-primitive data type. So, it won't be stored like this. Right? What will that be? Now, Aditya, see here, because we have defined a string literally, then it will be stored in our string pool, which is a part of heap memory. So, let's say, a small part of heap memory, in that, our Aditya will be stored. Something like this. And here, we will just point it. We will just say, that the name here, We will just say that the name will point to this. Right? Something like this. If you have seen the video of string, then you will remember. Otherwise, for now, you can assume that Aditya is a non-primitive data type. So, he will not be stored in this object. A separate object will be created. Now, string literally... Now, string pool is nothing. It is a special part of heap memory where strings are stored. So we can get it pointed there. So this will be our complete memory structure after this operation. Now see, as soon as we execute on this line, we come out of this line, that means our main function is completely finished. So what we will do is, as soon as our main function is finished, we will delete our entry basically from this main key, right, from stack space. So as soon as we delete its entry, all its local variables are also deleted. So which all local variables are deleted? Our int x equal to 5 is deleted. This s1 reference variable is deleted. Yes, reference variable is deleted. But it still exists. This object of ours This still exists in heap memory. And how long will it exist? Now it depends that whenever garbage collection runs, it will look at this object, scan this object and see if someone is pointing it. The answer is no. Neither someone is pointing it with stack nor someone is pointing it with heap. So this object is completely free. Free to de-allocate. So garbage collection will de-allocate it. So basically it will free memory in heap. I hope you got a good idea. Now we will go in depth in the structure of stack and heap. You will get a better idea. So now let's see how our stack memory works in depth. First of all, our stack memory uses a stack data structure and this memory is divided into stack frames So whenever we call a method, let's say we call a method M1, then the frame of M1 is made in our stack, right? So it is pushed in the stack. So one method call means one frame. Now let's say M1 called M2, then a stack frame of M2 will be made. Then M2 called M3, then a stack frame of M3 will be made. Something like this. Now in one stack frame, all the local variables of that method will exist. All the reference variables will exist, which you will make in it. So basically whatever variables you declare in this method, all of them will exist in this stack frame. In fact, our parameters too. So if you have a method that takes some parameters, then it will work as a local variable for it. So it will exist in the stack frame of the method. So if I list down what it stores, it stores the local variables, the parameters of the method, and one more interesting thing, it stores the return address, right? So let's say first of all you pushed the main, okay? And your main method let's say called m1 from inside, so then you pushed m1, right? So m1 will have its own body. Now when your m1 finishes, So after M1 is finished, we will pop it from here. Let's say we have popped it from here. Now only the main is left in the stack. So we will store its return address in it. So let's see the return address of the M1 that we have written here. So which line does it have to return on? Now some people may think that the stack is leafy, last in first out. So when we remove this memory from the stack, So below that will be the same method that called it. So let's say main called m1. So above main came m1. So when we removed m1, below is main only. Right? So what is the need of return address? We already know that we have to go back to main from m1. We had seen this too. Let's say main is there. I call a method from main, m1. I call a method from m1, m2. Something like this. So when my m2 is finished, it comes back to m1 only. Right? Because after m2, m1 is only there in the stack. Why are we not able to take advantage of last in first out? This is a very simple reason. Think about it this way. You will definitely get this information from the stack that if I pop M1, then what method do I have to go after that? But will you get this information that what line number do I have to go after that? You won't get it. Right. Imagine that this is your main code. Okay. And in this main code, let's say you call M1 on line number 1 for some reason. Then let's say you print something on line number 2. So system.out.println. So let's say you have printed hello here, then you call m1 again on line number 3, something like this. Now m1 itself is a function in which you do some work, right? When you have started executing the main, then it will be present in your call stack, right? It will become a stack frame. After that, main called m1. So, m1 became a stack frame. Now, when m1' s work is finished, then this time m1 should know that it has to go back to the next line number after this line number. Not to this line number, right? Because it had started executing from here till now. It didn't execute from this line. So, we need return address bus so that we can go to the exact line number that we have to start our execution from the previous line number of the previous method. Right? And remember, who used to store line number? PC, program counter. So when this M1 goes back to its previous method, we will update the program counter as well. Right, you assume that as soon as M1 gets called for the first time. I'll write it with a pen. As soon as M1 gets called for the first time. Okay. So the stack frame will be like this. First it will have main and then M1 will be pushed. M1. Okay. So when our program counter executes this line, then it will go to execute our m1. But here, the next time I have to start the execution again, I have to store its address somewhere, right? So that when the program counter starts executing it again, then it knows where to start again, right? So we store this information in the stack. So let's say I stored memory address 2 in M1. So the next time when you pop from here, Next time when you pop from here Start executing from line number 2 So now what will happen When I pop this Let's say I pop this So now as soon as I pop this I knew what my return address was I went straight to that return address So I went straight to my line number 2 And I have updated to in my program counter. Right. That now start executing again with second instruction. Okay. So our return address helps the program counter too. That when we have to go back, from which line number we have to start our execution. Okay. I hope you have understood why we need return address. So this is all the information that the stack holds with it. Local variable, method parameters, reference variable and return address. Now let's take an example of this, so that more things will be clear. So here I have written a basic demo code. So public class demo, here I have written public static void main. In which I have declared a variable equal to 10. And declared a variable result for which I have called a method add. Which basically takes 10 and 20 and adds them both. How does it work? It is very simple. It puts the value of x plus y in the sum which it takes in its parameters and returns the sum. And where will this sum be assigned? In our result. So basically in the result, our 30 will be 20 plus 10 and 30 will be stored in the result. It is a very simple code. Now let's simulate what will happen when I run my code with only our stack memory. We are ignoring the rest of the memory. We all want to imagine what will happen in the stack memory. So, first of all, JVM will start. As you know, JVM will start, so our demo class will be loaded in the method area. We don't go into that. What we do is, as soon as our main method starts executing, our main stack frame will be created. So, let's say I write the main frame here. Now what will be the information in this main frame? All the local variables have a local variable a, one is result, right? So it will come one information which is empty and one is the result information which is empty. Something like this, okay? So this was our, as soon as our main was executed, it started. Now see, the first line we will start executing is int a equal to 10. So what we will do is, in our local variable a, we will store 10. So here I have Wait a second, I have stored my 10 in this way Then we will go to our second line, we will come here We will store it in the result and to store it we will call a new method addA, 20 Okay So what will happen now? So let me bring it down a little first Now as soon as addA, 20 means this method will be called Our new stack frame will be created So our new stack frame will be created In which we will insert Add's frame Add Right Now see Add takes two parameters, x and y. And as I said, StackFrame stores the parameters of our method as well. So these two parameters will store x and y as well. Now in x, what did it get? It got a, which is 10. So here it will store the value of x as 10. And it will store the value of y as 20. So y equals 20. We write it correctly here, y is equal to 20. Now look carefully, from here we understand that how here a is equal to 10 and here x is equal to 10. Because here we copy the value because in java everything is called by value. We are just copying the value there. And apart from this, we also have a local variable called sum. So we store our sum here too, which is empty right now. Now we will start executing it First of all we will come to this line sum equal to x plus y So 10 plus 20 will be stored in the sum So we will directly store 30 in the sum After that we will come to the next line and say return sum Apart from this in this stack frame Return address will also be stored And where will it be? It will be the address after this line Now after this line obviously nothing is there So our main will end But just so you know We will also be storing return address Now as soon as sum equals to 30, our return is done, our add method is basically finished. So what we can do is, we can pop this stack by returning the value 30. So what we did is, we can assume that all this information is popped. I am not removing it, I am just showing you that it is popped. So now again, the main is left in our stack. And the pop that happened, what did it return? Sum. And where did it return? In this result. So we can update our value 30 in this result. So currently our stack looks like this, in which there is only one value of main, 10 and the value of result is 30. Now as soon as this line is also finished, our program counter will come back in the next line, our main method is also finished. So we will also make the main pop from our stack memory, so our main is also gone. And our stack is empty. Now from here, you must have drawn some observations. If I keep writing it along with it, that which observations we have drawn about stack. Now see your stack is growing and shrinking automatically depending upon which method calls or how many method calls are removed. So I can write let's say grows and shrink automatically and see Here, we don't need any garbage collection. These local variables are automatically cleared as soon as our current frame gets empty. So as soon as the add method ends, we remove its stack frame. As soon as our main method ends, we remove its stack frame as well. So here, we don't need any garbage collection. It automatically cleans itself. Right? So memory is auto-cleaned. Okay. And obviously, if you look at its execution order, then it is last in first out, which is basically the execution order of our stack. Now look, if you must be wondering, why do we store this in stack, why don't we store it in heap? If we know that we have to manage heap, then we can store local variables and method reference in heap. The reason for this is that our stack memory is very fast. And our method calls are very frequent. Like main called m1 directly, m1 called m2 directly etc. So we call a lot of methods and we want our code to be optimized. So we want the method call to be very fast. Now in the stack, the push and pop operations are very optimized. Both are done in constant time. We know that. If you have read about data structure, you know that push and pop are done in constant time. So the stack data structure is very optimized. To store such information, we call it execution stack. And you think, These local variables, if we put them in heap, then garbage collection will have to be cleaned, they will not be cleaned on their own. But in stack, as soon as we remove a stack frame, all our local variables are deleted. And after that, local variables have no use. Once the method is cleared, then local variables have no use. So because they are short lived, they are good in stack. In general, our stack memory is faster than our heap memory. Now if we talk about stack and not about stack overflow error then how can this happen? So stack overflow error In our video on exception handling, we have two things, errors and exceptions. Now this stack overflow error is an error. It's a throwable type, but it's an error. Now when will it come? Obviously, you'll know by the name when your stack memory will be full. Now we've already said that our stack grows and shrinks automatically. But our stack memory is not that flexible. So basically this stack memory is not very flexible, it's not like you can call as many methods as you want in it. It has a limited space, it can expand the string as much as it can, not much. Once that limited space is filled, you will get a stack overflow error. And the most common example of this is that you forget the base case in your recursion. Recursion without base case. Suppose you have a function f1, which calls this f1 again. And there is no base case here, this is just a small function. So what will it do? You can imagine, in our stack memory, first the f1 stack frame will be formed, then again f1, then again f1, and so on. By doing this, our entire stack will be full. And we can never get out of our infinite loop. So in that case, we get stack overflow error. We should avoid it, we should not write any such code, in which there is no base case of recursion. I hope you understood how the whole stack data structure works and how it optimizes the memory Now let's move to our next memory which is the heap memory So we are going to talk about our heap memory Now think about the thought process behind making a heap memory Java thought that I have some data which we call objects This is the kind of data that can't be predicted for a lifetime. It's unpredictable. Right? It's possible that some objects end up in milliseconds. Right? It's possible that some objects last for a few minutes. And there will be some objects that will remain in memory until the end of the program. So it's not like a simple local variable that as soon as our method ends, we remove the calls from the checkbox. Right? This shows some unpredictable behavior. So to store these types of objects or these types of variables, we need a special memory, which we called heap memory. Some such heap memory. Now what will happen here? Here our objects will not be clear Basically, we have placed a special manager here, let's say garbage collector. His job is to update here and there which are the objects that are ready to be free and then free them. Right? So basically, what did we say? We will make all the objects or any things that are dynamically allocated as part of our heap memory. Okay. So what all do we make in heap memory? What all do we allocate? Let's see. So let's say what goes in heap. So obviously, first of all, all the objects that we create, let's say if we make an object student s1 equal to new student. So because a new keyword is applied here, it will go straight into our heap memory. Apart from this, you can assume that our instance variables Instance variable. Where will that go? In our heap memory. So you know the instance variable. So let's say this was our student class. Here was our class student. And we had defined some variables in it. Let's say one was your string name. Okay. And let's say your age is 1, so int age. We had declared some of these variables. So when we store them, then again we will create a heap memory. We will create an object of our student class in that. And in that student class object, we will store the name as well as the age. Something like this. Right? So these instance variables are also part of our heap memory because they are stored inside the object. Okay. Okay. Apart from this, our arrays. Our arrays are also stored in the heap memory Because these are also non primitive data types So if I take an example of arrays So let's say I have made an array in this heap memory Something like this will also go in our heap memory And let's say if the name of this array is arr So this arr will go in our stack memory Which will point it We had seen this too Now, obviously, if arrays go, then our strings will also go into heap memory. Now, strings go into heap memory in two ways. Once it goes into normal heap, if it is declared with new keyword. But if that string is declared with literal, then it goes into a special part of heap memory, string pool. So, if you haven't seen the video on string, then you can watch it once. It will be clearer for you. But all this information is stored in our heap memory. Now, look. If we don't tell some useful information about our heap What is the benefit of our heap memory So if we talk about some properties of our heap memory So one thing we know very well That our heap memory is shared Shared across thread Right This means If we have to protect our heap memory If we have to protect an object Which is inside the heap memory And it is a critical resource So we have to put a locking mechanism on it Right Because we can't execute multiple threads Second, which is again interesting, our heap memory is very dynamic in nature. What does it mean? So, as I said, your stack grows or shrinks, but it cannot grow more, it is not flexible. Our heap memory can grow more, depending upon how many objects we are creating, it can increase its size more. So, it is dynamic in nature. In fact, as a developer, when we write code, we can tell our Java program how much maximum heap size and minimum heap size you have to take. This is very interesting. It has some keywords, if I tell you. When you are running your Java program, while running, If you pass- x ms, and then write how much space you need. Let's say 2 m, means 2 mb. Okay? So this will tell you minimum space required. Minimum space. Basically you are saying that I have heap memory. At least 2 mb storage will take. And if you pass, And if you pass Minus x mx means maximum space Let's say you write here 4 m So basically 4 mb So this will tell you maximum space Which your heap memory can take Okay So basically you start with 2 memory And maximum you have to expand to 4 memory Don't grow beyond that If you create more objects in it Which will expand 4 mb too Then you will get out of memory error Out of memory error Right You can do this in your code by yourself If I quickly show you a version of this So I have taken my demo.java as empty file Let's say I make a list here So I import the list And I make a very interesting list Let's say list of integer array Int array So let's say list equal to new array list And look, my motive is to be able to tell my program how much memory it needs to take. And I try to fill that memory here. So let's do one thing. Let's write a code, let's say while true. Until my memory gets full, I want an out of memory error. In this list, I will keep adding new int 250,000. I am inserting an array of 250,000 in my list. Why 250,000? Because I know in Java, the integer int takes 4 bytes. So the integer takes 4 bytes. And if I can store 250,000 integers here, then 250,000 x 4 is 1 million. That means I am storing information of 1 million bytes. Now if I convert 1 million bytes into megabytes, then it will be 1 megabyte. If I want to convert it into megabytes, then I will first divide it by thousands and convert it into kilobytes. Then I will divide it by thousands and convert it into megabytes. So basically I have stored 1MB of data in one element of the list. Now I am telling you to keep storing 1MB of data until our heap memory is full. So when I declare my heap memory, I will make it of 4MB only. And let's see how many times it happens. So I take the count variable, count + + and declare the uppers. Let's say int count equal to 0. So let's see how many times it happened. Let's print this count. Let's say allocated block. is count. Okay? is count. Okay. Something like this. So you must be understanding what we did. We made a list. And what we did in that list is we pushed an int array. And we push an array of 250,000 size at a time. Or I can say that I push 1 MB of data at a time on one element of the list. Right? So we'll store 2 MB of the list, 3 MB, 4 MB, 4 MB. Something like this. This time I won't run from here. This time I need a terminal because you can understand that I have to adjust the heap memory. So first of all I'll compile it, so I'll write javaseqdemo.java Like this, as soon as I compile it, my bytecode will be made, see demo.class Now I have to run this, so I'll write javademo, now before writing demo I'll tell you what my heap size should be So I'll write here, minus xms, 2m means take minimum 2mb, after that again minus xmx 4m and maximum is 4mb so if I assume 4mb is maximum then only 4 elements should be full and count should go to maximum 4 and then file name should be demo and let's run it so as soon as I run it I got allocated block 1,2,3,4 and after 5 it finished and I got out of memory error but why 5 we predicted that 4 blocks should be made and count variable should be increased to 4 see it was simple I took here 2 fifths I had taken 250,000 here. If I make an array of 250,000 on every element, and my int takes 4 bytes, then basically I have to store 1 MB in every element. And I have made my stack space of maximum 4 MB. So it should not take 5, it should take 4. So its simple answer is that when I am converting 1 million bytes into megabytes, then I am dividing it by 1000. But actually, I will divide it by 1024. So that the calculation is simple, we will divide it by 1000. But to convert it to megabytes, we will divide 1 million by 1024. Right? So this will be less than 1 MB overall. So you can assume that every space is a little less than 1 MB. Overall, we will enter the 5th block. And as soon as our count is plus plus, we will break beyond the 6th block. Okay? Okay. So we understood how out-of-memory error can come in our program. And how we can adjust our heap and tune it. So you do it by yourself, tune it in your own program. And try to bring out-of-memory error, in fact stack overflow error. You can use recursion for that. Apart from this, what other properties can we have? We know that this is managed by garbage collection. So managed by GC, I can write managed by garbage collection. And It is usually slower than stack. Why is it slow? Because it has allocation and deallocation complex. And it also has an overhead of garbage collection. So, it becomes slow because of this. And in stack, only push and pop operations are there which are done in constant time. So, it is a little faster than this. Now, if we understand step by step what object creation actually is. So, let's say I write my class student. So imagine that I have written my class as student and in my main method I will make an object of this student so I will write something like student let's say s1 equal to new student and when I will do new student then I will pass a name and an age in my constructor so let's say I can pass it here I have passed name as aditya and age as 28 and here I have made an object Now if we go to behind the scenes, then what will happen in the memory and here specifically we will only talk about heap memory, we will avoid the rest of the memory. So look, first of all, obviously JVM will start. And what will happen if JVM starts? First of all, our main method will load in our metadata, we will not talk about that. After that, its execution stack will also be made in our stack, we are not talking about that right now. We will talk directly about this line as soon as this line will run, student s1 equal to new student. So first of all, in our heap memory, here is our heap memory, an object of student will be made in it. Let's say this is our student. And all the instance variables in this student, like our name and age, will get default values. Since the name is a string, it will get a default value of null. And since the age is an integer, it will get a default value of zero. You know, when we write a new keyword, our object gets created, right? And when we write a student, what do we do from inside? We call our constructor. Now, when we call constructor, then what will happen? We have given the constructor two parameters, Aditya and 28. We will say that put these values in our instance variable name and age. So, basically, what I mean to say is that I will put Aditya in my name field. I will write this with a pen, Aditya. And I'll put 28 in the field of age. Something like this. And my object will be made completely. Now the reference variable of this object, s1, will be stored in my stack memory. So if I make it, let's say my stack memory will be somewhere here, s1. My reference variable will be stored in that. Okay. So this will be something like my behind the scenes. Now we know, if I write in my code again, let's say one more student variable, let's say s2 equal to s1, then it doesn't mean that another student's object will be created, right? No, it means... Right? This means that my stack had S1 which was pointing it. Now another reference variable has become S2 which is also pointing it. My object is the same. Until I don't write a new keyword, my new object won't be created. Now look, we talk about this that if our object becomes unreachable, then our garbage collection will remove it. But how is our object ever unreachable? Let's see that. So now imagine that you have your heap memory and this time I will make stack memory as well. So this is your stack memory. And in your heap memory there is an object named student and its reference name s1 is available in your stack memory. So this is our scenario. Now let's say when we would have made its object then something like this would have been written student s1 equal to Neo student. Let's say we have written such a code in our main method. Now if I store s1 equal to null, then what will happen? Nothing will happen. Simply, this reference variable will stop pointing it. And it will not point this object. And s1 will point null. Now see, as soon as you did this, you told your JVM that I have marked this object or made it eligible for garbage collection. I have made it eligible It doesn't mean that it will be deleted immediately When garbage collection will be run And garbage collection will feel that it should free this memory Then it will free this memory or else it won't So you have made it eligible That it can be run from garbage collection So this is one situation. Now consider the other situation. All this must be in a method. Right? And as soon as that method is finished, you know that the entry of our stack space must be finished, then also indirectly we will remove the reference from it. In that case also, you mark it or make it eligible for garbage collection. It is not necessary that it will be immediately removed from the garbage collection. Okay? Now see, a very interesting information. Heap will look like our graph data structure. Because you imagine, we have a class A It has a reference variable store of class B. It has an object store. Similarly, you have a reference variable store of class B. Let's say it has a reference variable store of class C. So, we basically link objects to each other. So, suppose something like this happens. Let's say there is a class. A class is this. A class is this. This class has this address. Now, this class has an instance variable. This class has a reference. Something like this. So, it will look like a graph to you. So, it is not always necessary that there is a reference of an object near a stack. Another heap object can also have an address of another heap object. And it will look like a whole graph data structure. I hope you have understood how the whole architecture of a heap looks. Let's keep this video as it is. In the next video, we will go into the depth of heap data structure. And we will see how the different parts of a heap are. And after this we will also go into the depth of garbage collection We will see which are the garbage collection algorithms Which are optimized, which are unoptimized, etc. So I hope you enjoyed it, you must have learned If you enjoyed it, then please do a good comment, hype the video And subscribe to my own channel Aditya Tandon too Let's meet in the next video, till then thank you so much