about questions from ocajp.i.v8.2.1284

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
clairechanmyae
Posts: 1
Joined: Fri Jul 14, 2017 2:32 am
Contact:

about questions from ocajp.i.v8.2.1284

Post 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:

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 51 guests