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.

Related Post

‘ant’ is not recognized as an internal or external command, operable program or batch file.
Write a function to reverse the words in a string? (e.g. “Your time has come” – > “come has time Your”)
What is a ‘Test Case’?
What is Boundary Value Analysis?
What is a dangling pointer?

Comments

Leave a Reply