Saturday, 28 May 2016

3 ways to create String instance

It may be tricky if not knowing the concept clearly.

There are three ways to create String instances in java. They may be instantiated in different part of memory allocation, i.e. heap memory or string constant pool; in the constant pool, an string instance may be reused for memory efficiency. 

1) String str = new String("hello world");  //1
2) String str = "hello world"; //2
3) System.out.println("hello world");  //3


//1: "new" will instantiate a new string object in heap memory, no matter what.
//2: JVM will check if the string constant already created in the constant pool first; if not, then create a new one; otherwise, the existing will be reused, so the reference of the same string maybe copied to different String variables.
//3: "xxxxx" may also instantiate a new string object in the string constant pool, if the same text constant is not existed yet. 

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...