Java Programming - Java.lang Class - Discussion

20. 

What will be the output of the program?

public class StringRef 
{
    public static void main(String [] args) 
    {
        String s1 = "abc";
        String s2 = "def";
        String s3 = s2;   /* Line 7 */
        s2 = "ghi";
        System.out.println(s1 + s2 + s3);
    }
}

[A]. abcdefghi
[B]. abcdefdef
[C]. abcghidef
[D]. abcghighi

Answer: Option C

Explanation:

After line 7 executes, both s2 and s3 refer to a String object that contains the value "def". When line 8 executes, a new String object is created with the value "ghi", to which s2 refers. The reference variable s3 still refers to the (immutable) String object with the value "def".


Marco said: (Jul 23, 2014)  
What is immutable?

Priyanga said: (Mar 26, 2016)  
if you declare any string it can't to be changed,it is called immutable.

Abhishek said: (Sep 9, 2016)  
As Strings are immutable then why the value of s2 is changed,as it was earlier def?

Aarti said: (Nov 24, 2016)  
If it is immutable then why the value of s2 changed as it was already initialization with another value?

Priya said: (Jan 30, 2018)  
The string is immutable we can't change the value of string by directly = operators. We can create new string("ghi") it will take otherwise no.

Sonal Gaikwad said: (Aug 7, 2018)  
S2 = def
s3= def
S2= ghi it will also overide s3 also ghi.

Because s2 and s3 pointing to the same value in the literal pool this give new reference to only unique value if a value already exists then both reference s2 n s3 points to one value.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.