What is Validate.isTrue in Java?

isTrue() is a staticdescribes the methods in Java that can be called without creating an object of the class method of the Validate class, that is used to check whether the passed expression results in True or False.

  • If the expression results in False, then the method raises an exception with a formatted message.
  • If the expression results in True, then the method does not return anything.

How to import Validate

The definition of Validate can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file.

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the Validate class as follows.

import org.apache.commons.lang3.Validate;

Syntax

public static void isTrue(final boolean expression, final String message, final Object... values)

Parameters

  • final boolean expression: The Boolean expression to check.

  • final String message: The exception message.

  • final Object... values: The optional values for the formatted exception message.

Return value

This method throws an IllegalArgumentException if the Boolean expression results in false. If the Boolean expression results in true, the method doesn’t return anything.

Code

import org.apache.commons.lang3.Validate;
public class Main{
public static void main(String[] args){
int j = 5;
int minVal = 1;
int maxVal = 5;
Validate.isTrue(j >= minVal && j <= maxVal, "The value must be between %d and %d", minVal, maxVal);
j = 7;
Validate.isTrue(j >= minVal && j <= maxVal, "The value must be between %d and %d", minVal, maxVal);
}
}

Output

The output of the code is as follows.

Exception in thread "main" java.lang.IllegalArgumentException: The value must be between 1 and 5
	at org.apache.commons.lang3.Validate.isTrue(Validate.java:158)
	at Main.main(Main.java:12)

Example 1

On line number 9, the method does not throw an exception because the Boolean expression results in true.

Example 2

On line number 12, the method throws an exception because the Boolean expression results in false.

The message of the exception is as follows:

The value must be between 1 and 5.

Free Resources