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

shuttle to Midway Beardstown .. Lockport Chicago limo O’Hare
In The News:

The FBI has issued a warning that scammers are impersonating doctors, police and banks using spoofed numbers as "smishing" texts surge nationwide.
Communities with unreliable internet service stand to gain after Amazon's Project Kuiper launched its first full batch of satellites into orbit April 28.
Tech expert Kurt “CyberGuy" Knutsson says unsubscribing from spam might actually backfire. Learn when to avoid it and stop junk effectively.
Tech expert Kurt “CyberGuy" Knutsson talks about how the first nonstop beating heart transplant, called zero ischemic time, at Taiwan hospital changes surgery.
Kurt “CyberGuy" Knutsson: FBI warns of "time-traveling" hackers.
Kurt “CyberGuy" Knutsson talks about a soft, vine-like robot called SPROUT that aids safe survivor rescues in collapsed buildings.
Health insurance giant Blue Shield of California confirmed it had been sharing private health data of 4.7 million users with Google for three years without even realizing it.
Delta and JetZero’s blended wing body aircraft marks a meaningful step toward a cleaner, quieter and more efficient future for air travel.
Recent reports show many common passwords can be cracked in literally seconds. Kurt the CyberGuy explains how to strengthen your passwords.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Iron, a robot that stands 5 feet, 8 inches tall and weighs 154 pounds, combines advanced artificial intelligence with human-like movement and exceptional vision.
Hertz, the rental car giant, recently confirmed that customer information was exposed through a cyberattack on one of its software vendors.
There are a number of features with AirPods you may or may not know about to take your listening experience to the next level. Kurt the CyberGuy explains.
These 35 Chrome extensions have privacy and security concerns. Tech expert Kurt “CyberGuy" Knutsson says to delete them now.
Tech expert Kurt “CyberGuy" Knutsson says 329,000 mph fusion rocket promises to be fast, disruptive and enable deep-space missions.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Tech expert Kurt “CyberGuy" Knutsson says a new autonomous AI is a game changer that also raises privacy risks. Is your data safe?
Tech expert Kurt “CyberGuy" Knutsson says robots and drones are revolutionizing fruit farming with faster picking and smarter handling.
Landmark Admin revises May 2024 cyberattack scope to show twice as many people were affected. Kurt “CyberGuy" Knutsson gives tips to help stay safe from an insurance data breach.
Tech expert Kurt “CyberGuy" Knutsson talks about how Yamaha’s hydrogen outboard motor could revolutionize boating with zero emissions.
Tech expert Kurt “CyberGuy" Knutsson reveals how to memorialize or remove a deceased loved one’s Facebook account and protect their digital legacy from misuse or scams.
Tech expert Kurt “CyberGuy" Knutsson says an Apple Watch saved psychiatrist Amanda Faulkner by detecting deadly leukemia early.
Scammers and fraudsters are increasingly targeting the most vulnerable, especially nursing homes and the personal data of their residents. Kurt the CyberGuy has safety tips.
Infected USB flash drives can spread malware among multiple organizations in ways that can easily bypass traditional security systems.
With a fully automated warehouse system and AI-powered robots, Ocado's Hive picks, packs and delivers grocery store orders in just a few minutes.

How To Identify, Cure and Prevent Spyware/Adware Infections

Just when you thought you were Web savvy, one more... Read More

Protect Your Computer...and Your Business!

We all take the computer for granted. I mean, all... Read More

Hubris - Definition: Microsofts Passport

Before September of 1995, Microsoft ignored the Internet because their... Read More

Perfectly New Database Query Tool - Foxy SQL Pro Released

Are you a database professional? Do you work with a... Read More

HelpDesk & Asset Management Software - Choosing The Right One

If you are to buy a HelpDesk & Asset Management... Read More

Configure Windows Indexing Service for Performance

The Windows Indexing Service provides you with the ability to... Read More

Microsoft CRM in Latin America: Implementation, Customization, Support ? Overview for Consultant

Microsoft Business Solutions CRM is present several years on the... Read More

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

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

Microsoft Great Plains Implementation ? Overview for IT Director/Controller

What is installation in the language of technology? Installation... Read More

Groupware Finds Home in American Business: Collaboration Tool Analysis

What is Groupware?Have you ever had to manage document collaboration... Read More

What You Must Know About Spyware Right Now

Spyware is like the new technological nuclear weapon on the... Read More

Microsoft Great Plains: Dexterity vs. eConnect ? FAQ

Microsoft Business Solutions Great Plains, former Great Plains Software Dynamics/eEnterprise... Read More

Computer Based Language Development and Spell-checking

Language development computer: Computer-based method for aiding language development seems... Read More

Getting Patched with Windows Service Pack

Are you one of those people that keeps track of... Read More

Antivirus Software ? Get The Bugs Before They Get You!

You turn on your computer, and it doesn't look quite... Read More

Algebra Help Software

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

Brief Notes About Mainframe Software Pricing

We don't think about mainframe software pricing anymore, we just... Read More

How to Choose the Right Accounting Software for Your Business

With any good luck and a good amount of hard... Read More

Unofficial Windows 98 SE Service Pack 2.0 RC2

Microsoft has never released a service pack for Windows98 SE,... Read More

Microsoft CRM Data Conversion FAQ

Microsoft Business Solutions CRM data conversion deserves FAQ type of... Read More

Microsoft CRM or Siebel

Siebel is traditional CRM market leader, however and mostly due... Read More

Make or Break Factors - When Considering Estimating Software

Make-or-Break Factors in Success and ProfitabilityFor quick printers, estimating can... Read More

Microsoft CRM Customization

Microsoft CRM customization techniques are very diversified and based on... Read More

Linux Secrets

The first thing that you will notice about Linux Red... Read More

Seven Reasons Why a Hosted Inventory Management Solution Might Be Right For Your Organization

Upgrading. Downtime. Maintenance. Hardware obsolescence. Implementation issues. The litany of... Read More

Green Bay Hummer H2 SUV rentals ..