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

maid service near Mundelein ..
In The News:

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.
Tesla's FSD v14.1.2 update reintroduces Mad Max mode, enabling higher speeds and more frequent lane changes than the standard Hurry profile setting.
A phishing email scam targeting American Express customers shows how cybercriminals use fake urgent messages to steal personal and financial information.
Facebook's new Meta AI feature analyzes your camera roll photos to create polished collages automatically, but requires cloud processing and raises privacy concerns.
A New Jersey teenager filed a major lawsuit against AI/Robotics Venture Strategy 3 Ltd. over ClothOff, an AI tool that created fake nude images from her social media photos.

Microsoft CRM Lotus Notes Domino Connector FAQ

Microsoft Business Solutions CRM and IBM Lotus Notes Domino, being... Read More

Microsoft Great Plains 8.0 Brazilian Version ? Overview For International Consultant

Microsoft Great Plains has substantial mid-market share in the USA... Read More

Assertion in Java

Assertion facility is added in J2SE 1.4. In order to... Read More

Microsoft Great Plains Food Processing ? Implementation & Customization Highlights

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

Software For Your Hard-Drive

All your software is stored on a hard-drive. But how... Read More

Keep Your Software Simple! A Review of EditPlus

I like my software simple. If it's too complex or... Read More

Begun, The Browser Wars Have

As Mozilla Firefox nears 10% market share, with well over... Read More

Getting Patched with Windows Service Pack

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

Microsoft Great Plains: Offshore Customization & Development ? Overview for Consultant

When you visit department stores and see that majority of... Read More

Document Templates Give You The Perfect Framework For Your Documents

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

Separate Anti-Keylogging Protection: Who Needs it Most?

If there still are few unprotected computers left, I haven't... Read More

Navision Attain Database access via C/ODBC in ASP.NET Application

Navision Software was purchased by Microsoft and now it is... Read More

Imagine if Everyone Working In Your Office Was In Synch?

Microsoft-Outlook is a pretty amazing program. So much more than... Read More

Microsoft eCommerce Web-development: Great Plains eConnect .Net ? Highlights for Programmer

In our small article we'll consider Microsoft Business Solutions Great... Read More

Microsoft Great Plains ? Licensing & Product Versions

Current Microsoft Business Solutions Great Plains has more that 10... Read More

Make or Break Factors - When Considering Estimating Software

Make-or-Break Factors in Success and ProfitabilityFor quick printers, estimating can... Read More

Great Plains Bill of Materials Setup & Customization for Process Manufacturing ? Overview

Microsoft Great Plains has full-featured Manufacturing suite of modules: Capacity... Read More

Groupware and Online Collaboration: Collaboration Series #4

This article is the fourth of a series of articles... Read More

Microsoft Great Plains: Service Business Customization & Integration Example

Microsoft Business Solutions Great Plains might be considered as ERP... Read More

SQL: Querying Microsoft Great Plains ? Overview for Database Administrator/Developer

Looks like Microsoft Great Plains becomes more... Read More

Internet Faxing Service Review

The Internet is reshaping every form of communications medium, and... Read More

It?s Back!! WordPerfect?s Amazing Comeback

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

Falling in Love With More Than One Screensaver: The Fun Part

Having from five to ten and more favorite screensavers is... Read More

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

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

Start Developing Your Own Software

Learning how to program software seems like a daunting task... Read More

high-end home cleaning Bannockburn ..