All you need to know about the assertion
Sun, 17 Nov 2024
assertion
Let us take an example:
findRoot(int a, int b, int c)
, which finds the root of the equation ax^2 + bx + c = 0
and returns the root.private double findRoot(int a, int b, int c){
int det = b*b - 4*a*c;
double root = (-b + Math.sqrt(det))/(2*a);
return root;
}
a
, b
, c
is read from somewhere else, then passed to the function, then there might be a possibility that the function findRoot(int,int,int)
will not behave correctly.What if we have something during development phase, that will let us know if the equation have two or zero root? Then we can find out why the equation has two or zero root by searching through the retrieval of a
, b
, c
. This is exactly what assertion
does.
something
in a strong, confident, and forceful way,something
, we believe that something
should be true,something
always true.It can be written in 2 ways.
assert expr;
assert expr : errorMessageExpression;
errorMessageExpression
: allows writing custom error message. Can be any data type,If expr
evaluates to true
, no action will be taken. Code will be executed normally. But if evaluates to false, java.lang.AsssertionError
will be thrown.
Let's see the code first
private double findRoot(int a, int b, int c){
int det = b*b - 4*a*c;
assert det == 0;
double root = (-b + Math.sqrt(det))/(2*a);
return root;
}
If we call the function with findRoot(1,2,1)
, it will return -1
in both cases.
But for findRoot(1,5,6)
, our previous code will return -2
, but updated code will throw java.lang.AssertionError
. Then we can debug the issue.
-ea
) to see assertion in action:java -ea OurClassName
java -ea .\src\Main.java
Try to understand by yourself.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Bit2Byte {
public static void main(String[] args) {
// Today's date: 20 oct 2024
// LocalDate dob = LocalDate.of(2001,3,21); // ok. 'User is adult'
LocalDate dob = LocalDate.of(2021,3,21);
int age = calculateAge(dob);
assert age >= 8 : "User is child";
System.out.println("User is adult");
}
private static int calculateAge(LocalDate localDate){
LocalDate now = LocalDate.now();
long age = ChronoUnit.YEARS.between(localDate,now);
return (int)age;
}
}
Executed using:
java -ea .\src\Bit2Byte.java
Output:
Exception in thread "main" java.lang.AssertionError: User is child
at Bit2Byte.main(Bit2Byte.java:12)
This is a comment 1.
This is a comment 2.