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

spotless home service Deerfield ..
In The News:

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.
Comprehensive analysis of Google Maps, Waze and Apple Maps examines usability, routing accuracy, data handling and features across the top navigation platforms.
Expert analysis reveals whether wired Ethernet or wireless Wi-Fi connections are safer for home internet use, plus practical steps to secure your network from attackers.
Australian construction robot Charlotte uses sand, crushed brick and recycled glass to 3D print fireproof, floodproof homes with reduced carbon footprint.
Cybercriminals are using fake invitation emails to trick recipients into downloading malware and stealing personal information and data.
Flying drones could help retailers fight a 93% increase in theft rates as Flock Safety promotes airborne security systems to track suspects and deter crime.
The Fox News Artificial Intelligence Newsletter brings you the latest news on the emerging technology every Saturday, highlighting top stories.
Hacker group Radiant stole data from 8,000 children at Kido nursery chain, demanding ransom and directly contacting parents with intimidation tactics.
As 18 states implement bell-to-bell cell phone bans, creative students use Google Docs, iMessage on MacBooks and Post-It notes to stay connected in class.
A sheriff's captain says deputies often spend hours writing reports between calls, but Axon's AI program, Draft One, helps them save crucial time in the field.
Sora 2, OpenAI's new video-generation app, can create AI-generated videos based on a singular prompt. The results are both mind-blowing and terrifying.
iPhone and Android users can reduce Wi-Fi calling battery drainage through settings adjustments, background app limits and stronger Wi-Fi connections.
Work email scams are becoming harder to detect as criminals use AI and spoofed addresses to trick employees into opening malicious attachments and links.
From her Arizona living room, Christina Chapman ran a covert hub that helped North Korean operatives infiltrate U.S. firms, netting $17 million in stolen salaries.
UC Santa Barbara researchers developed a soft robotic intubation system that achieved 100% success rates for experts and 96% for paramedics with minimal training.
Scammers exploit probate filings to target grieving families with fake fees and debts, Kurt "Cyberguy" Knutsson reports.
Automotive giant Stellantis becomes latest victim of widespread Salesforce breaches affecting companies like Google, Cisco and Adidas this year.
A woman from Washington reunited with her missing Maine Coon cat Louie after 11 days using Love Lost, a free AI-powered pet recovery platform.

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

ERP for Large Corporation ? New Selling Strategy

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

New SQL Delta Version 3.1

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

20 Extra Hours Per Week: What Would You Do?

While I was in college, if you would have asked... Read More

Navision Sales Module & Reporting: Jet Reports, C/ODBC, XBRL, Business Analytics ? highlights

Microsoft bought Navision, Denmark based software development company, along with... 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

Lotus Notes Domino and Web: Application Development ? Tips for Programmers

Beginning with Domino version R4 it has integration with the... Read More

Top Questions to Ask Before Buying a Help Desk & Asset Management Software

#5 All your hardware components like Printers, PCs etc come... Read More

Microsoft Great Plains: Service Business Customization & Integration Example

Microsoft Business Solutions Great Plains might be considered as ERP... Read More

Microsoft Great Plains: Interest Calculation Example ? Stored Procedure for Crystal Report

This is intermediate level SQL scripting article for DB Administrator,... Read More

Spyware Protection: A Must for Any Home Computer

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

Introducing GRML

Creating a new markup language.Introduction.General Reuse Markup Langauge, or GRML,... Read More

Linux for Home Users

Hey Guys! Don't raise your eyebrows or fear by hearing... Read More

A Case Study on Selecting Contract Management Software

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

Managing Stress in the Computer Industry - Five Steps to a Stress-free Life

It would be easy to think, like most people apparently... Read More

Microsoft CRM Implementation - US Market Lessons

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

FreeDOS

Before September 1995, Microsoft Windows was an MS-DOS program. DOS... Read More

Microsoft Great Plains PM: Payables Management

Microsoft Business Solutions Great Plains is marketed for mid-size companies... Read More

Configure Windows Indexing Service for Performance

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

Lotus Notes Domino and Microsoft CRM Integration

Well, even if the combination might look very unusual, we... Read More

Crystal Reports - Geterogeneus databases: SQL Server, Oracle, Unidata, Btrieve ? Tips For Developer

Crystal Reports is the most flexible tool on the market... Read More

Protect Your Most Vital Business Asset with Security Software

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

Integrating Microsoft Great Plains Accounting/ERP: RMS, CRM, eCommerce, Lotus Domino ? overview

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

Microsoft CRM for Corporate Business ? Working Offline

If your company has regional and worldwide operations, you might... Read More

CROOK: A Methodology for the Refinement of Forward-Error Correction

Table of Contents1) Introduction 2) Related Work 3) Framework 4)... Read More

spotless home service Buffalo Grove ..