0
class MyClass{
   public void method(){
     String s = new String("a");
   }
}
  • s goes to JVM Stack
  • new String("a") goes to Heap
  • "a" goes to SCP. Which is in Metaspace.

Is that correct?

user567068
  • 435
  • 8
  • 15
  • Yes. The key point to remember is that non-primitive variables always store references, which are either null or point to an object. That object is either in the heap or in metaspace. In the case of a local variable, the reference itself is on the stack. So when you say "s goes to JVM stack", what you mean is that the reference that s contains is on the stack, but the object that it refers to is on the heap. – Dawood ibn Kareem Sep 13 '21 at 21:36
  • 1
    @DawoodibnKareem That part is not clear to me. "That object is either in the heap or in metaspace." Metaspace does _not_ contain objects. So there are 2 copies of "a" one as an object on the heap and another as a string literal in Metaspace, right? – user567068 Sep 13 '21 at 21:43
  • The literal "a" will be created in the Heap. Starting from Java 7, the String Pool is moved inside the heap. SCP doesn't reside in the Metaspace. – null Sep 14 '21 at 04:53
  • @null "Since the Method Area contains artifacts “such as the run-time constant pool, field and method data, and the code for methods and constructors…”, in other words non-Java-objects (the pool may contain references to heap objects though), it is part of the Metaspace now." https://stackoverflow.com/questions/50163218/is-method-area-still-present-in-java-8 – user567068 Sep 14 '21 at 19:47

0 Answers0