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

bmw rental chicago Bath .. Lockport Chicago limo O’Hare
In The News:

Spambots, data thieves, and other bad actors run rampant online — more so now than ever before. Here's what to do if one gets ahold of you.
Tech expert Kurt “CyberGuy" Knutsson says the Super Bowl's huge audience makes it a prime target for many types of cybersecurity scams.
It's not just about freeing up space on your computer, Kurt “CyberGuy" Knutsson says. It's about protecting your digital memories and important documents.
From proofreading and research to brainstorming and data analysis, you can use generative AI as a sidekick for just about any task you can dream of.
Tech expert Kurt “CyberGuy" Knutsson says Super Bowl 2025 ads promise star power and laughs, featuring Beckham's twin reveal.
First driverless semi delivers 100 loads in Texas, transforming logistics with AI. Tech expert Kurt “CyberGuy" Knutsson gives his takeaways.
A new scam using Elon Musk's name is making the rounds, promoting "energy-saving" devices and falsely linking the Tesla and SpaceX leader to the products.
China recently unveiled a new bullet train prototype with a test speed of 280 mph that is poised to break records and set new standards.
Hackers sometimes find ways to exploit iPhones, and Apple recently discovered a vulnerability in iOS that may have been exploited for over a year.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Lynx the robot dog from China is pushing boundaries of what autonomous mobile robots can achieve with a groundbreaking design and unique mobility.
A startup claims to have developed the world's first entirely artificial intelligence-designed and 3D-printed shoe, the brainchild of a 25-year-old.
Creating an email alias can help clean up your inbox by organizing emails based on purpose, like creating different aliases for shopping, newsletters and work.
A multipurpose robotic system promises to transform how items are stacked onto pallets, aiming to maximize space utilization and reduce shipping costs.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The number of people affected by a UnitedHealth data breach in February 2024 was actually higher than previously reported and was the largest medical data breach in U.S. history.
A phishing campaign uses Google Calendar to schedule fake meeting invitations that appear legitimate, redirecting targets to phishing sites.
Toll road text scam: Fake messages claim unpaid fees, seek payment via fraudulent links. Kurt “CyberGuy" Knutsson says this scam is becoming increasingly sophisticated and widespread.
Kurt “CyberGuy" Knutsson says these steps ensure that your friends and family get to the exact moment you want them to see. Try it out and streamline your sharing experience.
Tech expert Kurt “CyberGuy" Knutsson offers tips on how to protect your identity: Be vigilant, monitor accounts, use smart security, know theft response.
Tech expert Kurt “CyberGuy" Knutsson says cybercriminals are exploiting iMessage phishing protection, tricking users to reactivate links.
It's hard to imagine life without in-flight Wi-Fi these days – but sky-high web surfing comes with its own set of privacy concerns. Here's how to protect yourself.
Over 400,000 cases of credit card fraud were reported in 2024 to the Federal Trade Commission. The CyberGuy explains how to protect against becoming another victim.
A nondescript metal box transforms into a fully functional electric motorcycle that blurs the line between vehicle and urban infrastructure.
Many apps unrelated to location still ask users for tracking permission, and Texas Attorney General Ken Paxton has filed a lawsuit seeking to end this alleged practice by Allstate.

Exactly What Does FTP Stand for and What Can it do for Me?

FTP stands for "file transfer protocol". FTP is basically a... Read More

netstat - Linux Command to Display Networking Information

In linux, one of great commands for finding out information... Read More

Database Guru James F. Koopmann Reviews DBxtra Reporting and Query Tool

DBxtra is a powerful query and reporting tool that hides... Read More

Brief Notes About Mainframe Software Pricing

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

Artificial Intelligence And Intuition

The intuitive algorithm.Roger Penrose considered it impossible. Thinking could never... Read More

Reloading Windows XP

If you have been running Windows XP for a couple... Read More

Huddle Up; Groupware on Three

It could just be me, but my experiences with document... Read More

Microsoft Great Plains on Ctree or Pervasive SQL ? What to Do ? Tips for IT Manager

As you probably know, when Microsoft purchased Great Plains Software... Read More

Fundraising Software ? How Can That Help Me?

Fundraising software lets you connect with donors in a way... Read More

Microsoft CRM Customization Secrets ? Second Edition

This article is for advanced Microsoft CRM SDK C# developers.... Read More

How To Create A Data Capture Procedure Checklist For Your Small Business CRM Software

Fortunately one of the most common reasons cited for the... Read More

Interactive Mapping Brings Information to Life

What is Interactive Mapping?Interactive mapping is a visual display medium... Read More

Introduction To ISDN, Part II

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

Will Adobe Manage to Replace Industry Work Horse Quark Express by Giving Adobe InDesign for Free?

And kill the best layout software in the process of... Read More

Microsoft Great Plains POP: Purchase Order Processing ? Overview For Consultants

Great Plains Purchase Order Processing (POP) module makes up one-third... Read More

Reduce TCO: The Java Database Way

TCO (Total Cost Ownership) is the buzzword in... Read More

40/sec to 500/sec

IntroductionSurprised, by the title? well, this is a tour of... Read More

Spyware, What is it?

Spyware, what it is and what it does. Basically, spyware... Read More

SpyBot - Search and Destroy versus Microsoft AntiSpyware (Beta).... My personal experiences...

Ok... Where to start?Well, I guess I will start at... Read More

Downloading Spyware Removers: Think Before, not After

Just imagine: you are walking, say, towards your car, and... Read More

Internet Faxing Service Review

The Internet is reshaping every form of communications medium, and... Read More

Is Software Tester a Most Infamous Person in a Software Project Team?

The fact that a software tester is a most infamous... Read More

Microsoft Great Plains: exchange & brokerage ? implementation notes

If you company is small or mid-size special products or... Read More

Great Plains Accounting Migration to Microsoft Great Plains - Overview for IT Specialist

This is a short article, written in question/answer/FAQ style to... Read More

A Case Study on Selecting Contract Management Software

Professional services firm cuts costs and improves productivity with integrated... Read More

limousine service Ava ..