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

custom home cleaning Lincolnshire ..
In The News:

Amazon Prime Day shoppers face threats from 120,000-plus scam websites as cybercriminals prepare phishing traps and malware ahead of the July sales event.
Fox News' AI Newsletter brings you the latest on this rapidly evolving technology.
The AEON humanoid robot tackles labor challenges with Nvidia AI, Microsoft Azure cloud and advanced spatial awareness, working alongside industry leaders Schaeffler and Pilatus.
Google's Ask Photos feature brings AI-powered searches to your photo library, letting you find memories with natural language queries while maintaining privacy controls.
The return of blue book exams emerges as universities fight widespread AI academic dishonesty and educators debate whether to ban AI tools or teach responsible usage.
Signs your phone might be hacked include strange behavior, unauthorized texts, battery drain and pop-ups, while protection involves updating software and avoiding public Wi-Fi.
Tokyo startup H2L has launched Capsule Interface technology enabling full-body robot control with muscle sensors, offering immersive remote operation.
The A.I. industry seems set for growing pains as Big Tech companies scramble for solutions to the medium's unprecedented strain on the power grid.
Fourth of July fireworks cause a 60% spike in lost pets, but GPS trackers and AI photo-matching services like Love Lost can help reunite missing dogs with their families.
Protect yourself from jugging, the rising crime by which thieves monitor ATM users and follow them to steal cash, with six practical safety tips to stay alert and secure.
U.S. airlines like Delta, American and United are selling your domestic flight records to government agencies through the little-known Travel Intelligence Program.
Autonomous robots from Uber Eats are rolling out across U.S. cities, featuring LIDAR sensors, secure compartments and all-weather operation for food and grocery delivery.
Costco has expanded into EV infrastructure with new ultra-fast charging stations that can charge most electric vehicles to 80% in 20-60 minutes while shoppers browse the warehouse.
The new Gemini Robotics On-Device AI allows robots to perform complex tasks without internet, offering enhanced privacy, reliability and adaptability for real-world use.
Protect yourself from Amazon phishing scams by spotting red flags like suspicious sender addresses and spelling errors while using Amazon's Message Center to verify communications.
GAC Group's new Govy AirCab flying car combines lightweight design with advanced safety systems and smart cabin technology to revolutionize city travel with an 18.6-mile range.
The Berkeley Humanoid Light (BHL) is a lightweight, open source humanoid robot that anyone can build using 3D-printed parts and off-the-shelf components.
Meta’s new AI chatbot is getting personal, and it might be sharing more than you realize.
A new threat targets both Android and iPhone users: SparkKitty, a powerful mobile malware strain that scans private photos to steal cryptocurrency recovery phrases and other sensitive data.
Thanks to a team at the University of California, Davis, there's a new brain-computer interface (BCI) system that's opening up real-time, natural conversation for people who can't speak.
Privacy risks are hiding in plain sight, as your personal data is likely being collected, tracked, and sold without your knowledge.
VenHub, a fully autonomous, AI-powered smart store just opened at the LAX/Metro Transit Center in Los Angeles.
A woman's Facebook account takeover reveals dangerous social engineering tactics and provides lessons on recovery, avoiding scams and enacting stronger security measures.
Shanghai engineers are using 432 walking robots to relocate a complex, preserving Shikumen architecture while creating space for a modern underground hub and cultural center.
Major healthcare data analytics firm Episource had a cybersecurity incident exposing 5 million patients' medical records and personal information in recent breach.

The XP Firewall Isnt Enough

You might think you don't need a firewall... Read More

Microsoft Great Plains eCommerce: overview for developer

Microsoft Business Solutions Great Plains was designed back in the... Read More

Recovering Microsoft Great Plains Customization ? Tips for IT Director

Remember nice and prosperous Clinton era? When you implemented innovative... Read More

Screenplay and Script Writing Software

When it comes to screenplay software each screenwriter needs to... Read More

Free Software for Newbies and Web Developers

Here is some free software tools to help you build... Read More

Dashboard Widgets for Windows

For a windows user like me, just can watch with... Read More

Online PowerPoint Presentation ? Convert PowerPoint to Flash

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

Microsoft Great Plains Beverage Production & Distribution ? Implementation & Customization Highlight

Microsoft Business Solutions Great Plains has many years of successful... Read More

Removing Incoming Email in MS Exchange, C# Example

The purpose of one of our projects was MS Exchange... Read More

Implementing ERP for Large Publicly Traded Corporation ? Microsoft Great Plains

We would like first emphasize the change in the paradigm.... Read More

Microsoft Great Plains Data Conversion ? Overview For Developer

Looks like Microsoft Great Plains becomes more and more popular,... Read More

MCP Market News: Microsoft SQL Server & SQL Reporting Services

Are you ready? SQL Server 2005, the next-generation data management... Read More

FreeDOS

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

Microsoft Great Plains customization ? Freight Forwarding/Transportation industry example

Microsoft Business Solutions Great Plains version 8.5, 8.0, 7.5, Great... Read More

How to Backup Windows XP Home Edition

Your computer cost you from hundreds to thousands of dollars,... Read More

Backing Up And Restoring Your MySQL Database

If you've been using MySQL database to store your important... 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

Microsoft CRM Customization

Microsoft CRM customization techniques are very diversified and based on... Read More

How to Choose the BEST Charting Software

I suggest that you do not spend a lot of... Read More

Microsoft CRM Integration with Lotus Notes Domino: Messaging Connector ? Future Directions

IBM Lotus Notes Domino and Microsoft CRM (Client Relation Management)... Read More

Microsoft CRM Data Conversion FAQ

Microsoft Business Solutions CRM data conversion deserves FAQ type of... Read More

Introduction To ISDN, Part II

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

Microsoft Great Plains Food Processing ? Implementation & Customization Highlights

Microsoft Great Plains might be considered as ERP platform to... Read More

ERP Consulting: Microsoft Great Plains Partner Future Directions

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

Reloading Windows XP

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

move in cleaning service Glencoe ..