Import Java - Util. Import Java - Util.Scanner Public Class Assertionexample

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

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 invoes when a method is invoed and Postconditions are the assertions
which invoes after a method finishes.
Where to use Assertions
!e can use assertions in "ava to mae 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 expression% and throws an AssertionError with expression& as the error message if
expression% is false.
'ow we are providing you an example which explains you more clearly.
Here is the code o AssertionExa!ple."ava
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 num!er !et"een # an$ %#& );
int value = scanner.next'nt();
assert( value (= # )) value *= %# ) &
'nvali$ num!er& + value;
System.out.print,( -ou .ave entere$ /$0n1 value );
2
2
In the above example, !hen the user enters the number scanner.next#nt$) 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.
%o run the a&ove exa!ple'
(ompile the example with: "avac AssertionExa!ple."ava
)un the example with: "ava (ea AssertionExa!ple
To enable assertions at runtime, $ea command$line option is used
When )ou enter the nu!&er *ithin range' output *ill &e displa)ed as:
When )ou enter the nu!&er out o range' output *ill &e:

You might also like