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

expert residential cleaners Park Ridge ..
In The News:

The Omoway Omo X features a modular design, obstacle detection and emergency braking, and can drive itself to charging stations, signaling the future of smart urban mobility.
PillTrek, a tiny wireless smart capsule created by Caltech, provides real-time gut health data by detecting electrolytes, metabolites, glucose, hormones, pH levels and temperature.
Learn to spot fake bank text messages with five warning signs of Chase phishing scams, including suspicious links and urgent deadlines designed to steal your account information.
Robot coyotes built on motorized cars reaching 20 mph are being deployed at military airfields as an innovative solution to wildlife threats to aircraft safety.
Explore Google Drive's strengths and weaknesses as a backup solution, including its encryption security, privacy concerns and comparison to dedicated backup tools.
As environmental challenges grow, underwater habitats gain momentum with DEEP's Vanguard, supporting short missions and Sentinel designed for 28-day stays at depth.
The new Urban Eyes safety vest features dual cameras, reflective panels and a wireless remote to deter harassers and provide peace of mind for outdoor workouts.
The $200 billion data broker industry tracks your personal details across websites, posing privacy risks that can be mitigated through data removal services.
UCC Holding has teamed up with COBOD to create desert-inspired, 3D-printed schools in Qatar, featuring dune-like wavy walls impossible with conventional construction.
Darkling beetles equipped with microchip backpacks can be guided through disaster areas using electrical signals, offering a biological solution for search and rescue.
Scammers use number porting to take control of outdated landlines still connected to financial accounts, bypassing two-factor authentication to steal funds while avoiding detection.
Twitter co-founder Jack Dorsey developed Bitchat, a privacy-focused messaging app that works offline via Bluetooth without requiring email, phone numbers or personal data.
Google is making a push to ensure its AI, Gemini, is tightly integrated with Android systems by granting it access to core apps like WhatsApp, Messages, and Phone.
A new green energy system is set to change how we capture clean power, and it all starts with the ocean. French startup Seaturns has designed technology that taps into the natural motion of the sea.
Cybersecurity researchers are warning that hackers have started exploiting flaws in chatbots to carry out AI phishing attacks.
Google has just made it easier than ever to regain control of your inbox with Gmail's new Manage Subscriptions tool.
Despite the benefits, residential power saver programs come with several potential drawbacks and concerns that have been raised by both customers and experts.
The Blackdot AI tattoo machine is quiet. It's steady. And according to early users, it hurts a lot less.
Attackers have started to exploit the very signals that users assume will keep them safe when it comes to add-ons to improve productivity or entertainment.
Located on Cerro Pachón in Chile, the world's most powerful digital camera is set to transform how we see the universe.
The innovative DQ Tower stands 28 feet tall with 420 square feet of living space, featuring floor-to-ceiling windows and premium amenities in a prefabricated design.
A new mmWave imaging system allows warehouse robots to scan and create 3D models of objects inside sealed containers, potentially revolutionizing shipping processes.
Family fraud endangers seniors when relatives exploit their trust, but removing personal data online and monitoring identity can prevent financial harm to aging parents.
A study analyzing 500,000 customer service interactions shows chatbots struggle with complex issues while human agents excel at matching customer communication styles.
Aigen's Element robot uses solar power and AI to provide farmers with a sustainable alternative to herbicides, working efficiently in cotton and soy fields.

Internet Faxing Service Review

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

Keep Your Software Simple! A Review of EditPlus

I like my software simple. If it's too complex or... Read More

10 Things You Could be Using Photoshop For, But Probably Arent

Most people don't use Photoshop to its fullest capabilities. Here... Read More

New SQL Delta Version 3.1

COMMAND LINE FUNCTIONA powerful command line script processor has been... Read More

Need of Document Management System (DMS)

Document Management or Enterprise Information Management is perhaps one of... Read More

Are You Waiting for Microsoft Longhorn Operating System

I love new technology. I am still ready to wait... Read More

Understanding XML Server

XML Server can be a Web Server that stores the... Read More

Microsoft Great Plains: Manufacturing or Bill of Materials - Overview for IT Specialist

Microsoft Great Plains is main Microsoft Business Solutions product, targeted... Read More

Microsoft Great Plains Partner Selection: Overview

Microsoft Great Plains, Navision, Solomon and Axapta are Microsoft Business... Read More

Where to Find Free Fleet Maintenance Software

Costs of fleet maintenance software can vary widely. It is... Read More

Configure Windows Indexing Service for Performance

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

You Can Write Microsoft Office Program in About 60 Minutes

Microsoft Office program is a programming tool called Visual Basic... Read More

Unofficial Windows 98 SE Service Pack 2.0 RC2

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

How a Bug Challenges to a Software Professional

It is really interesting that a bug can create problem... Read More

The True Meaning of Freeware

The vast majority of us will have, at some point,... Read More

Examining the Substance of Studio MX

To all web designers out there, this article is for... Read More

.Net Charts and Graphs Interact with Businesses and Customers

Bar charts, bar graphs, and any other chart or graph... Read More

Instant Messaging is a Sweet Way to Communicate

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

Microsoft CRM Implementation - US Market Lessons

Microsoft CRM is CRM answer from Microsoft Business Solutions. If... Read More

Microsoft CRM Customization Secrets ? Second Edition

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

Groupware: Answers the 5 Questions of Document Collaboration

Every organization which creates collaborative documents, whether they are budgets,... Read More

ERP Consulting: Microsoft Great Plains Partner Future Directions

In the Clinton era the status quo was simple: you... Read More

Looking for an Alternative to Microsoft Office? You Should Be!

Now is the time to look at an alternative to... Read More

The Hidden Power of Online Manual

Writing software manuals is boring, isn't it? We often think:... Read More

Who?s Watching What You Type?

If someone entered your home, uninvited and installed numerous cameras... Read More

green cleaning service Park Ridge ..