Page 1 of 1

About Question enthuware.ocajp.i.v7.2.999 :

Posted: Sat Mar 02, 2013 9:38 am
by The_Nick
I would like to add a clarification.

basically intern of course is useful only for String object as the String literals are automatically interned.
A part from that, the use of intern to be meaningful must be done at the same time the object it's created.
example:

Code: Select all

String str1 = "Indeed";
String str = new String("Indeed").intern();
System.out.println(str1==str);
If it had been done something like str.intern(); after the creation of str it of course would be too late as the different object would have been already created.

Let's pass this OCA exam.

Re: About Question enthuware.ocajp.i.v7.2.999 :

Posted: Sat Mar 02, 2013 10:17 am
by admin
That is incorrect. A new String object is created anyway when you do new String("Indeed"). However, when you call intern on it, the JVM finds out the interned String object containing the same value and assigns to str.
The reference to the newly created String object is lost.