String is an immutable object.
Then how can the following code be justified.

String s1 = ?ABC?;
String s1 = s1+?XYZ?;
s.o.p(s1);

The output is ABCXYZ, which is the value of s1 ?

Answer Posted / amr

actually its a compiler error , variable already defined ..

but i'll answer the other part ,
String is immutable but does it make sense to write
String S1= abc;
S1=s1+"def";
YEAH its immutable and what happens behind the scene :
a new temporary String is created and using StringBuffer
which mutable class then appending then returning the
temporary string , thats the meaning of String is immutable
but StringBuffer is mutable , so if u r gonna use intensive
String manipulation u better go for StringBuffer because
String concatenation will result in more lines of code in
the byte code file generated when we compile .
this is a very frequent interview question .

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why string objects are immutable in java?

563


What is the difference between Java1.4 and Java1.5

1828


Is string pool garbage collected?

547


What best practices should you follow while writing multithreaded code in java?

541


Where we write javascript code in html page?

562






Explain yield() method in thread class ?

621


Explain about static nested classes in java?

611


why are wait(), notify() and notifyall() methods defined in the object class? : Java thread

553


What is mean by collections in java?

564


Which sorting is best in java?

535


what is meant by Garbage collection?

619


Can a string be null?

544


How do you sort a string in alphabetical order in java?

534


What does void * mean?

534


What is object english?

585