What will be output of the following program?
public static void main(String[] args) {
String s1 = new String("Hello");
change(s1);
System.out.println(s1);
}
public static void change(String s1) {
s1 += " Guest";
}
The output of the program will be “Hello” only. ” Guest” won’t be appended to the original string.
This is due to immutable nature of string. In the change method, appending string to s1 won’t change previous string, rather it will create a new string which will be “Hello Guest” and will be pointing to some other memory location and not to the String location which is passed to the ‘change’ method.
September 27, 2008 | Filed Under Java
Related Post
Comments
Leave a Reply