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

Assertions - Pointing out the errors Questions and Answers

51.

Which line rests on a mistaken assumption?

public class Sample51
{
    public static void main(String[] args)
    {
        Object o = null;
        assert o instanceof String : "not a string";
        System.out.println("ok");
    }
}

Answer: C

instanceof answers false for null rather than throwing, so the assertion fails cleanly with its message and no NullPointerException occurs. That is correct behaviour, but the message is misleading: null is not a String of the wrong kind, it is no object at all. A null check states the real precondition.

Please log in or register to report this question.

52.

Which line is an inappropriate use of an assertion?

public class Sample52
{
    static boolean verbose = false;

    public static void main(String[] args)
    {
        assert verbose = true;
        if (verbose) System.out.println("diagnostics on");
        System.out.println("done");
    }
}

Answer: D

This is the trick of using an assertion to detect whether assertions are enabled: the single = assigns, the assigned value is boolean so it compiles, and it passes. It works, but it makes the program behave differently under -ea by design, which is the opposite of what assertions are for, and it reads as a typo for ==.

Please log in or register to report this question.

53.

Which line is an inappropriate use of an assertion?

public class Sample53
{
    public static void main(String[] args)
    {
        assert compute() > 0;
        System.out.println("checked");
    }

    static int compute() throws IllegalStateException
    {
        throw new IllegalStateException("no data");
    }
}

Answer: A

The condition calls a method that always throws, so with -ea the program dies with IllegalStateException rather than an AssertionError, and without -ea it prints checked and never notices. An assertion whose condition can throw reports the wrong failure, or none at all.

Please log in or register to report this question.

54.

Which line contains the error?

public class Sample54
{
    public static void main(String[] args)
    {
        assert -0.0 == 0.0;
        assert Double.valueOf(-0.0).equals(Double.valueOf(0.0));
        System.out.println("both");
    }
}

Answer: B

The primitive comparison is true: == treats negative and positive zero as equal. Double.equals does not, because it compares the underlying bit patterns so that collections behave consistently. So the first assertion passes and the second fails, on values that look identical.

Please log in or register to report this question.

55.

Which line is an inappropriate use of an assertion?

public class Sample55
{
    private int[] data = new int[4];

    public int at(int i)
    {
        assert i >= 0 && i < data.length : i;
        return data[i];
    }
}

Answer: C

at() is public, so the valid index range is part of what callers are promised and must be enforced whether or not -ea is set. Here the check disappears in production and the array access throws ArrayIndexOutOfBoundsException instead. That happens to be a reasonable error, but it is luck rather than design; the bounds belong in an explicit test.

Please log in or register to report this question.

56.

Which line contains the error?

import java.util.*;

public class Sample56
{
    public static void main(String[] args)
    {
        List<String> fixed = Arrays.asList("a", "b");
        assert fixed.size() == 2;
        fixed.add("c");
        System.out.println(fixed);
    }
}

Answer: D

The assertion is true and harmless. The fault is the add: Arrays.asList returns a fixed-size view backed by the array, so adding throws UnsupportedOperationException. No assertion would have caught it, because the list really does have two elements at the point that was checked.

Please log in or register to report this question.

57.

Which line contains the error?

import java.util.*;

public class Sample57
{
    public static void main(String[] args)
    {
        List<String> ro = Collections.unmodifiableList(new ArrayList<String>());
        assert ro.isEmpty();
        ro.add("x");
        System.out.println(ro.size());
    }
}

Answer: A

An unmodifiable view rejects every mutation with UnsupportedOperationException, so the add is the error. The assertion above it is correct and passes. Note the wrapper is a view, not a copy: changes made through the original list would still be visible here.

Please log in or register to report this question.

58.

Which line contains the error?

import java.util.*;

public class Sample58
{
    public static void main(String[] args)
    {
        List<String> l = new ArrayList<String>(Arrays.asList("a", "b"));
        for (String s : l)
        {
            assert s != null;
            if (s.equals("a")) l.remove(s);
        }
    }
}

Answer: B

Removing from a list while iterating it with a for-each throws ConcurrentModificationException on the next step. The assertion is fine and unrelated. Removal during iteration is done through the Iterator's own remove method, or by collecting the doomed elements and removing them afterwards.

Please log in or register to report this question.

59.

Which line is an inappropriate use of an assertion?

public class Sample59
{
    static int made = 0;

    Sample59()
    {
        assert ++made > 0;
    }

    public static void main(String[] args)
    {
        new Sample59();
        new Sample59();
        System.out.println(made);
    }
}

Answer: C

The counter is incremented inside the assertion, so it records constructions only when -ea is set: the program prints 2 with assertions on and 0 with them off. A count the program reports is state it depends on, and must be maintained by an ordinary statement.

Please log in or register to report this question.

60.

Which line contains the error?

public class Sample60
{
    interface Op { int apply(int v); }

    public static void main(String[] args)
    {
        Op twice = v ->
        {
            assert v >= 0 : v;
            return v * 2;
        };
        System.out.println(twice.apply(-3));
    }
}

Answer: D

Assertions are perfectly legal inside a lambda body, and this one states a reasonable precondition. The error is the call, which passes -3 and so breaks the stated invariant. With -ea it reports an AssertionError carrying -3; without it the method quietly returns -6.

Please log in or register to report this question.

Loading…
Tags: Assertions - Pointing out the errors Questions and Answers || Assertions - Pointing out the errors MCQ Questions and Answers || Assertions - Pointing out the errors GK Questions and Answers || Assertions - Pointing out the errors GK MCQ Questions || Assertions - Pointing out the errors Multiple Choice Questions and Answers || Assertions - Pointing out the errors GK || GK on Assertions - Pointing out the errors || Java Programming Questions and Answers || Java Programming MCQ Questions and Answers || Java Programming GK Questions and Answers || GK on Java Programming