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

Assertions - Pointing out the errors Questions and Answers

41.

Which line contains the error?

public class Sample41
{
    public static void main(String[] args)
    {
        assert "abc".substring(3).isEmpty();
        assert "abc".charAt(3) == 'd';
        System.out.println("checked");
    }
}

Answer: A

The two look symmetrical but are not. A start index equal to the length is legal for substring and gives the empty string, so the first assertion passes. charAt rejects an index equal to the length and throws StringIndexOutOfBoundsException, so the second fails before it can be evaluated as true or false.

Please log in or register to report this question.

42.

Which line rests on a mistaken assumption?

public class Sample42
{
    public static void main(String[] args)
    {
        String csv = "a,b,,";
        assert csv.split(",").length == 4 : csv.split(",").length;
        System.out.println(csv.split(",").length);
    }
}

Answer: B

split with the default limit discards trailing empty strings, so the two empty fields at the end are dropped and the length is 2, not 4. The assertion encodes the wrong expectation. Passing a negative limit, split(",", -1), keeps them and would make the claim true.

Please log in or register to report this question.

43.

Which line rests on a mistaken assumption?

public class Sample43
{
    public static void main(String[] args)
    {
        assert Math.round(-2.5) == -3 : Math.round(-2.5);
        System.out.println(Math.round(-2.5));
    }
}

Answer: C

Math.round adds one half and takes the floor, so a value exactly halfway rounds toward positive infinity: -2.5 becomes -2, not -3. The assertion assumes rounding moves away from zero on both sides, which holds for positive halves only.

Please log in or register to report this question.

44.

Which line rests on a mistaken assumption?

public class Sample44
{
    public static void main(String[] args)
    {
        int mask = 1 << 32;
        assert mask == 0 : mask;
        System.out.println(mask);
    }
}

Answer: D

For an int shift only the low five bits of the distance are used, so a shift of 32 is a shift of 0 and the value stays 1. The assertion assumes the bits fall off the end and leave zero. The result is 1, so the assertion fails with 1 as its detail message.

Please log in or register to report this question.

45.

Which line contains the error?

import java.util.*;

public class Sample45
{
    public static void main(String[] args)
    {
        Map<String, Integer> m = new HashMap<String, Integer>();
        m.put("a", 1);
        assert m.get("b") == 1 : "missing key";
        System.out.println(m.size());
    }
}

Answer: A

get returns null for an absent key, and comparing a null Integer against the int 1 unboxes it, throwing NullPointerException rather than evaluating to false. The assertion cannot even report its message. Check containsKey first, or compare against Integer.valueOf(1) with equals.

Please log in or register to report this question.

46.

Which line contains the error?

package com.acme.core;

public class Sample46
{
    public static void main(String[] args)
    {
        int stock = -1;
        assert stock >= 0 : stock;
        System.out.println(stock);
    }
}

Answer: B

Nothing is wrong with the code. The mistake people make with it is at the command line: running java -ea:com.acme... com.acme.core.Sample46 enables the check, but -ea:com.acme.core without the three dots names a CLASS, and no class has that name, so assertions stay off and the negative stock passes unnoticed.

Please log in or register to report this question.

47.

Which line is an inappropriate use of an assertion?

public class Sample47
{
    static void process(int[] data)
    {
        try
        {
            assert data.length > 0 : "empty batch";
        }
        catch (AssertionError e)
        {
            System.out.println("continuing anyway");
        }
    }

    public static void main(String[] args)
    {
        process(new int[0]);
    }
}

Answer: C

Catching AssertionError and carrying on defeats the point of the assertion: the broken invariant is reported, ignored, and the program continues in the state the assertion said was impossible. AssertionError sits under Error precisely to discourage this. If the condition is recoverable it is not an assertion.

Please log in or register to report this question.

48.

Which line is an inappropriate use of an assertion?

public class Sample48
{
    static int find(int[] a, int target)
    {
        for (int i = 0; i < a.length; i++)
        {
            if (a[i] == target) return i;
        }
        assert false : "target not present";
        return -1;
    }

    public static void main(String[] args)
    {
        System.out.println(find(new int[]{1, 2}, 9));
    }
}

Answer: D

A missing target is an ordinary outcome for a search, not an impossible state, and the method already handles it by returning -1. Asserting false on a reachable path turns a normal result into a crash under -ea. assert false is only right where control genuinely cannot arrive.

Please log in or register to report this question.

49.

Which line contains the error?

public class Sample49
{
    public static void main(String[] args)
    {
        String a = "ja" + "va";
        String b = "java";
        assert a == b;
        String c = new StringBuilder("ja").append("va").toString();
        assert c == b;
    }
}

Answer: A

The first assertion passes: concatenating two literals is folded at compile time into the single pooled literal java, so the references are identical. The second fails, because a String built at runtime is a new object no matter what it contains. Identity comparison of strings is only ever safe for interned values, which is why equals exists.

Please log in or register to report this question.

50.

Which line rests on a mistaken assumption?

public class Sample50
{
    public static void main(String[] args)
    {
        byte b = 10;
        b += 300;
        assert b == 310 : b;
        System.out.println(b);
    }
}

Answer: B

A compound assignment carries an implicit narrowing cast, so b += 300 compiles and wraps the result into a byte rather than failing. The value becomes 54, so the assertion is false. The line the author expected to be rejected is legal, and the assertion states the arithmetic they assumed.

Please log in or register to report this question.

Loading…

Other Subjects

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