Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

public class Probe14
{
    public static void main(String[] args) throws Exception
    {
        StringBuilder sb = new StringBuilder("abcdef");
        sb.setLength(3);
        System.out.println(sb + " " + sb.length());
    }
}

  • A.The program prints abcdef 6
  • B.The program prints abc 3
  • C.The program prints abc 6
  • D.The program prints def 3

Answer: B

setLength truncates the builder when the new length is smaller, discarding everything from that index onward, so the content becomes abc and the length 3. Given a larger value it would pad with null characters instead of throwing.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.