Page 1 of 1

about questions from ocajp.i.v8.2.1284

Posted: Fri Jul 14, 2017 2:37 am
by clairechanmyae
Hi,

I don't understand why output is "javajavac" for below question :

Code: Select all

What will the following class print when run?
public class Sample{
   public static void main(String[] args)  {
     String s1 = new String("java");
     StringBuilder s2 = new StringBuilder("java");
     replaceString(s1);
     replaceStringBuilder(s2);
     System.out.println(s1 + s2);
  }
  static void replaceString(String s) {
     s = s.replace('j', 'l');
  }
  static void replaceStringBuilder(StringBuilder s) {
     s.append("c");
  }
}
I understand String is immutable. That is why its value can't be change only by calling method and StringBuilder can change its value by calling method. However, return type for replaceStringBuilder method is void. That is why I thought it doesn't change the value of s2 but it seems the answer is saying it changed the value for s2 :geek: :geek:

Re: about questions from ocajp.i.v8.2.1284

Posted: Fri Jul 14, 2017 4:48 am
by admin
s2 keeps pointing to the same StringBuilder object. But the string data contained inside that StringBuilder object itself is changed by the method.

These write ups should be helpful in getting your basics clear:
http://www.javaworld.com/article/207742 ... value.html
and
https://stackoverflow.com/questions/404 ... s-by-value