Java Assertion
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;
assert expr1 : expr2;
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.
Syntax
java –ea programname
Or
java –enable assertions programname
Steps to use Eclipse Java Assertion
In Eclipse, it can be done using the below steps.
Step 1: Select Run Configurations.
Step 2: Go to the left panel and select Java Application, and Right-click on it.
Step 3: Select New configuration and type –ea on VM Arguments. Once it is done, click.
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); } }
Output:
- On executing the code, the message “The given value is 14” gets displayed.
- 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.
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); } }
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.
- At the same time, when a value which is greater than 20 is given, no errors are thrown, and the message gets displayed.
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"); } }
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.
- Let us remove Holiday from the input values and see what the output will be.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
