This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
There is an example of String, I came across this code during my interview but still I am not understand this code. And my Interviewer asked me that "how many references of String are there and if we use only two lines of this code then how many references are created?" . Please clarify it.
I believe there are four objects created. the literals "abc" and "abcdef" each cause an object to be created - even though each literal appears twice. However, since we are also using "new String", each of those calls creates ANOTHER object. So, after these four lines run, you have two strings each for "abc" and "abcdef".
Each reference - st, st1, st2, st3 - points to its own, unique String object.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Well, each of the distinct String literals causes one object to be created: "abc", "abcdef" and "abcde". Then, you also create two new Strings explicitly (st = new String(...) and st1 = new String(...)).
So you create 5 objects.
The tree String literals will each have a reference to them in the String pool, and st2 and st3 wil also reference "abc" and "abcde". Finally, the two Strings that are explicitly created will be referenced by st and st1.
Something it took me a long time to 'get was that Strings work differently than other objects. Any time you see a literal string (something enclosed in double quotes), a String is made and put into the 'String pool'. If the exact same literal is seen more than once, like your "abc", the string is created one time, and both references point to the same String object.
Now, ANY time you see the 'new' operator used, that means a new object is created. So when you do "new String("foo")", you get TWO objects created. A string is put in the String pool for the "foo" literal (unless "foo" was already used somewhere else prior to this line), and a SECOND String object is created, this time NOT in the String pool, which also has a value of "foo". You get two-for-one when you write it that way.