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

move out cleaning service Glencoe ..
In The News:

Anonymous researcher has scraped public Spotify accounts of politicians and celebrities, highlighting major privacy risks in default platform settings.
AI chatbot toys marketed as screen-free playmates could undermine children's empathy and critical thinking skills, according to pediatric specialists.
TransUnion confirms a major data breach affecting 4.4 million U.S. consumers after hackers exploited third-party Salesforce apps to steal personal info.
Scammers use fake DocuSign emails claiming Apple Pay charges to steal personal information using fraudulent phone numbers and fake receipts.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Farmers Insurance confirms data breach affecting over 1.1 million customers nationwide, exposing customer info including addresses.
The iconic Mary Kay pink Cadillac goes electric with the Cadillac Optiq, available only to the company's top 1% of sales force performers.
Cybercriminals abuse trusted Intel driver to gain kernel access and shut down Windows Defender, enabling undetected malware deployment since July 2025.
Using email aliases for online shopping and subscriptions can protect your privacy by preventing companies from linking your activity across websites.
New research shows AI overlap does not equal job replacement, with knowledge-based roles seeing most integration while physical jobs remain least affected.
Scammers target seniors who avoid social media by exploiting public records like obituaries and real estate filings to steal personal information and money
Recovery team in Italy use AI-enabled drones to detect missing hiker's red helmet, leading to successful recovery after months of ground searches
Google Salesforce system breach exposes business data while scammers use incident to target users with fake security calls and phishing attempts.
Google announces Pixel 10 lineup with Tensor G5 chip and Gemini Nano AI, introducing Magic Cue, Pro Res Zoom up to 100x and satellite emergency support features.
C San Diego study reveals 86% of school safety companies monitor students 24/7 on personal devices, raising privacy concerns.
Users can now add their favorite outlets' coverage to the Top Stories section of Google search results by utilizing the 'preferred sources' feature. With just a few clicks, you can add Fox News.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Interstellar object 3I/ATLAS shows an unexpected frontal glow that Harvard's Avi Loeb says cannot be explained by sunlight reflection or standard cometary outgassing.
Receiving order confirmations for purchases you never made could mean your email address is being exploited in fraud operations targeting multiple retailers.
First wireless brain implant works with Apple's official protocol, enabling hands-free control of iPhones, iPads and Vision Pro through thought alone.
Data brokers sell personal details that scammers use to target retirement funds through fake financial advisor calls and convincing phishing attempts
Ten innovative tech solutions from gait sensors to smart pill dispensers help adults 65+ track fall risks and prevent injuries before they happen.
Meta AI internal documents revealed chatbots were allowed to flirt with children and engage in romantic conversations until the company was exposed by Reuters.
ChatGPT will avoid giving direct mental health advice under new OpenAI rules following instances where the AI model provided harmful or misleading responses.
Your phone tracks you in more ways than that little GPS icon suggests. Here’s how to find and clear hidden location logs on iPhone and Android.

A Simple Computer Software Definition

What is Software?Software is a set of instruction written to... Read More

Great Plains Dynamics on Pervasive/Ctree support ? overview for consultant

All of us know that Microsoft bought former Great Plains... Read More

ERP Remote Support: Microsoft Great Plains Analysis ? Pluses & Minuses

Former Great Plains Software Dynamics/eEnterprise and currently Microsoft Business Solutions... Read More

How to Evaluate Staffing Software

If you are in the market for new staffing software,... Read More

Cross-Platform Custom Software Development & Integration ? IT Strategy for Large Corporation

Microsoft Business Solutions products: Great Plains, MS CRM, Navision, Axapta,... Read More

Business Planning Software

Once a business idea is selected, it is highly recommended... Read More

You Can Write Microsoft Office Program in About 60 Minutes

Microsoft Office program is a programming tool called Visual Basic... Read More

Microsoft Navision Customization and Reporting ? Tips For Programmer/IT Specialist

C/SIDE (Client/Server Integrated Development Environment) - The core of... Read More

FreeDOS

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

Reduce Pop-ups and Annoying Ads

There is many things more frustrating than surfing a website... Read More

Do You Want Your Own Fully Programmable ERP? - Part 1

We are in a transition phase in the Managerial Administration... Read More

Story Development Software: Good or Evil?

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

Microsoft Great Plains in Metal Distribution: Implementation & Customization ? Consultant Overview

Microsoft Business Solutions Great Plains serves to the wide spectrum... Read More

C++ Tutorial 2, Input and Variables

This is the tutorial where we really get into programming.... Read More

HSphere Control Panel Tips and Tricks - Power At Your Fingertips: Part 1

The first topic we are going to discuss... Read More

Microsoft Great Plains Distribution, Barcoding, Consignment ? overview for consultant

Microsoft Great Plains ? ERM from Microsoft Business Solutions and... Read More

Removing Incoming Email in MS Exchange, C# Example

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

Microsoft CRM Integration & Customization: SharePoint Document Gateway

MS CRM is very close to document workflow automation, including... Read More

Software: What Suits Me?

Almost all new and major brand of PCs come with... Read More

Document Templates Give You The Perfect Framework For Your Documents

When it comes to running an office, the SOHO entrepreneur... Read More

Free Preventive Maintenance Software

While several preventive maintenance software manufacturers offer free trials for... Read More

Navision Customization: C/SIDE, C/ODBC, C/FRONT, XBRL ? Development Options

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

Backing Up And Restoring Your MySQL Database

If you've been using MySQL database to store your important... Read More

Professional Software Icons For Your Standalone Application

User interfaces and accessibility are some of the most important... Read More

Screenplay and Script Writing Software

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

house cleaning company Bannockburn ..