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

non-toxic cleaning company Winnetka ..
In The News:

Researchers are now showing us that old smartphones as data centers could be the next big thing in sustainable tech.
Scientists have created micro-robots for sinus infection treatment that can enter the nasal cavity, eliminate bacteria directly at the source, and exit without harming surrounding tissue.
Let's examine how your data is collected in everyday life, who is buying and selling it, what happens to it afterward, and, most importantly, what you can do to protect yourself.
Researchers at the University of Sheffield in the U.K. developed small robots called "Pipebots" that can travel inside water pipes to find and potentially repair leaks, all without any excavation.
A groundbreaking new study has uncovered disturbing AI blackmail behavior that many people are unaware of yet.
Four teams of autonomous humanoid robots competed in China's first AI soccer tournament, demonstrating advanced capabilities in ball detection and independent decision-making.
The ID. Buzz autonomous van features self-driving technology with 13 cameras, nine LiDAR units and five radars after Volkswagen partnered with Hamburg and Uber for 2026 deployments.
Social Security phishing scams use urgency and impersonation to steal personal data. Learn how to spot fake SSA emails and implement 10 protective measures.
French startup Pazzi Robotics created an AI-powered pizza robot that made pies in under five minutes without human help, but it closed in 2022 despite patents and expert partnerships.
Reclaim your time from big tech with effective screen time reduction strategies for iPhone and Android, featuring steps to limit app usage and create phone-free zones.
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.

Adware, What Is It?

Adware is a type of Spyware program that displays some... Read More

Microsoft Great Plains Integration Manager ? Working With Text File

Microsoft Business Solutions main middle market ERP application - Microsoft... Read More

Running a Program on a Remote Server Using SSH

How do you run a program on a remote server... Read More

Adware and Spyware Blockers

The most important things you can do for your computer... Read More

Chinese Input - Step by Step Instruction on How to Input Chinese Characters in English Windows XP

Enabling Chinese input is quick and easy, there are only... Read More

Microsoft CRM Implementation & Remote Support

We would like to give you pluses and minuses of... Read More

How To Choose A Fire Wall Software Program

In the real world a "fire wall" is a fireproof... Read More

Does your Company have Documentum?

Are you lost in the mess of documents that get... Read More

CRM and Customer Life Cycle

Customer Relationship Management or CRM is a combination of enterprise... Read More

Constructionalist Parsing - Deciphering Natural Language

The research in the field of Natural Language Processing usually... 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

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

Microsoft Great Plains Partner Selection: Overview

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

How to Get The Best Accounting Software For Your Small Business

Buying accounting software is a major investment. It's an important... Read More

Navision Attain C/ODBC Crystal Report ? Customization Example

Microsoft Business Solutions Navision is main ERP application for European,... Read More

SQL scripts for Project Accounting: Microsoft Great Plains series ? overview for developer

Microsoft Business Solutions Great Plains has Project Accounting module where... 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

Microsoft CRM Data Conversion FAQ

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

Tools for Customizing Great Plains

Microsoft Business Solutions ? Great Plains has captured the US... Read More

Dig Out That Worm

Internet worms. Is your PC infected?If your computer has become... Read More

Increase Office Efficiency With One Simple Tool

When you need a phone number, you do a quick... Read More

Resume Software ? Advantages Revealed

The various resume software offered, particularly on the internet, can... Read More

Microsoft Great Plains Integration Manager ? Advanced Techniques

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

Microsoft Business Solutions - Navision Customization: C/SIDE, C/ODBC, C/FRONT, XBRL

Microsoft bought Navision, Denmark based software development company, along with... Read More

Microsoft Great Plains Integrations ? Retail Management Sample

Microsoft Business Solutions is emerging as very attractive vendor for... Read More

experienced cleaning professionals Glencoe ..