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

trusted cleaning company Mundelein ...
In The News:

The OlloNi SS1 AI robot pet uses a 4K camera and facial recognition to learn your family, but its removable Red Heart memory module raises questions.
Nine identity theft warning signs range from unfamiliar credit inquiries to SIM swap attacks that can quietly drain your bank account funds.
Robot.com's R-dog uses articulated legs and wheels to climb stairs and deliver packages, while its built-in screens display paid ads along the route.
MyChart phishing emails mimic real patient portal alerts with fake lab results and malware tricks that target Windows users across the country.
The Fox News AI Newsletter covers the latest artificial intelligence technology advancements, including the challenges and opportunities AI presents now and for the future.
Google's Motion Assist places animated dots on Pixel screens to combat motion sickness in vehicles, but the Android 17 rollout remains limited.
Moving to a 55+ community can quickly expose your data to scammers and data brokers before you even unpack, putting your whole family at risk.
Amazon Prime Air drone delivery plans to reach nearly 500 U.S. cities by the end of 2026, but your yard and ZIP code may determine eligibility.
The FBI reports nearly $21 billion in cybercrime losses for 2025, up 26%, as AI scams make fake voices and identities more convincing than ever.
Uber teen accounts now feature live video streaming from the driver's camera, but encrypted recordings stay on Uber's servers for up to 14 days.
Router firewalls and software firewalls serve different roles in protecting your home Wi-Fi from unwanted traffic and suspicious connections.
A Chrome extension with 70,000 users and a 4.7-star rating began injecting fake update warnings after a threat actor acquired and weaponized it.
Amazon's Alexa+ rolls out free to Fire TV devices across the U.S., but hands-free microphones and stored voice data raise key privacy questions.
Meta's new teen accounts settlement sets a default two-hour daily limit on Instagram and Facebook, plus night mode and school mode restrictions.
The CareCloud data breach exposed Social Security numbers, banking information and medical records belonging to more than 3.75 million people.
Waymo reveals its custom 5-nanometer chip and dual computing systems designed to take over instantly if the robotaxi's primary computer fails.
Identity theft now includes account takeover, phone hijacking and payment card exposure. Here's what to look for in identity theft protection services.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The FBI and Justice Department seized domains tied to QScan and QTRouter, tools allegedly used by China-linked hackers to breach NASA and other agencies.
Uber Eats drone delivery launches later this year through a Zipline partnership, starting in Dallas and Houston with a goal of one million daily flights.
Medicare Open Enrollment scams start with data broker targeting months before October. Learn why August is the time to remove your personal info.
The World Humanoid Robot Games' crashes show how far the technology still needs to go to be useful, "Survivor" reality TV star and robotics scientist Christian Hubicki says.
X-Humanoid's TianGong Ultra ran 100 meters in 9.32 seconds at Beijing's World Humanoid Robot Games, beating last year's winner by more than half.
A tap-to-pay charity scam is turning small $15 or $20 donations into charges of nearly $5,000, with victims losing thousands before they notice.
Kurt Knutsson shares seven emergency preparedness lessons from surviving Hurricane Katrina inside a New Orleans hotel as conditions turned desperate.

Corporate ERP: Standard vs. Rich functionality ? Microsoft Great Plains

Traditionally we were considering functionally rich systems, such as SAP,... Read More

Four Easy Ways To Prevent Spyware

How would you like to prevent spyware and adware from... Read More

Microsoft Great Plains Integration Manager: Using Continuum ? Overview for Developer

Microsoft Business Solutions Great Plains has I'd say end user... Read More

Know-how in Microsoft Publisher

For those who still don't know, Microsoft Publisher helps computer... Read More

String in Java

Handling character strings in Java is supported through two final... Read More

RFID: Strengthen the Position for SAP; United States

SAP Inc., a global leader in client/server enterprise application software... Read More

eConnect: eCommerce Development for Microsoft Great Plains

Microsoft Business Solutions Great Plains has several options to enable... Read More

Great Plains Sales Order Processing and Invoicing Modules ? Tips For Consultants

We'll give you non formal view, based on our consulting... Read More

Lotus Domino Implementation and Development: Infrastructure ? Present and Future

Domino server is a buffer between the operation system and... Read More

Free Program Removes Spyware not Detected by Premium Security Scan

What is Spyware?Spyware monitors your surfing habits and sends the... Read More

Microsoft Great Plains: Annual Enhancement Program ? How To Be Re-Enrolled

Microsoft Business Solutions Great Plains is mid and even corporate... Read More

Microsoft CRM Integration with Microsoft Retail Management System (RMS) ? Overview

Microsoft Client Relation Management system (Microsoft CRM) and Microsoft RMS... Read More

Software Piracy

SOFTWARE PIRACY We regularly hear reports... Read More

Tools for Customizing Great Plains

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

How a Bug Challenges to a Software Professional

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

Story Development Software: Good or Evil?

In the early days of the personal computer, we're talking... Read More

Snort for Network IDS

What is Snort?Snort is an open source network intrusion detection... Read More

Microsoft Great Plains Integration with Legacy Systems ? Overview For Developer

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

Microsoft Great Plains Upgrade ? Version 8.0 Overview for IT Director/Controller

If you have Microsoft Great Plains as main accounting and... Read More

ERP System of the Future: Database, Business Logic and Interface

We will base our prognosis on our Microsoft Business Solutions... Read More

COSMIC: A Small Improvement on the Symons Method

The COSMIC FP (function point) software quality metric, is no... Read More

Information Products: A Business Owners Best Friend

We live in a post-industrial age where information is the... Read More

Microsoft Great Plains eCommerce ? Stored Procedures Approach

Since Version 8.0 Microsoft Business Solutions Great Plains & Great... Read More

Oracle Development: JDeveloper 10G ? Java, J2EE, EJB, MVC, XML - Overview For Programmer

In 2004 Oracle, Inc. made its new step toward J2EE... 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

weekly home cleaning Glenview ...