advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Assertions in Java :

Internal Invariants

Assertions can be used within programs to make sure the program behaves in a predetermined manner and will throw an error when violated. For instance, an assertion can be placed in the code below to declare that interest will never be negative.

	if (interest > 5000){
		principal = principal + 500;
	}else if (interest < 5000 ){
		principal = principal +10;
	}else {
       		assert interest >0:"Interest cannot be negative"
	}

It can also be used to check the ability to reach statements in a method. In the example below the assert statement is included at a place where it would not be reached. If, however, for some reason the code is executed, we know that a serious problem exists.

	
public int returnSomeValue(int d){
	 if (d > =0)
	return d;
	 if (d<0)
	         return Math.abs(d);
	
	assert false: "This statement should not be reached Since it has reached 
	and you are seeing this error there is some serious problem". 

	}

Preconditions:

Following the principles of "Design by Contract," assert statements can be used to check for preconditions. Preconditions are values or parameters passed to a method, to be used for the functioning of the program. Assert statements can be used to check the validity of the parameters passed before they get used in the body of the method.

However java warns that assert statements should not be used to check parameters of a public method. In the sample above an assert statement could have been used if the method were public, to check that the interest was always greater than zero.

private int checkInterest (int interest) {
  assert interest > 0:"Interest cannot be negative."

           Do computation with interest.
}

Postconditions:

Just like preconditions, there may be instances where a program needs to execute some postconditions. Postconditions need to be evaluated before each exit point in the method. For instance assert statements can be used to check for the validity of the returned values in a method that has multiple return statements.

Class Invariants:

A class invariant specifies the values of attributes across multiple instances of a class. Assertions can be used to check on a method of a class if it is accessed and modified by multiple instances. Assert statements can be used to make sure that internal structures in a class are intact or according to the specification even after multiple manipulations on them.

Where not to use Assertions:

Assertions are not suitable for all occasions. A fact that needs to be remembered is that assertions cannot be used wherever the normal course of a program is affected when assertions are disabled. Assertions can be disabled and affect the outcome of the program. Normally, assertions are used to check conditions during programming. The idea is to have them on while developing and testing. Assertions are turned off during production, when you feel the system (program) is running normally and you do not need the extra overhead of assertions in the code. The memory saving is particularly helpful in wireless applications where memory is a constraint.

Assertions should not be used to check arguments on a public method. According to the spec this should be done by the method regardless of whether assertions are enabled or not. Moreover incorrect arguments to methods need to throw an appropriate IllegalArgumentException instead of a generic AssertionError.

Compiling programs with Assertions:

By default, assertions are disabled during compilation using J2SE 1.4 compiler, so the command javac somefile.java will compile without assertions. To compile a java program with assertions we need to include the command line option –source 1.4.

javac –source 1.4 AssertionsFile.java 

Assert is a new keyword included in J2SE 1.4, so compiling a program with assertions using an earlier version of the compiler will complain that assert is not defined. This could cause compatibility problems with existing code that might have used assert as an identifier. However existing class files may not be affected. A java file needs to be compiled with assertions enabled so that the program can be run with assertions enabled.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 34
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

IBM Brings Developers Into the Cloud
Apache at 10: You Can't Buy Us
Microsoft's CodePlex Foundation Moving Forward
Apple Claims 100,000 Apps, Google Analyzes Them
Nokia Latest to Play Opera Mobile 10 Browser
PayPal Opens Up Payment Platform to Devs
Ubuntu Linux 9.10 'Karmic Koala' Starts Its Climb
IBM Links Rational Developer Tools, Tivoli Apps
Libraries Give Vista Apps a Windows 7 Look
Ubuntu: The 'Default Alternative' to Windows?

Delivering Web-based Embedded Fonts in CSS 3
Adobe Helps PHP Developers Create Rich Internet Applications
Java Developers Finding a Home at Adobe Flex
Virtualization Delivers a Dynamic Infrastructure
Consuming XML Web Services in iPhone Applications
Build a More Agile Business with IBM
POJO-Based Solutions for LDAP Access: One Good, One Better
IBM Offers Enhanced Measurement and Management for Energy Usage
IBM Helps Transformation to an Information-Based Enterprise
Top Five Touch UI-Related Design Guidelines

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs