Monday, July 19, 2010

assertion replacing sop()s in code debugging from JDK 1.4

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.
---------------------------------------------------------
links

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/guide/lang/assert.html

---------------------------------------------------------
1. How do I get the assert statement to work?
2. How do I get line numbers?
3. How do I get soft tabs?
4. How do I run Javadoc?
5. How do I see the javadoc for Sun-supplied classes?
6. Why are my JUnit results not showing up?
7. How do I create a test suite?
8. In JUnit, what's the difference between a "failure" and an "error"?
9. Why does Source->Format really mess up my formatting?
10. How do I import an existing program into Eclipse?

1. How do I get the assert statement to work?

In Eclipse 3.1, go to Window -> Preferences -> Java -> Compiler and set the Compiler Compliance Level to 1.4 or 5.0. Also check Use Default compliance settings. This tells the compiler to recognize and allow assert statements, but does not enable them.

In Eclipse 3.0 (Java 1.4), the settings are a little fussier. Go to Window -> Preferences -> Java -> Compiler -> Compliance and Classfiles and set:

Compiler Compliance Level: to 1.4
Use default compliance settings to unchecked
Generated .class files compatibility: to 1.4
Source compatibility: to 1.4
Disallow identifiers called 'assert': to Error
Compiler Compliance Level to 1.4


To enable (make active) assert statements, you must set a flag to the compiler. Go to Run -> Run... -> Arguments, and in the box labeled VM arguments:, enter either -enableassertions or just -ea. Accept the changes and close the dialog.

To get Javadoc to recognize the assert statement, see How do I run Javadoc?

2. How do I get line numbers?

Go to Window -> Preferences -> General -> Editors -> All Text Editors and check Show line numbers.

3. How do I get soft tabs?

To get soft tabs (tabs replaced by spaces) as you type, go to Window -> Preferences -> Java -> Code style-> Formatter and select the profile Java Conventions [built-in]. This should be set correctly to give soft tabs.

You can create your own profile by clicking Show...; for soft tabs, go to Indentation uncheck Use tab characters. After making your changes, you will be prompted for a name for your new profile.

4. How do I run Javadoc?

1. In the Package Explorer window, choose the package or file for which you want to generate documentation.
2. Choose File -> Export... -> Javadoc -> Next>
1. If the dialog box displays the message The Javadoc command does not exist, then you need to click the Configure... button and locate javadoc.exe. You already have this file--it is probably in YourJavaDirectory/jdk1.5.0/bin/.
3. Select the project, and the destination for the Javadoc files. Normally, you should only generate documentation for public fields and methods.
4. If you have no assert statements, you can click Finish at this point.
5. Click Next >.
6. Click Next > again.
7. Check JRE 1.4 source compatibility (otherwise your assert statements will be treated as errors). [See also How do I get the assert statement to work?]
8. Click Finish.

5. How do I see the javadoc for Sun-supplied classes?

If you hover (don't click) your mouse over the name of a method, you should see a simplified Javadoc explanation. If this doesn't work for Sun-supplied methods, then you don't have the source code installed. Here's how to install the source code:

1. Go to http://java.sun.com/j2se/1.5.0/download.jsp and choose to download the JDK 5.0 Source Code (I don't know what SCSL and JRL are, but SCSL worked for me).
2. For JDK 5.0, select Download(SCSL source) .
3. Register. This is relatively painless, especially if you either ignore or enjoy reading license agreements.
4. Download JDK (SCSL) 5.0 (1.5.0). This will give you a file jdk-1_5_0-src.scsl.zip. You do not need to unzip this file; Eclipse likes it the way it is.
5. In Eclipse, go to Projects -> Properties -> Java Build Path -> Libraries and expand JRE System Library [jre 1.5.0], then rt.jar. Select Source attachment and click Edit....
6. Select the above zip file.
7. Finish by exiting the dialog boxes.

6. Why are my JUnit results not showing up?

Maybe it's because all your tests succeeded. For more satisfying results, go to Window -> Preferences -> Java -> JUnit and uncheck Show the JUnit results view only when an error or failure occurs.

7. How do I create a test suite?

Go to File -> New -> Other... -> Java -> JUnit -> TestSuite, and click Next>. Select all the classes, and click Finish.

You can run this test suite the same way you run other JUnit tests.

8. In JUnit, what's the difference between a "failure" and an "error"?

A failure is when one of your assertions fails--that is, your program does something wrong, and your JUnit test notices and reports the fact. An error is when some other Exception occurs--one you haven't tested for and didn't expect, such as a NullPointerException or an ArrayIndexOutOfBoundsException.

9. Why does Source->Format really mess up my formatting?

You have unmatched brackets, braces, or parentheses, and the code reformatter is doing the best it can. Find the syntax error (somewhere near the beginning of the messed up formatting), fix it, and reformat.

10. How do I import an existing program into Eclipse?

Here are two ways that work. First,
1. In your workspace folder, create a new folder, and put your files into that folder.
2. Ask Eclipse to create a new project (File -> New -> Project...) and, for the name of the project, type in the exact name of your new folder.
3. Click Finish.
The second way is very similar:
1. Ask Eclipse to create a new project (File -> New -> Project...) with any suitable name.
2. Copy your files into the new folder.
3. In Eclipse's Package Explorer pane, right-click on the new project and choose Refresh from the pull-down menu.


---------------------------------------------------------

package com;

public class AssertTest {

/**
* @param args
*/

public boolean myErrorDisplay(){
System.out.println("here error");
return false;
}
public static void main(String[] args) {
// The following assert statement will stop execution
// with a message if assertions are turned on.

assert 1<10; assert true; assert 1>10 : new AssertTest().myErrorDisplay();
assert 1<10;
assert true;
// The following statement will only be printed if
// assertions are turned off because assertions
// were not allowed at run time by the -ea parameter.
System.out.println("Assertions are not active.");


}

}

No comments: