Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 15)
15.
What will be the output of the program?
String s = "ABC"; 
s.toLowerCase(); 
s += "def"; 
System.out.println(s);
ABC
abc
ABCdef
Compile Error
Answer: Option
Explanation:

String objects are immutable. The object s above is set to "ABC". Now ask yourself if this object is changed and if so where - remember strings are immutable.

Line 2 returns a string object but does not change the originag string object s, so after line 2 s is still "ABC".

So what's happening on line 3? Java will treat line 3 like the following:

s = new StringBuffer().append(s).append("def").toString();

This effectively creates a new String object and stores its reference in the variable s, the old String object containing "ABC" is no longer referenced by a live thread and becomes available for garbage collection.

Discussion:
4 comments Page 1 of 1.

Neetish said:   9 years ago
Can anyone explain this in easy words?

Please help me to understand the concept.

Pavan said:   9 years ago
String String s is immutable how can we assign to the same string by concatenating some String?

Nancy said:   1 decade ago
@Rajiv.

s is assigned a new value ABCdef so s refers to this value now and ABC is not referenced by s.

So it can be garbage collected.

Rajiv said:   1 decade ago
Can anyone suggest me here that as "ABC" is in String Pool area so how it will be available for Garbage collection as the string literals in String pool do not available for garbage collection?

Post your comments here:

Your comments will be displayed after verification.