Assertion in Java

Assertion facility is added in J2SE 1.4. In order to support this facility J2SE 1.4 added the keyword assert to the language, and AssertionError class. An assertion checks a boolean-typed expression that must be true during program runtime execution. The assertion facility can be enabled or disable at runtime.

Declaring Assertion

Assertion statements have two forms as given below

assert expression;

assert expression1 : expression2;

The first form is simple form of assertion, while second form takes another expression. In both of the form boolean expression represents condition that must be evaluate to true runtime.

If the condition evaluates to false and assertions are enabled, AssertionError will be thrown at runtime.

Some examples that use simple assertion form are as follows.

assert value > 5 ;

assert accontBalance > 0;

assert isStatusEnabled();

The expression that has to be asserted runtime must be boolean value. In third example isStatusEnabled() must return boolean value. If condition evaluates to true, execution continues normally, otherwise the AssertionError is thrown.

Following program uses simple form of assertion

//AssertionDemo.java

Class AssertionDemo{

Public static void main(String args[]){

System.out.println( withdrawMoney(1000,500) );

System.out.println( withdrawMoney(1000,2000) );

}

public double withdrawMoney(double balance , double amount){

assert balance >= amount;

return balance ? amount;

}

}

In above given example, main method calls withdrawMoney method with balance and amount as arguments. The withdrawMoney method has a assert statement that checks whether the balance is grater than or equal to amount to be withdrawn. In first call the method will execute without any exception, but in second call it AssertionError is thrown if the assertion is enabled at runtime.

Enable/Disable Assertions

By default assertion are not enabled, but compiler complains if assert is used as an identifier or label. The following command will compile AssertionDemo with assertion enabled.

javac ?source 1.4 AssertionDemo.java

The resulting AssertionDemo class file will contain assertion code.

By default assertion are disabled in Java runtime environment. The argument ?eanbleassertion or ?ea will enables assertion, while ?disableassertion or ?da will disable assertions at runtime.

The following command will run AssertionDemo with assertion enabled.

Java ?ea AssertionDemo

or

Java ?enableassertion AssertionDemo

Second form of Assertion

The second form of assertion takes another expression as an argument.

The syntax is,

assert expression1 : expression2;

where expression1 is the condition and must evaluate to true at runtime.

This statement is equivalent to

assert expression1 : throw new AssertionError(expression2);

Note: AssertionError is unchecked exception, because it is inherited from Error class.

Here, expression2 must evaluate to some value.

By default AssertionError doesn't provide useful message so this form can be helpful to display some informative message to the user.

Rahim Vindhani
Application Develper [Application Development & Webservices]
IBM Global Services, pune, India
email: rahim.vindhani@gmail.com
web: http://www.rahim.co.nr

green cleaning service Park Ridge ..
In The News:

A groundbreaking new study has uncovered disturbing AI blackmail behavior that many people are unaware of yet.
Four teams of autonomous humanoid robots competed in China's first AI soccer tournament, demonstrating advanced capabilities in ball detection and independent decision-making.
The ID. Buzz autonomous van features self-driving technology with 13 cameras, nine LiDAR units and five radars after Volkswagen partnered with Hamburg and Uber for 2026 deployments.
Social Security phishing scams use urgency and impersonation to steal personal data. Learn how to spot fake SSA emails and implement 10 protective measures.
French startup Pazzi Robotics created an AI-powered pizza robot that made pies in under five minutes without human help, but it closed in 2022 despite patents and expert partnerships.
Reclaim your time from big tech with effective screen time reduction strategies for iPhone and Android, featuring steps to limit app usage and create phone-free zones.
Amazon Prime Day shoppers face threats from 120,000-plus scam websites as cybercriminals prepare phishing traps and malware ahead of the July sales event.
Fox News' AI Newsletter brings you the latest on this rapidly evolving technology.
The AEON humanoid robot tackles labor challenges with Nvidia AI, Microsoft Azure cloud and advanced spatial awareness, working alongside industry leaders Schaeffler and Pilatus.
Google's Ask Photos feature brings AI-powered searches to your photo library, letting you find memories with natural language queries while maintaining privacy controls.
The return of blue book exams emerges as universities fight widespread AI academic dishonesty and educators debate whether to ban AI tools or teach responsible usage.
Signs your phone might be hacked include strange behavior, unauthorized texts, battery drain and pop-ups, while protection involves updating software and avoiding public Wi-Fi.
Tokyo startup H2L has launched Capsule Interface technology enabling full-body robot control with muscle sensors, offering immersive remote operation.
The A.I. industry seems set for growing pains as Big Tech companies scramble for solutions to the medium's unprecedented strain on the power grid.
Fourth of July fireworks cause a 60% spike in lost pets, but GPS trackers and AI photo-matching services like Love Lost can help reunite missing dogs with their families.
Protect yourself from jugging, the rising crime by which thieves monitor ATM users and follow them to steal cash, with six practical safety tips to stay alert and secure.
U.S. airlines like Delta, American and United are selling your domestic flight records to government agencies through the little-known Travel Intelligence Program.
Autonomous robots from Uber Eats are rolling out across U.S. cities, featuring LIDAR sensors, secure compartments and all-weather operation for food and grocery delivery.
Costco has expanded into EV infrastructure with new ultra-fast charging stations that can charge most electric vehicles to 80% in 20-60 minutes while shoppers browse the warehouse.
The new Gemini Robotics On-Device AI allows robots to perform complex tasks without internet, offering enhanced privacy, reliability and adaptability for real-world use.
Protect yourself from Amazon phishing scams by spotting red flags like suspicious sender addresses and spelling errors while using Amazon's Message Center to verify communications.
GAC Group's new Govy AirCab flying car combines lightweight design with advanced safety systems and smart cabin technology to revolutionize city travel with an 18.6-mile range.
The Berkeley Humanoid Light (BHL) is a lightweight, open source humanoid robot that anyone can build using 3D-printed parts and off-the-shelf components.
Meta’s new AI chatbot is getting personal, and it might be sharing more than you realize.
A new threat targets both Android and iPhone users: SparkKitty, a powerful mobile malware strain that scans private photos to steal cryptocurrency recovery phrases and other sensitive data.

Popular Fleet Maintenance Programs

Some companies that are in need of fleet management may... Read More

Introduction To ISDN, Part II

In the previous ISDN article, we looked at how and... Read More

What Stands Behind The Software Description?

With thousands of web pages added to the Net every... Read More

Algebra Help Software

Need help making sense of algebra? Have algebra lectures in... Read More

The Dreaded Paper Label - Should it be Used?

While paper labeling CDs and DVDs may appear to be... Read More

Microsoft RMS ? Great Plains Integration ? Overview For IT Specialist

Microsoft Great Plains and Microsoft Retail Management System (Microsoft RMS)... Read More

ERP Software Financing: the Future? ? Overview for Company Owner

In our case ? we serve Microsoft Business Solutions ERP... Read More

SSH (SCP) Send Files from Windows to Your Linux Box

Not all of us have the luxury of working both... Read More

A Simple Guide To Wikis

A wiki is an editable text-based website. But you don't... Read More

Microsoft Great Plains: Government & Non-Profit Organization ? Workflow Implementation

Usually workflow & messaging is realized in CRM and then... Read More

Story Development Software: Good or Evil?

In the early days of the personal computer, we're talking... Read More

Microsoft Great Plains Data Conversion ? Overview For Developer

Looks like Microsoft Great Plains becomes more and more popular,... Read More

Microsoft CRM Integration with IBM Lotus Notes Domino ? Machinery Dealership Example

IBM Lotus Notes with Domino email server is traditional document... Read More

IT Department Skills to Support Microsoft Great Plains and Microsoft CRM

Microsoft Great Plains as ERP and Microsoft CRM as... Read More

What is Preventive Maintenance Software?

Preventive Maintenance (PM) is defined as scheduled work done on... Read More

Microsoft Great Plains ? Licensing & Product Versions

Current Microsoft Business Solutions Great Plains has more that 10... Read More

Internet Security Threats: Who Can Read Your Email?

Before being able to choose a secure Internet communication system,... Read More

Tripwire for Linux File Integrity

What is Tripwire?Tripwire is a form intrusion detection system (IDS)... Read More

How to Tell You Have Spyware, Ad-ware or Viruses

Usually, the easiest way to tell you have spyware is... Read More

C++ Tutorials: 3, Program Flow (If, Else, While, For)

Program Flow is what you think it is. How the... Read More

Navision Sales Module & Reporting: Jet Reports, C/ODBC, XBRL, Business Analytics ? highlights

Microsoft bought Navision, Denmark based software development company, along with... Read More

Great Plains Sales Order Processing and Invoicing Modules ? Tips For Consultants

We'll give you non formal view, based on our consulting... Read More

Do You Know These Facts About Spyware ?

Imagine something that follows you home and sets itself up... Read More

Most Common Ways to Accumulate Spyware (where It is Downloaded to Your PC)

It is possible that if one avoided all sources of... Read More

5 Easy File Management Tips in Microsoft Word

How many steps does it take you to locate and... Read More

emergency cleaning services Morton Grove ..