July 01, 2012

Assertions in Java


Introduction

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

Code:
//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.

Tell the World ...
Handling an Assertion Error
When an assertion fails, AssertionError is thrown. Handling an assertion failure is rarely done. A situation in which you might handle an assertion failure is

in the top-level loop of a high-availability server.
COPY

try {
    assert args.length > 0;
} catch (AssertionError e) {
    // In this case, the message is null
    String message = e.getMessage();
}

try {
    assert args.length > 0 : "my message";
} catch (AssertionError e) {
    // In this case, the message is a string
    String message = e.getMessage();
}


Other way :

In this tutorial we are going to tell you what is assertion in Java and how to use it in your Java program to improve the quality of your applications!

What is Assertion in Java

According to Sun, we can use assertion to test our assumption about programs. That means it validates our program!
In another words we can say that assertions ensures the program validity by catching exceptions and logical errors. They can be stated as comments to guide the

programmer. Assertions are of two types:
1) Preconditions
2) Postconditions.

Preconditions are the assertions which invokes when a method is invoked and Postconditions are the assertions which invokes after a method finishes.

Where to use Assertions
We can use assertions in java to make it more understanding and user friendly, because assertions can be used while defining preconditions and post conditions of the

program. Apart from this we can use assertions on internal, control flow and class invariants as well? to improve the programming experience.

Declaring Assertion:
Assertion statements have two form-
assert expression;
This statement evaluates expression and throws an AssertionError if the expression is false.

assert expression1 : expression2
This statement evaluates expression1 and throws an AssertionError with expression2 as the error message if expression1 is false.
Now we are providing you an example which explains you more clearly.

Here is the code of AssertionExample.java

import java.util.*;
import java.util.Scanner;
 
public class AssertionExample
  {
 public static void main( String args[] )
  {
  Scanner scanner = new Scanner( System.in );

  System.out.print( "Enter a number between 0 and 20: " );
  int value = scanner.nextInt();
  assert( value >= 0 && value <= 20 ) :
  "Invalid number: " + value;
  System.out.printf( "You have entered %d\n", value );
 }
  }
In the above example, When the user enters the number scanner.nextInt() method reads the number from the command line. The assert statement determines whether the

entered  number is within the valid range. If the user entered a number which is out of range then the error occurs.

To run the above example,
Compile the example with:  javac AssertionExample.java
Run the example with:  java -ea AssertionExample
To enable assertions at runtime,  -ea command-line option is used

When you enter the number within range, output will be displayed as:

When you enter  the number out of range, output will be:




Other way:

This tutorial introduces Java's assert statement, which specifies assertions that can be used to enforce preconditions and postconditions. This tutorial is intended

for students who are familiar with methods and exception handling and for Java developers.

[Note: This tutorial is an excerpt (Section 13.13) of Chapter 13, Exception Handling, from our textbook Java How to Program, 6/e. This tutorial may refer to other

chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp.664-665.

Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

Assertions

When implementing and debugging a class, it is sometimes useful to state conditions that should be true at a particular point in a method. These conditions, called

assertions, help ensure a program’s validity by catching potential bugs and identifying possible logic errors during development. Preconditions and postconditions are

two types of assertions. Preconditions are assertions about a program’s state when a method is invoked, and postconditions are assertions about a program’s state after

a method finishes. While assertions can be stated as comments to guide the programmer during development, Java includes two versions of the assert statement for

validating assertions programatically. The assert statement evaluates a boolean expression and determines whether it is true or false. The first form of the assert

statement is assert expression; This statement evaluates expression and throws an AssertionError if the expression is false. The second form is assert expression1 :

expression2; This statement evaluates expression1 and throws an AssertionError with expression2 as the error message if expression1 is false. You can use assertions to

programmatically implement preconditions and postconditions or to verify any other intermediate states that help you ensure your code is working correctly. The example

in Fig. 13.9 demonstrates the functionality of the assert statement. Line 11 prompts the user to enter a number between 0 and 10, then line 12 reads the number from

the command line. The assert statement on line 15 determines whether the user entered a number within the valid range. If the user entered a number that is out of

range, then the program reports an error. Otherwise, the program proceeds normally.


Fig. 13.9 Checking with assert that a value is within range.
   1  // Fig. 13.9: AssertTest.java
   2  // Demonstrates the assert statement
   3  import java.util.Scanner;
   4
   5  public class AssertTest
   6  {
   7     public static void main( String args[] )
   8     {
   9        Scanner input = new Scanner( System.in );
  10      
  11        System.out.print( "Enter a number between 0 and 10: " );
  12        int number = input.nextInt();
  13      
  14        // assert that the absolute value is >= 0
  15        assert ( number >= 0 && number <= 10 ) : "bad number: " + number;
  16      
  17        System.out.printf( "You entered %d\n", number );
  18     } // end main
  19  } // end class AssertTest


Enter a number between 0 and 10: 5
You entered 5




Enter a number between 0 and 10: 50
Exception in thread "main" java.lang.AssertionError: bad number: 50
        at AssertTest.main(AssertTest.java:15)



Assertions are primarily used by the programmer for debugging and identifying logic errors in a application. By default, assertions are disabled when executing a

program because they reduce performance and are unnecessary for the program’s user. To enable assertions at runtime, use the -ea command-line option when to the java

command. To execute the program in Fig. 13.9 with assertions enabled, type
java -ea AssertTest
You should not encounter any AssertionErrors through normal execution of a properly written program. Such errors should only indicate bugs in the implementation. As a

result, you should never catch an AssertionError. Rather, you should allow the program to terminate when the error occurs, so you can see the error message, then you

should locate and fix the source of the problem. Since application users can choose not to enable assertions at runtime, you should not use the assert statement to

indicate runtime problems in production code. Rather, you should use the exception mechanism for this purpose.

3 comments:

  1. Attractive portion of content. I just stumbled
    upon your weblog and in accession capital to say that I get actually enjoyed account your blog posts.

    Anyway I will be subscribing for your feeds and even I achievement you get entry to constantly rapidly.



    Also visit my web blog; anti snoring mouth guard

    ReplyDelete
  2. Sweet blog! I found it while surfing around on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo News?
    I've been trying for a while but I never seem to get there! Thanks

    Also visit my blog post :: mazda 16x

    ReplyDelete
  3. This is the perfect webpage for everyone who hopes to find out about this topic.

    You understand a whole lot its almost hard to argue with you (not that I really would want to…HaHa).
    You certainly put a new spin on a subject that's been written about for many years. Wonderful stuff, just great!

    Check out my web blog ... garbage disposals

    ReplyDelete

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts