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

Discussion

What will be the output of the program?

public class Item80
{
    void execute()
    {
        String s = "a";
        for (int i = 0; i < 3; i++) s += s;
        System.out.println(s + " " + s.length());
    }

    public static void main(String[] args)
    {
        Item80 demo = new Item80();
        demo.execute();
    }
}

  • A.The program prints aaaa 4
  • B.The program prints aa 2
  • C.The program prints aaa 3
  • D.The program prints aaaaaaaa 8

Answer: D

Each pass doubles the string rather than adding one character, because s is appended to itself. Starting from one character, three doublings give eight. Each iteration also discards the previous String, which is why a builder is preferred in a loop.

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

Post your comment

Please log in or register to post a comment.