[HD Pg 133, Sec. 3.5.3 - garbage-collection-of-strings]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

[HD Pg 133, Sec. 3.5.3 - garbage-collection-of-strings]

Post by OCAJO1 »

String str = "hello";
for(int i=0; i<5; i++){
str = str + i;
}

In the above example, does JVM cache the object str or str+i (similar to valueOf would) or actually creates 11 new string objects on the heap?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 133, Sec. 3.5.3 - garbage-collection-of-strings]

Post by admin »

First thing that you should remember is that all objects, whether cached or not, are always created on the heap.

As per section 15.18.1,
The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).
So, in your example, the strings containing str+i will be newly created (and not cached).
This simple example proves it:
int i = 1;
String s1 = "a"+i;
String s2 = "a"+i;
System.out.println(s1 == s2); //prints false, this implies s1 and s2 point to two different objects
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 69 guests