Table of Contents
How does Assertion work in Java?
Steps to use Eclipse Java Assertion
Examples to Implement Java Assertion
Example #3
Advantages of using Assertion in Java
Conclusion
Home Java javaTutorial Java Assertion

Java Assertion

Aug 30, 2024 pm 04:05 PM
java

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

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 vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

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

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

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.

See all articles