Java memory questions about 'new' keyword

前端 未结 3 1276
小鲜肉
小鲜肉 2021-01-05 01:43

What happens if you run the following code..

while (true) {
    String x = new String(\"ABC\");
}

in terms of memory?

Is String x a

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 02:29

    Is String x allocated on the stack or on the heap?

    x isn't a String. It is a reference to a String. The reference is a local variable, and so goes on the stack. The String is an object, and so goes on the heap.

    Will the program eventually crash because of a memory overflow

    Probably not.

    or will garbage collection prevent that?

    It should.

    Does the new keyword always create the object on the heap?

    Yes.

    When is an object created on the stack?

    Never ... unless the JVM decides it cannot escape the current scope and so decides to do so.

提交回复
热议问题