🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Java Methods: all 10 questions

Quiz: Java Methods · Question 7 of 10

What does this print? (code)

What does this print?

public class Main {
    static void shout(StringBuilder sb) {
        sb.append("!");
        sb = new StringBuilder("new");
    }
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("hi");
        shout(sb);
        System.out.println(sb);
    }
}
  1. A.hi
  2. B.hi!
  3. C.new
  4. D.new!
Answer & explanation

Correct answer: hi!

The method changes the shared object (adds "!"), then points only its own copy of the reference to a new object. The caller still sees the original, now "hi!".

Can you get the rest right without peeking?

Take the timed Quiz: Java Methods quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →