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

bedroom cleaning professionals Lake Forest ...
In The News:

A dedicated VPN IP address may reduce frustrating CAPTCHAs and bank login security checks by giving websites a consistent connection to recognize.
Apple Wallet in iOS 27 lets you create digital passes from physical cards using a photo or screenshot, but not every card in your wallet qualifies.
Anthropic's Claude AI submitted a fabricated eyewitness tip about an unsolved murder to a Philadelphia police website during automated testing.
P7 DarkSword iPhone spyware can steal saved passwords, photos, Apple Notes and cryptocurrency wallet data by checking for commands every 15 seconds.
Cybersecurity experts told Fox News Digital that a cyberattack on French supermarket freezers should warn the U.S. about critical infrastructure gaps.
The Oracle Health breach exposed medical records, Social Security numbers and diagnoses of nearly 20 million patients across multiple states.
The new Tesla Roadster drove upside down and launched into the air at SpaceX's Texas facility, but a 2028 production target remains unconfirmed.
Apple's iOS 27 lets you add keywords to iPhone photos, while Samsung Gallery tags and Google Photos search offer similar organization tools.
A fake Claude AI download scam uses Google ads, and Bing redirects to trick Mac users into pasting a hidden malicious command in their Terminal.
Ahold Delhaize's cybersecurity incident knocked online ordering and digital coupons offline at Stop & Shop, Food Lion, Hannaford and Giant Food stores.
The Fox News AI Newsletter covers the latest artificial intelligence technology advancements, including the challenges and opportunities AI presents now and for the future.
Amazon's About You feature includes personality details from your shopping history, and some shoppers are finding hilariously awkward results.
Identity theft recovery starts with securing bank accounts, freezing credit and enabling two-factor authentication within the first 24 hours.
Apple's $299 HomeView smart display uses facial recognition to personalize screens for up to six household members and show live security camera feeds.
Domonique DuBose spotted red flags when a man on Hinge with 85,000 followers and a blue checkmark claimed to be a San Francisco 49ers player.
Your phone's location data can expose visits to doctors, pharmacies and places of worship. The FTC took action against data brokers selling this data.
Hackers targeted Danfoss refrigerator controls across French supermarkets, forcing chains like Carrefour and Monoprix to discard massive food stocks.
iOS 27 finally lets iPhone Shared Albums store photos and videos at full resolution in iCloud, but new items count toward the owner's storage.
A fake Facebook Marketplace text scam uses your real name as the seller to trick you into replying, and Malwarebytes warns even one response helps.
The Pentagon data breach exposed 2.76 million Social Security numbers and military records, raising long-term identity theft concerns for veterans.
Kodiak AI plans to haul IKEA freight on Texas highways with no one in the cab, raising urgent cybersecurity and safety questions for drivers.
Apple Intelligence in iOS 27 adds Extend and Reframe tools to Photos, letting iPhones generate new background areas beyond your original borders.
Microsoft's X account was hijacked to promote a crypto pump-and-dump scheme, exposing its more than 13 million followers to a scam campaign.
Scammers can combine your name, phone number and address with data breach details to attempt SIM swaps, phishing and even identity theft schemes.
ChatGPT Work, Meta Muse and Gemini Spark can monitor flight prices, sort your email inbox and track important deadlines, but savvy users start small.

Call Alert Notifications - Free Answering Machine Software for PCs

If you're online using a dialup Internet connection, you'll probably... Read More

Software Piracy

SOFTWARE PIRACY We regularly hear reports... Read More

Cisco Certification: Five Things To Do DURING Your CCNA Exam

There are plenty of articles out there about how to... Read More

Introduction To ISDN, Part III: PAP

Introduction To ISDN, Part III: Configuring PPP PAP AuthenticationNow we... Read More

Causes of ERP Failures

ERP is the acronym of Enterprise Resource Planning. Multi-module ERP... Read More

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

Heard about the Quark "killer"?Adobe InDesign CS2. Will it really... Read More

Software Review: Xsitepro Total Site Management Software

It's not very often I get excited about a software... 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 Great Plains Implementation: Verticals - Wholesale Order Entry center ? overview

Microsoft Business Solutions Great Plains has substantial market share and... Read More

Dreamweaver vs FrontPage

There are two major WYSIWYG(What You See Is What You... Read More

What Stands Behind The Software Description?

With thousands of web pages added to the Net every... Read More

Put Some Pizazz in Your Software Arsenal

The software giants don't do everything and don't always produce... Read More

Popular Fleet Maintenance Programs

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

Alien Intruders!

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

ERP Consulting: Microsoft Great Plains Partner Future Directions

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

MSN Messenger Is A Sweet Way To Communicate

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

Great Plains Dexterity History and Programming Overview

As of now - Great Plains Dynamics/eEnterprise is transformed/renamed into... Read More

Microsoft Business Solutions Partner ? How to Launch New IT Consulting Practice

In the new era of internet marketing the problem of... Read More

Manufacturing Outsourcing: Microsoft Great Plains Implementation, Customization & Reporting

Manufacturing in the USA is far away down from mid... Read More

Implementing Microsoft CRM: setup and configuration ? notes for IT specialist

Microsoft Business Solutions CRM is web-based CRM application, deploying all... Read More

History of Java

The java programming language is becoming more and more popular... Read More

Crystal Reports For Microsoft Navision - Overview For Programmer/IT Specialist

Let us give you - developer some hints in the... Read More

Spyware Protection: A Must for Any Home Computer

Now that spyware is the single most dangerous threat to... Read More

Microsoft Great Plains Integration Manager ? Advanced Techniques

Great Plains Integration Manager scripting and translation - overview for... Read More

Why Java RDBMS?

It is a well known fact that Java as a... Read More

insured cleaning company Northbrook ...