Java - What is the output: String parameter and concatenation?

Question

What is the output of the following code?

public class Main {
  public static void changeString(String s2) {
    System.out.println("#2: s2 = " + s2);
    s2 = s2 + " there from book2s.com";
    System.out.println("#3: s2 = " + s2);
  }

  public static void main(String[] args) {
    String s1 = "hi";
    System.out.println("#1: s1 = " + s1);
    Main.changeString(s1);
    System.out.println("#4: s1 = " + s1);
  }
}


Click to view the answer

#1: s1 = hi
#2: s2 = hi
#3: s2 = hi there from book2s.com
#4: s1 = hi

Note

A String object is immutable.

You cannot be changed after it is created.

To change the content of a String object, create a new String object with the new content.

Related Quiz