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 Bannockburn ..
In The News:

Apple's iOS 26.1 update delivers major security fixes, performance boosts and enhanced privacy controls for your iPhone. Discover why updating now protects your data.
Russian hackers use fake CAPTCHA tests to spread dangerous malware targeting governments and journalists. Learn how to protect yourself from these deceptive attacks.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Miami-Dade debuts America's first autonomous police SUV with AI cameras, drone deployment and real-time crime detection in groundbreaking law enforcement pilot.
Bank impostor scams cost Americans $2.9 billion as criminals use AI voices and caller ID spoofing to steal life savings. Learn nine essential fraud protection tips.
Foreign-owned apps secretly harvest personal data from seniors, making them prime targets for scams. Learn how to protect your privacy and stop data brokers today.
Sens. Josh Hawley and Richard Blumenthal introduce bipartisan GUARD Act to protect minors from AI chatbots through mandatory age verification and disclosure requirements.
Ghost-tapping scammers exploit wireless technology to drain accounts through small transactions, but RFID-blocking wallets and transaction alerts can protect you.
French pilot project demonstrates wireless charging roads that can deliver over 300 kilowatts of power to EVs while driving, potentially eliminating range anxiety.
YouTube's Ghost Network spreads information-stealing malware through thousands of fake videos offering cracked software, using compromised accounts and fake engagement.
Protect your privacy by disabling your smart TV microphone. Most TVs have hidden mics that listen even when voice commands are off. Learn quick steps to stop unwanted audio capture.
SessionReaper vulnerability hits Magento and Adobe Commerce stores, compromising 250+ sites in one day. Hackers steal data and hijack shopping sessions.
Master essential parental controls and digital safety tools to protect your kids online. Learn screen time limits, location settings and privacy controls every parent needs.
Cybersecurity expert shares six essential steps to protect against dark web threats, including data removal services, password managers and antivirus software.
NVIDIA GPU space mission could revolutionize cloud services by enabling orbital data centers that make apps, games and AI tools faster and more efficient.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Microsoft warns Windows 10 users face serious security risks as 90% of ransomware attacks target unsupported systems. Learn why upgrading to Windows 11 is crucial.
Nike unveils Project Amplify, revolutionary motorized shoes developed with Dephy that add powered assistance to every step for runners and walkers.
Cybersecurity experts warn about one of the largest credential compilations ever found, urging users to check "Have I Been Pwned" and change passwords immediately.
Quick iPhone and Android battery optimization techniques help your device stay powered all day by turning off hidden features that secretly drain power in the background.
Kodiak Driver autonomous truck achieves perfect 98 safety score, matching top human fleets in groundbreaking AI evaluation by Nauto's VERA system.
New 401k catch-up contribution rules in 2026 will change taxes for high earners over 50. Learn how scammers exploit these changes and protect your retirement savings.
Kurt Knutsson's guide covers social media privacy protection through location settings, account privacy controls and two-factor authentication to prevent scams and data breaches.
Revolutionary retinal implant restores central vision in 80% of patients with advanced macular degeneration, offering hope where treatments once only slowed blindness.
Learn how to use passkeys on Windows and Mac computers without cameras or fingerprint readers. Discover secure authentication methods that replace passwords.

Microsoft Great Plains Integration Manager ? Advanced Techniques

Great Plains Integration Manager scripting and translation - overview for... 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 Great Plains Customization Recovery & Upgrade for Large Corporation

At the end of XX century, in the late 1990th... Read More

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

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

Resume Software ? Advantages Revealed

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

Running a Program on a Remote Server Using SSH

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

It?s Back!! WordPerfect?s Amazing Comeback

Have you noticed WordPerfect is gearing up for a comeback... Read More

Professional XP Style Icons in Software and Website Development

Using professional icons in your application or website can bring... Read More

About Microsoft Sysprep (System Preparation) Utility (Windows 2000)

The Microsoft system preparation utility for Windows 2000 is a... Read More

Corporate ERP: Microsoft Great Plains For The Plant In Brazil ? Overview For CIO

Microsoft Business Solutions Great Plains as new ERP for multinational... Read More

What is Groupware?

Vince Lombardi once said that, "The achievements of an organization... Read More

RFID: Strengthen the Position for SAP; United States

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

Collaboration Software: Index of Collaboration Software Technologies

Collaboration SoftwareCollaboration Software, also known as group collaboration software or... Read More

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

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

Is Software Tester a Most Infamous Person in a Software Project Team?

The fact that a software tester is a most infamous... Read More

Getting Patched with Windows Service Pack

Are you one of those people that keeps track of... Read More

Three Steps To Windows Safety Heaven

Now there are Three Steps To Heaven Just listen and... Read More

Your Computer May Be Infected, Heres How To Check (NOT about virus)

NOTE: Please take time to read on - it may... Read More

Downloading Spyware Removers: Think Before, not After

Just imagine: you are walking, say, towards your car, and... Read More

Business Plan Software Review: Ultimate Business Planner?

One of the main reasons business owners and entrepreneurs use... Read More

Microsoft Great Plains Logistics & Warehouse Management ? Implementation & Customization Highlights

Logistics automation is often considered as barcoding extension to Sales... Read More

OEComplete ? A Personal Information Manager

OEComplete is a utility for managing the personal information of... Read More

What You Should Know About Installing Screensavers

Do you remember that frustrating feeling when you find an... Read More

Dig Out That Worm

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

Putting Screensavers Under Control

No matter how much you enjoy your favorite screensavers, sometimes... Read More

luxury cleaning services Lake Forest ..