简体   繁体   中英

String and Array Objects in Java

In Java, objects are created using the new keyword and they are stored in Heap.

As we may all know, String and Array are non-primitive data types and they are treated as objects in Java.
But we can declare any String and Array object without using the new keyword.

So my question is: Where are they stored in memory?

But we can declare any string and array object without using new keyword.

Obviously ...

So where are they stored in memory?

In the heap. Those special ways of declaring strings and arrays are just syntactic sugar. The underlying objects work (pretty much 1 ) the same way as objects instantiated with new . And all objects live in the heap 2 .


1 - There is a small wrinkle for String literals. For some older JVMs, string objects corresponding to literals are held in a separate "permgen" heap. This distinction was largely removed in Java 8.

2 - In recent JVM (Java 7 onwards, I think), there is a JVM switch to enable a JIT compiler optimization which can store some objects on the stack. However, this is entirely transparent to application code, and you can't "force" it to happen in application code.

All object reside on heap, the creation of the object can be through multiple ways:

  1. new
  2. clone
  3. reflection - getinstance
  4. special - like the case you have mentioned

But regardless they will all live and die in the heap

all objects are stored in the heap, whether it was string or an array; the real deference right here isn't the storage place but it is the way that java deals with string literals and string objects, if you create object using String literal syntax eg "Hello", it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space) for example:

String str = "abc";
String str2 ="def";

here str and str2 refers to the same object, unlike using new which creates new object for each reference.

String str = new String("abc");
String str2 = new String("def");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM