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

elite cleaning services Des Plaines ..
In The News:

Learn how to set email reminders on iPhone and Android so you never forget to reply again. Simple built-in features help you stay organized and on top of messages.
Discover how Apple's passkeys revolutionize Mac security by replacing vulnerable passwords with biometric authentication and encryption for ultimate protection.
New survey reveals 78% of parents fear AI scams targeting their kids, yet nearly half haven't discussed these threats. Learn why this dangerous gap exists.
Chrome now autofills passport and driver's license info automatically. Google's latest browser update adds official document support with encryption and user control.
Scammers impersonate Department of Veterans Affairs employees claiming veterans owe money, but real VA communications only direct to VA.gov or official channels.
The AltoVolo Sigma hybrid-electric aircraft flies 500 miles at 220 mph while operating 80% quieter than helicopters, featuring safety systems and compact design.
Google search scam alert: fake customer service numbers can give scammers remote control of your phone. Learn how to spot these traps and protect yourself.
Electric vehicles overtake gas cars in total CO2 savings after just two years of driving, with emissions benefits growing over time as power grids get cleaner.
Louvre Museum reportedly used "Louvre" as password for surveillance system during $100M jewel heist. Learn how weak passwords put even famous institutions at risk.
Bipartisan AI jobs bill from Sens. Hawley and Warner would require companies to report AI-related layoffs and hiring to Department of Labor quarterly.
Joe A. from Shelton, Connecticut, lost $228,000 to a ZAP Solutions cryptocurrency investment scam after his divorce, highlighting rising online fraud.
AI-powered autonomous trucks from Waabi and Volvo target U.S. freight driver shortage with Level 4 self-driving technology and NVIDIA computing platform integration.
Survive flight disruptions with expert travel tips: Book early morning flights, download airline apps and know your refund rights during service cuts.
Apple's iOS 26.1 update delivers major security fixes, performance boosts and enhanced privacy controls for your iPhone. Discover why updating now protects your data.
Russian hackers use fake CAPTCHA tests to spread dangerous malware targeting governments and journalists. Learn how to protect yourself from these deceptive attacks.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Miami-Dade debuts America's first autonomous police SUV with AI cameras, drone deployment and real-time crime detection in groundbreaking law enforcement pilot.
Bank impostor scams cost Americans $2.9 billion as criminals use AI voices and caller ID spoofing to steal life savings. Learn nine essential fraud protection tips.
Foreign-owned apps secretly harvest personal data from seniors, making them prime targets for scams. Learn how to protect your privacy and stop data brokers today.
Sens. Josh Hawley and Richard Blumenthal introduce bipartisan GUARD Act to protect minors from AI chatbots through mandatory age verification and disclosure requirements.
Ghost-tapping scammers exploit wireless technology to drain accounts through small transactions, but RFID-blocking wallets and transaction alerts can protect you.
French pilot project demonstrates wireless charging roads that can deliver over 300 kilowatts of power to EVs while driving, potentially eliminating range anxiety.
YouTube's Ghost Network spreads information-stealing malware through thousands of fake videos offering cracked software, using compromised accounts and fake engagement.
Protect your privacy by disabling your smart TV microphone. Most TVs have hidden mics that listen even when voice commands are off. Learn quick steps to stop unwanted audio capture.
SessionReaper vulnerability hits Magento and Adobe Commerce stores, compromising 250+ sites in one day. Hackers steal data and hijack shopping sessions.

Microsoft Great Plains Upgrade ? Things to Consider and FAQ

If you have Microsoft Great Plains and support it for... Read More

10 Programming Tips

(1) Avoid using the same variable again and again for... Read More

Razzle Dazzle Them

Once upon a time not so long ago, there was... Read More

Corporate Accounting System: Microsoft Great Plains ? Overview

Corporate ERP/MRP selection might be tough one, especially considering very... Read More

Microsoft CRM Lotus Notes Domino Connector FAQ

Microsoft Business Solutions CRM and IBM Lotus Notes Domino, being... Read More

Lowering The Risks In Developing Do-It-Yourself Software Projects

Mike Dunville* had a decision to make. As the new... Read More

Manufacturing Solutions for Microsoft Great Plains ? Overview for Consultant

Microsoft Business Solutions Great Plains has full-featured manufacturing set of... Read More

Microsoft CRM Messaging through Lotus Domino eMail Server - Balanced Solution

Microsoft CRM and IBM Lotus Notes Domino seem to be... Read More

Microsoft Great Plains Logistics & Warehouse Management ? Implementation & Customization Highlights

Logistics automation is often considered as barcoding extension to Sales... Read More

Great Plains DOS Support ? Notes for Consultant

Great Plains Accounting, accounting package for mid-size and small companies... Read More

Removing Incoming Email in MS Exchange, C# Example

The purpose of one of our projects was MS Exchange... Read More

Google Brings the Earth to Your Desktop

Google Inc. has launched a new software package that allows... Read More

Software Development in 2005 - Back to the Future

2005 ? Back to the Future.What does the future hold?... Read More

EDI: Electronic Document Interchange for Microsoft Great Plains ? Overview for Software Developer/Pr

Microsoft Great Plains - Microsoft Business Solutions accounting and ERP... Read More

Alien Intruders!

You probably didn't casually invite, or extend a formal attendance... Read More

Spyware, Adware, etc. -- Terms and Common Sense

When reading an article where some term is used often,... Read More

How to Get The Best Accounting Software For Your Small Business

Buying accounting software is a major investment. It's an important... Read More

6 Easy Steps for a Smoother CD/DVD Order

It's all about turn times in the eMedia industry! The... Read More

What is Preventive Maintenance Software?

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

SyncUp ? A File/Folder Synchronizer For Windows

SyncUp, a file synchronizer is designed to assist the home... Read More

Free Software - Powerful Alternatives to Budget-Busting Software

When you buy a computer, it most likely comes with... Read More

Microsoft Great Plains Customization Recovery & Upgrade for Large Corporation

At the end of XX century, in the late 1990th... Read More

Recovering Microsoft Great Plains Customization ? Tips for IT Director

Remember nice and prosperous Clinton era? When you implemented innovative... Read More

What is a Document Manager without Version History?

Document Manager and Version HistoryIn previous articles I have discussed... Read More

25 Things Mapping Software Can Do For You

1. With mapping software you can create a report that... Read More

eco-friendly cleaning service Buffalo Grove ..