Memory organization for member of class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Memory organization for member of class

In Java, does the heap memory contains variables or the data belonging to it ? With this I mean that for eg if I create String str="hello" ; So here is str (reference variable or instance variable) stored in heap or it's content hello stored in heap , and what is the method area used in Java for?

24th Apr 2020, 5:30 PM
Shubham Pandey
Shubham Pandey - avatar
7 Answers
+ 2
Strings in Java are by default of reference type. String str = "hello"; Here str is a reference variable which is stored on the stack. Whereas "hello" is stored on the heap in a separate memory location called the String constant pool (SCP). But when you create a String object- String str = new String("hello"); There are two copies of the string get created, one on the SCP and one outside it in the heap. If the "hello" is already present in the SCP then the one which is suppose to be stored in it will be discarded since SCP cannot contain duplicates. Hope I have made my point clear. Regarding 2nd part of your question. Method area generally store your class details, all the instance variables, constructors, methods and instances if declared inside the class. It might as well have relation details of class if it has extended a class or have implemented an interface.
24th Apr 2020, 5:42 PM
Avinesh
Avinesh - avatar
24th Apr 2020, 5:32 PM
Shubham Pandey
Shubham Pandey - avatar
+ 1
Shubham Pandey I had to find a link to support my answer. I would have not brought that up if I was not sure about it. You can refer the below link. https://stackoverflow.com/questions/19672427/string-s-new-stringxyz-how-many-objects-has-been-made-after-this-line-of
24th Apr 2020, 6:12 PM
Avinesh
Avinesh - avatar
26th Apr 2020, 3:11 PM
narayanaprasad
narayanaprasad - avatar
0
Are u sure that on creating String str =new String ("hello"); Will create hello outside scp in heap as well as in scp. I think it will create only one hello in the heap outside scp
24th Apr 2020, 6:00 PM
Shubham Pandey
Shubham Pandey - avatar
0
Avinesh Thank you so much u cleared my doubt as well as misunderstanding
24th Apr 2020, 6:20 PM
Shubham Pandey
Shubham Pandey - avatar
0
Shubham Pandey you're welcome. Nice to know it helped.
24th Apr 2020, 6:22 PM
Avinesh
Avinesh - avatar