Java Programming - Java.lang Class - Discussion
Discussion Forum : Java.lang Class - Finding the output (Q.No. 20)
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);
}
}
Answer: Option
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".
Discussion:
6 comments Page 1 of 1.
Sonal Gaikwad said:
7 years ago
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.
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.
Priya said:
8 years ago
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.
Aarti said:
9 years ago
If it is immutable then why the value of s2 changed as it was already initialization with another value?
Abhishek said:
9 years ago
As Strings are immutable then why the value of s2 is changed,as it was earlier def?
Priyanga said:
9 years ago
if you declare any string it can't to be changed,it is called immutable.
Marco said:
1 decade ago
What is immutable?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers