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

residential cleaning services Lincolnshire ..
In The News:

Friendly text conversations about BBQs and social events can lead to WEEX gold trading scams that target older adults with fake investment opportunities.
California company Skyeports creates self-healing glass spheres from Moon regolith that generate solar power and support plant growth for sustainable lunar living.
Cleafy researchers discover fake VPN streaming app Mobdro Pro that installs Klopatra banking Trojan, giving attackers full control over Android devices.
Police departments across the U.S. and Canada are adopting virtual reality training to better prepare officers for high-pressure, real-world situations.
House Bill 469 would prevent AI systems from owning property, serving as executives, or gaining legal personhood in Ohio under Representative Thaddeus Claggett's proposal.
Public voter records expose retirees' personal details to election scammers who create targeted cons using names, addresses, and voting history data.
Instead of fearing what comes next with artificial intelligence, think outside the box. Here are high-earning AI jobs that don't require a computer science degree.
OpenAI CEO Sam Altman says polite words like "please" and "thank you" cost millions annually, while direct prompts may improve ChatGPT accuracy by several points.
Chattee Chat and GiMe Chat exposed intimate conversations and photos, revealing users spent up to $18,000 on AI companions before the breach.
New Instagram parental controls allow families to manage teen screen time and content limits through the Family Center with stricter safety settings.
Third-party security breach at Discord exposes sensitive user information including government IDs, highlighting cybersecurity risks from external service providers.
Survey of 1,000 students shows teens using AI for personal relationships while two-thirds of parents remain unaware of their children's AI usage.
Cybersecurity experts warn about a ShadowLeak vulnerability that weaponized ChatGPT's Deep Research agent to steal personal data from Gmail accounts through hidden commands.
Tesla's Full Self-Driving system faces federal investigation following 58 reports of crashes, with six vehicles running red lights before colliding with other cars.
The Fox News AI Newsletter brings you the latest developments on artificial intelligence, with news on OpenAI moving to soon allow erotica for adult users.
Eric Schmidt alerts that hackers can reverse-engineer AI models to bypass safety measures, citing examples like the jailbroken ChatGPT variant called DAN.
Cybercriminals exploit Microsoft Teams through impersonation, malicious links and fake profiles to gather intel and deliver ransomware to personal and work devices.
Google, Dior, Allianz and dozens of other companies lost sensitive customer data in Salesforce-related breaches affecting millions of records across multiple sectors.
Apple launches iOS 26 with new Preview app that combines document editing, PDF annotation and scanning features into one streamlined iPhone experience.
New AI road monitoring system uses sensor-embedded fabric to predict infrastructure problems, potentially reducing maintenance costs and traffic disruptions for cities.
Holiday charity scams target retirees through lookalike organization names, untraceable payment requests, and data broker information to steal donations.
The Federal Trade Commission says criminals are posing as IRS agents, law enforcement officers or other officials, often over the phone or online, to steal thousands of dollars at a time.
AI phishing scams now use voice cloning and deepfake technology to trick victims, but Kurt "CyberGuy" Knutsson reveals warning signs to watch for.
Inversion Space unveils Arc, a reusable reentry vehicle that can deliver up to 500 pounds of cargo from orbit to anywhere on Earth in under an hour.
Red flags like processing fees, urgent countdowns and requests for full Social Security numbers expose fraudulent settlement sites targeting consumers.

Create ASP in Minutes

DBxtra goes ASPGetting to the information hidden within corporate databases... Read More

How to Upgrade Dexterity Customization ? Tips for IT Manager

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

My Experience - Making a Vision into Reality

Disclaimer: All the thoughts expressed are my views only! Your... Read More

MSN Messenger Is A Sweet Way To Communicate

MSN messenger is a pretty cool invention. I mean I'm... Read More

Microsoft Great Plains IV: Inventory Management

Great Plains Inventory Management (IV) module gives your business a... Read More

Microsoft CRM Messaging through Lotus Domino eMail Server - Balanced Solution

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

Bridging the Gap between Paper and Data

The cornerstone of successful automated office systems is the ability... Read More

Microsoft CRM ? Consulting in the Post-Recession Time

New post-recession era has new features, which didn't exist in... Read More

Online PowerPoint Presentation ? Convert PowerPoint to Flash

Although we don't know whether Microsoft ever envisioned such a... Read More

Popular Fleet Maintenance Programs

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

Review on QuarkXpress 6.0

After almost two decades of existence, Quark has become the... Read More

ERP for Large Corporation ? New Selling Strategy

Our opinion is based on our Microsoft Business Solutions Great... Read More

A Guide To Purchasing Professional XP Icons Online And Enhancing Your Applications

Icons are used everywhere; right from software applications, to internet... Read More

Free Program Removes Spyware not Detected by Premium Security Scan

What is Spyware?Spyware monitors your surfing habits and sends the... Read More

Corporate ERP: Microsoft Great Plains For The Plant In Brazil ? Overview For CIO

Microsoft Business Solutions Great Plains as new ERP for multinational... Read More

Best Practices In Choosing Network Monitoring Software

Blue Cross and Blue Shield of Hawaii (HMSA) found itself... Read More

Protect Your Most Vital Business Asset with Security Software

Homeland security, airport security, Internet security ??" these days we???re... Read More

Free Preventive Maintenance Software

While several preventive maintenance software manufacturers offer free trials for... Read More

Your Computer May Be Infected, Heres How To Check (NOT about virus)

NOTE: Please take time to read on - it may... Read More

Open Source Concepts: Dual Licensing Explained

We were recently faced with a decision: either to let... Read More

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

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

Make 2005 the Year You Save Time!

Today's business world is fast-paced. No matter what it is... Read More

Partitioning, Formatting and Reinstalling in Windows 98

Formatting and reinstalling windows 98 is very easy if you... Read More

eStore Advantage ? Extending Microsoft eConnect for MBS Great Plains

eStore Advantage allows front-office applications to communicate with back-office business... Read More

Does your Company have Documentum?

Are you lost in the mess of documents that get... Read More

best cleaning company Highland Park ..