isTrue()
is a Validate
class, that is used to check whether the passed expression results in True
or False
.
False
, then the method raises an exception with a formatted message.True
, then the method does not return anything.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;
public static void isTrue(final boolean expression, final String message, final Object... values)
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.
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.
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);}}
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)
On line number 9, the method does not throw an exception because the Boolean expression results in true
.
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
.