Hi all, I am preparing for SCJP 1.4 and found this question in EXAM CRAM2 Java 2 Programmer (page 59). How many String objects are created in the following code? 1. String A, B, C; 2. A = new String( "1234" ) ; 3. B = A; 4. C = A + B; A. One B. Two C. Three D. Four My guess is C. Three. Since line 2 A = new String( "1234" ) ; would create 2 String objects, and line 4 C = A + B; created another one. But the book's answer is B. Two Could anyone please explain it. Is there a way that we can check the answer programmatically? Thanks. cn
You can try to invoke String methods on those references, and if they are objects they should not give you NullPointerException (I think I should try it, before mentioning it duhh!!). Sorry that's all I can think of.
hi Carolyn the only thing i see is- the question asks "String Objects". the two strings that are created in A = new String("1234"); are essentially, 1. String Object reference A 2. string "literal" "1234" but out of these String Object is only one. so in place you counted 2, its only 1 "String Object" which leads to the answer B. regards maulin
"compiler automatically creates a new String object for every literal string it encounters, you can use a literal string to initialize a String. " and it goes on to describe that the following line of code String s = new String("Hola Mundo"); would create two Strings. "The compiler creates the first string when it encounters the literal string "Hola Mundo!", and the second one when it encounters new String. "
K&B's book has a similar example and they count it as three. The K in K&B is one of the exam co-authors, so if it comes up on the exam, I would go with three.
Joined: Nov 04, 2001
yeah this question has always results into long threads of discussion as there seems uncertainty in definition or interpretation and what not ... to me, i would agree w/ ppl here that this sort of question should not be there in exam but if it is just go w/ what u think. none is gonna take away life from u for ONLY ONE wrong answer out of all if u know what i mean regards maulin
totally at the end of the program we have two different strings so two objects obviously,since the strings which are same are treated as a single object(excluding some special cases),we have 2 string objects.