What is the output of the following code? 1: String str = "Welcome"; 2: 3: str.concat(" to Java!"); 4: 5: System.out.println(str); A) Strings are immutable, compilation error at line 3. B) Strings are immutable, runtime exception at line 3. C) Prints "Welcome". D) Prints "Welcome to Java!". I had read that concat method is for strings so whats the output of the above code??
The answer given is C but i thought that one can concatenate with strings, however considering that strings are immutable than we cannot use the concat...Is this the logic? One more thing, i am not compiling each code...rather doing it more theoretically, Is it the right approach? or should i also compile and see the outputs? and then deduce etc. ooops! i just compiled and found the answer...that was quite a simple problem..and i guess one should compile!!to have a real understanding. one last thing: line 3 cannot be used alone and has to be assigned to str to make it work for the compiler! right?
Because Strings are immutable, all string methods are non-destructive Any seemingly mutable operation on String ( concat, +=, trim, toUpperCase, toLowerCase. etc ) actually returns a reference to the new string object. Obviously, they don't affect the object on which the method is called. In your example, the .concat method is returning a new string, but you are not storing it anywhere. The original String str continues to preserve its original value. Hope this clarifies, Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
hi in simpler words if u would have said str=str.concat("to java"); the u would have got D as u r answer
lets say & means address of the reference * means object to which it is pointing to
String str = "Welcome"; // str &200 "welcome" address is *300 str.concat(" to Java!"); // a new object is created but without assignment to any reference System.out.println(str); //str still contains reference to object stored at *300 hope this helps
I do some of my very best work in water. Like this tiny ad: