Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Assertions in Java

 

In this lesson, you will learn

  • What is Assertions
  • Examples

 

What is Assertions

  1. Assertions are the statements that enable you to test any assumptions that you make regarding a program during its execution.
  2. Assumptions can be simple facts such as the range of a number must be between 0 and 100, the person’s age can’t be negative, the period to calculate a simple interest can’t be 0, etc.
  3. In such scenarios, you can use the assertion to validate your code to accept only correct inputs.
  4. Assertions can be implemented using the assert keyword.

 

Assertions are used during the testing of a program. They enable you to test the assumptions made in a program during its execution.

 

Implementing Assertions

The assert keyword is used to implement assertions. Here’s the basic syntax for using assertions in Java:

assert expression;

Or, with an additional detail message:

assert expression : "error message";

 

How do Assertions Work in Java?

Here the expression is a boolean condition. During program execution, the expression with assert statement is tested.

If it returns true then “The assertion made in the program is true and execution continues uninterruptedly”

If the expression evaluates to false, the assertion fails, and an AssertionError is thrown.

 

Assertions are enabled or disabled with the -ea (enable assertions) or -da (disable assertions) flag when running the JVM. By default, assertions are disabled.

 

Before you can successfully implement assertions in your code, you need to enable
them in the Java environment.

 

How to Enable Assertions?

Please follow the following steps after creating a program.

  1. Right click -> Run As -> Run Configurations

 

 

2. Arguments -> VM Arguments -> Apply -> Run

 

Example 1: Implementing Assertions – Validate Age

package assertions;

import java.util.Scanner;

public class ValidateAge {
	//Validate age using 'assert'
	public static void validateAge(String name,int age) {
		assert age>0 && age<100: "Age must be between 1 and 100";
		System.out.println("The age of "+name+" is: "+age);
	}
	public static void main(String args[]) {
		@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter name: ");
		String name = scanner.next();
		System.out.print("Enter age: ");
		int age = scanner.nextInt();
		validateAge(name, age);
	}
}

Output

Test Case 1:

Enter name: James
Enter age: 32
The age of James is: 32

 

Test Case 2:

Enter name: James
Enter age: -10
Exception in thread "main" java.lang.AssertionError: 
Age must be between 1 and 100
	at assertions.ValidateAge.validateAge(ValidateAge.java:8)
	at assertions.ValidateAge.main(ValidateAge.java:18)

 

Example 2: Checking Method Invariants

In this example, we use an assertion to ensure that a method always returns a non-negative value. This is particularly useful in methods where the business logic should guarantee certain outcomes.

 

package assertions;

public class InventoryAssertion {
    private int itemsCount;

    public InventoryAssertion(int initialItems) {
        assert initialItems >= 0 : "Initial items count cannot be negative";
        this.itemsCount = initialItems;
    }

    public void addItem(int count) {
        assert count > 0 : "Must add a positive number of items";
        itemsCount += count;
    }

    public void removeItem(int count) {
        assert count > 0 && count <= itemsCount : 
        	"Invalid count of items to remove";
        itemsCount -= count;
    }

    public int getItemsCount() {
        assert itemsCount >= 0 : "Items count should never be negative";
        return itemsCount;
    }

    public static void main(String[] args) {
        InventoryAssertion inventory = new InventoryAssertion(10);
        inventory.addItem(5);
        inventory.removeItem(3);
        System.out.println("Current inventory count: " + inventory.getItemsCount());
        inventory.removeItem(15); 
        // This will trigger an AssertionError if assertions are enabled.
    }
}

Output

Test Case 1:

Current inventory count: 12

 

Test Case 2: After enabling Assertion in VM Arguments

Current inventory count: 12
Exception in thread "main" java.lang.AssertionError: Invalid count of items to remove
	at assertions.InventoryAssertion.removeItem(InventoryAssertion.java:17)
	at assertions.InventoryAssertion.main(InventoryAssertion.java:31)

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review