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

Discussion

The program is run with java -ea Probe26 - what will be the output?

import java.util.*;

public class Probe26
{
    static List<String> seen = new ArrayList<String>();

    static boolean record(String s) { seen.add(s); return true; }

    public static void main(String[] args)
    {
        assert record("a");
        assert record("b");
        System.out.println(seen);
    }
}

  • A.The program prints []
  • B.The program prints [a, b]
  • C.An AssertionError is thrown.
  • D.Compilation fails.

Answer: B

With assertions enabled both expressions are evaluated, so both calls run and the list ends up holding a and b. Run without -ea the same program prints an empty list, because neither call happens. One source file producing two different results depending on a debugging flag is the whole argument against side effects in assertions.

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

Post your comment

Please log in or register to post a comment.