Home > Java > javaTutorial > body text

Java Assertion

WBOY
Release: 2024-08-30 16:05:04
Original
833 people have browsed it

In Java, Assertion is a statement that ensures or tests the correctness of the assumptions made in a program. It is done with the help of the assert statement. When the written assumption is executed, it is considered as true. If it is false, an assertion error will be thrown by the Java Virtual Machine.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The main reasons why Assertions are used are:

  • To confirm whether an unreachable code is reachable.
  • To check whether the assumptions available in the comments are correct or not.
  • To confirm, the default case in the switch is not reached.
  • After the invocation of a method.
  • To check the state of an object.

Syntax

Below is the syntax of the Java Assertion statement.

assert expression;
Copy after login
assert expr1 : expr2;
Copy after login

Any of these syntaxes can be used based on the requirement.

How does Assertion work in Java?

As already mentioned, assert can be written in two forms.

  • The syntax asserts expression; is used in order to test the expressions of Boolean form. If the particular expression is false, the program gets terminated by throwing an AssertionError. Unlike the normal exceptions, these errors are disabled during runtime.
  • However, the syntax asserts expr1: expr2; it is used in cases where the program has some extra information that helps diagnose certain failures.
  • Similar to the uncaught exceptions in Java, assertion errors are commonly labeled in stack trace along with the file as well as line number from which the exception is thrown.

Even though these are the main pros of Assertion, there are certain situations where Assertions should not be used. They are:

  • Error message replacement.
  • Argument checking in public methods
  • Command-line arguments.
Note:  Before compiling the code, make sure that assertion is enabled.

Syntax

java –ea programname
Copy after login

Or

java –enable assertions programname
Copy after login

Steps to use Eclipse Java Assertion

In Eclipse, it can be done using the below steps.

Step 1: Select Run Configurations.

Java Assertion

Step 2: Go to the left panel and select Java Application, and Right-click on it.

Java Assertion

Step 3: Select New configuration and type –ea on VM Arguments. Once it is done, click.

Java Assertion

Similarly, assertions can be disabled using the syntax given below. Java –da programname

Examples to Implement Java Assertion

Now, let us see some sample programs for the assertion in order to get a clear idea of the same.

Example #1

Java program to check whether a particular value is higher than 20.

Code:

class AssertionExample{
public static void main( String args[] ){
int val = 14;
assert val>=20:" Value is not valid";
System.out.println("The given value is: "+ val);
}
}
Copy after login

Output:

  • On executing the code, the message “The given value is 14” gets displayed.

Java Assertion

  • It can be clearly seen that assertion is not checked here since the value is greater than 20 is not checked.
  • In order to enable assertion, -ea has to be set before compiling. For that, perform the steps mentioned in NOTE.
  • If you again try to run the code, it can be clearly seen that an AssertionError has been thrown since the value is less than 20.

Java Assertion

Example #2

Java program to check whether a particular user input value is higher than 20.

Code:

import java.util.Scanner;
class AssertionExample{
public static void main( String args[] ){
Scanner <u>sc</u> = new Scanner( System.in );
System.out.print("Enter a number to check assertion ");
//store the input value to the variable <u>val</u>
int val = sc.nextInt();
//assertion check whether the input value is greater than 20
assert val>=20:" Value is not valid";
System.out.println("The given value is: "+ val);
}
}
Copy after login

Output:

  • The user will be asked to input a number on executing the code. In the below result, the number 13 is given as input. Since it is less than 20, an AssertionError has been thrown.

Java Assertion

  • At the same time, when a value which is greater than 20 is given, no errors are thrown, and the message gets displayed.

Java Assertion

Example #3

Java program to check the number of days in a week.

Code:

class AssertionExample {
//main method
public static void main(String args[]) {
//declare a string days
String[] days = {" Monday " , " Holiday " , " Saturday " , " Tuesday " , " Wednesday " , " Sunday " , " Thursday " , " Friday " };
//set the assertion as 7
assert days.length==7 : "7 days are present in a week, Your input is wrong";
//print the line below
System.out.println("There are " + days.length + "  days in a week");
}
}
Copy after login

Output:

  • On executing the code, an assertion error is thrown as the number of days in a week is 7, and the string input given contains more than that.

Java Assertion

  • Let us remove Holiday from the input values and see what the output will be.

Java Assertion

Yes. The line gets printed as the assertion value satisfies the input value.

Advantages of using Assertion in Java

The following are the main advantages of using Assertion.

  • Efficient detection and correction of bugs.
  • Boilerplate code will be removed and helps in creating a readable code.
  • Execution time won’t be affected since it gets removed automatically during runtime.
  • Quick bug detection and correction.
  • Code optimization and refactoring is done with high confidence in order to function correctly.

In addition to the above points, below are the important points that have to be known while studying Assertions.

  • An assertion in Java is introduced in the version JDK 1.4
  • Assert is the keyword used in order to implement assertion.
  • Enabling and disabling of assertion can be done at runtime with the help of corresponding syntaxes.
  • Even though assertion compliments the exception, it does not replace the exception.
  • It does not replace the unit testing even if it helps in the validation of conditions.
  • Never use assertion for arguments or parameters validation of a method that is public.

Conclusion

Java Assertion is a statement that checks the trueness of a particular condition. It is commonly used in testing during software development. Moreover, they are used with certain Boolean expressions. In this article, several aspects such as syntax, working, pros, cons, and examples of Assertion is explained in detail.

The above is the detailed content of Java Assertion. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template