Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What is printed from the following program? 1 class Sophie { 2 3 public static v

ID: 3833349 • Letter: W

Question

What is printed from the following program?

1 class Sophie {

2   

3 public static void main(String[] args) {

4

5 String s = "Java";

6 StringBuilder buffer = new StringBuilder(s);

7 change(buffer);

8 System.out.println(buffer);

9 }

10

11 public static void change(StringBuilder sbval) {

12 sbval.append(" on the web");

13 sbval = new StringBuilder(" and HTML ");

14 }

15 }

16

17   

The program will not compile

Java on the web

Java and HTML

Java

Nothing. There is a runtime error on line 12

The program will not compile

Java on the web

Java and HTML

Java

Nothing. There is a runtime error on line 12

Explanation / Answer

Ans) a
The program prints "Java on the web" and following is the explanation.
Initially s is assigned the string "Java" and the same is assigned to buffer variable after creating a new StringBuilder object. Now buffer contains "Java". When the function 'change' is called with buffer as parameter and inside that the buffer object has the string " on the web" added. That means now buffer object contains "Java on the web".

After that we can see the variable sbval will have new string builder object with string " and HTML " because of 'new' construct used in the statement. Now buffer and sbval points to different objects. Thats why after returning from function, the buffer object will have the value as "Java on the web"

NOTE: One thing you should keep in mind that in Java objects are passed by reference. Thats why the variable 'buffer' which is modified inside the function has got its change reflected outside.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote