Hey, Tea Lovers! Today we will talk about Java Memory Management with the example. We will look at the code and then how it is affecting the JVM. So the relationship between these 2. I will try to explain it line by line. So let us see how a code lives its life.


You can follow me on social media via @coderstea on TwitterLinkedinFacebook, or Instagram. We also share high-quality videos about programming on our Youtube channel. You can also publish your post on CodersTea, just share your thought on Contact Us or let us know in the comments.


It is part of the JVM post series “Get Ready to Deep Dive Java Memory Management”.
Before we explain examples first we will understand the java rules for java memory allocation.

Rules for Java memory

  • Objects are stored on the heap
  • Variables are a reference to the object
  • Local Variables are stored on the stack

Below the example, we initialize String & list & manipulate the values of variables, for better understanding discuss the below example line by line.

The Code

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		String name = "mahesh";
		modified(name);
		final List<String> listOfString = new ArrayList<>();
		modified(listOfString);
		System.out.println("name :: "+name);
		System.out.println("listOfString :: "+listOfString);
	}
	public static void modified(String str){
	    System.out.println("exiting name :: "+str);
	    str = "Imran";
	    System.out.println("modified name :: "+str);
	}
	public static void modified(List<String> listStr){
	    System.out.println("exiting listStr :: "+listStr);
	    listStr.add("Imran");
	    System.out.println("modified listStr :: "+listStr);
	}
}

Output

exiting name :: mahesh
modified name :: Imran
exiting listStr :: []
modified listStr :: [Imran]
name :: mahesh
listOfString :: [Imran]

What a Life the Code has

I will start from line 7 because calling the main method with a string array(args) is common in all.

For better understanding, we will use the below diagram for the java memory allocation on stack & heap.

StackDiagram

Step – 1)

  • On code line 7 we have an initialized String name variable with the “mahesh” value.
  • On the stack, it will store the variable identifier as the name & make the String object on the heap assigned value as the “mahesh” & point the stack variable to the heap.
  • It will represent in the diagram.
StackDiagram

Step – 2)

  • On code line 8, It will call the modified(String str) method & control pass to the modified(String str) method, with the String str variable with the “mahesh” value.
StackDiagram

Step – 3)

  • On code line 19, It will display the str value on the console.
  • On code line 20, str assigned string value as “Imran”.
  • There It will create a new string with the value “Imran” & then it will change an str reference to that “Imran”.
StackDiagram

Step – 4)

  • On code line 21, It will display the str value on the console & control again pass to the main method on code line 9 & same time str is gone out of scope. it will garbage collect str variable & java memory structure looks like as below.
StackHeapExample

Step – 5)

  • On code line 10, here create a list of ArrayList type with identifier listOfString.
  • listOfString is an of final.
  • On java memory, the structure looks as below.
StackDiagram

Step – 6)

  • On code line 11, It will call the modified(List<String> listStr) method & control pass to the method, Initialized listStr variable with the initial value. (null)
StackDiagram

Step – 7)

  • On code line 25, It will display the value on the console, & the next line.
  • On code line 26, It will insert/add the string value “Imran” in List<String> listStr. This will create a string with “Imran” & then an str reference point to that listStr index 0 from the list, the same shown below.
StackDiagram

Wait, It’s possible to modify the value in the final list?

  • To understand this let’s first understand the final keyword
    Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
  • This will applies to the List because the List is an object. if a final variable holds a reference to a List, then the components of the List may be changed by operations on the List, but the variable will always refer to the same List on the heap.
  • If you find in the above picture in listOfString it has a reference on list object & from inside this, it has an index which pointed to the object in the current case it String.

for more info check out : Interview Question: Final vs Finally vs Finalize

Step – 8)

  • Then On code line 27, It will display the value on the console & after control again pass to the main method on code line 13 & meanwhile remove reference to List<String> listStr which looks like as below.
StackDiagram
  • Finally, On code lines 13 & 14, It will display the value in name & listOfString on the console & program exit.

Conclusion

I hope you liked the post. I tried to simplify things. If I had missed something please feel free to suggest it to me in the comment section. If you are still confused about the JVM, I would say please see my post series on JVM “Get Ready to Deep Dive Java Memory Management”. Please see them in the following order.

I hope you liked the post. See you in the next post. HAKUNA MATATA!!!

You can follow me on social media via @coderstea on TwitterLinkedinFacebook, or Instagram. We also share high-quality videos about programming on our Youtube channel. You can also publish your post on CodersTea, just share your thought on Contact Us or let us know in the comments.

2 comments

Ashish Singh January 22, 2022 - 9:07 am

I am not sure, but don’t you think that a copy of the list will be created when it is passed into the method?
According to the 7th stach diagram, you are pointing two references to the same list. Is that correct?

Reply
mahesh-profile-picture
Mahesh More January 22, 2022 - 5:23 pm

To understand this let’s divide your question into two-part,

1. for the method call, Is the list copy is created??
2. In the 7th stack diagram, two references point to the same list. Is that correct?

Before jumping to this, we need to understand that java is only supporting the call by value,
but due to object dramatic behavior, something weird happened (call by reference).

when we call the method with primitive data type then it provides a copy of that variable but when we call the method with an object,
then the object reference is passed to a method, the method gets a copy of the object reference, and both the original and the formal copy refer to the same object,

therefore within the method, the state of an object parameter can be changed.

Now your question, when method call with a list (which type of ArrayList), we are passing the object of it so we passing reference of that object. So copy will not be created & reference pass.

& In the second question, when we pass reference so in the method space no any copy created they got reference so in local space & former space have the same reference due to this, In 7th Stack diagram, we showing as two reference to the same list & it’s correct.

If you still have any queries, let me know,

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

TWITTER FEED

INSTRAGRAM FEED

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

coderstea-logo-invert
@2022 All Right Reserved. Designed and Developed by CodersTea

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More