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?
7 odpowiedzi
+ 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.
+ 1
What do this diagram represent
https://drive.google.com/file/d/11Jgtfm8_8lSQmUYz2r3PHUQZZN4HPyk1/view?usp=drivesdk
+ 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
+ 1
You may find answer in http://www.cyberplusindia.com/blog/index.php/2014/04/24/memory-organisation-of-objects-in-c/
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
0
Avinesh Thank you so much u cleared my doubt as well as misunderstanding
0
Shubham Pandey you're welcome.
Nice to know it helped.