Assert Statements Exercises:

Assert Statements Tutorial

Question 1

Given the code below, write the assert statements at the places indicated that correctly describe the value of max in the class below.

// openjml --esc AssertExample1.java
public class AssertExample1 {

    private int max;

    public void max3(int a, int b, int c) {
        if (a >= b && a >= c) {
            max = a;
            // first assert here
        } else if (b >= a && b >= c) {
            max = b;
            // second assert here
        } else {
            max = c;
        }
        // third assert here
    }

}

Learning Objectives:

  • Gain practice using assert statements
  • Understand how assert can be used

Question 2

Given the method below, write the assert statements describing the state of the program that verify at the places indicated.

// openjml --esc AssertExample2.java
public class AssertExample2 {
    
public boolean primeChecker(int num) {
        //@ assume num > 0;
	boolean isPrime = true;
        int i;
	for (i = 2; i < num/2; i++) {
                //@ assume isPrime && 2 <= i;
		if (num % i == 0) {
			// first assert here
			isPrime = false;
			return isPrime;
		}
	}
        //@ assume isPrime && 2 <= i;
        if (num % i == 0) {
            isPrime = false;
            return isPrime;
        }
	// second assert here
	return isPrime;
}

}

Learning Objectives:

  • Gain more experience writing assert statements

Answer Key

All exercises

Resources