This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I know that the statement : String str=new String("abc"); will create a new String object and store it on heap but then for the initialization String str="abc"; does java creates new object? & how n=much objects will be created by following code,
Creates a new reference variable to a String object holding the data "ABC" which resides in the String constant pool. If there is no such String object in the pool a new one is created.
Creates a new reference to a new String object holding the data "ABC" which resides on the heap. No checking is done whether another String object with that value already exists elsewhere.
Will usually (not guaranteed though) print true.
Will never print true (unless there's a JVM/compiler which doesn't work correctly and replaces the dynamic string creation calls with calls to Strings in the String constant pool).
Number of objects created in your sample would be 3. One String "abc", another "abcabc", and yet another "abcabcabc". 6 references to these 3 Strings will exist, 4 of them pointing to the same String "abc".