What happens if you run the following code..
while (true) {
String x = new String(\"ABC\");
}
in terms of memory?
Is String x a
In theory, new
creates on the Heap, and non-objects (i.e., int
s, char
s and so on) are created on the stack. The only exception, afaik, are strings, created on the stack as well. In practice, the JIT compiler of many modern JVMs will see that, in some cases, objects created with new
can be created on the stack (for example, local objects that are not referenced outside of the current function).
The garbage collector will take care of the deallocation for you, that's its purpose, but of course you can run out of memory if you create and keep references on too many objects at the same time (try creating a list with a billion strings, for example).