Assertion in java

New Features:

  • Assertion(jdk-4)
  • For-each loop(jdk-5)
  • Varargs(jdk-5)
  • Static Import(jdk-5)
  • Autoboxing and Unboxing(jdk-5)
  • Enum Type(jdk-5)
  • Generics(jdk-5)
  • Annotation(jdk-5)
  • String datatype in switch(jdk-7)
  • Parameterized try(jdk-7)
  • Catch with multiple parameters(jdk-7)
  • Nio pacakge(jdk-7)
  • Underscores in number(jdk-7)
.................

Assertion:

Comes in jdk 1.4.
According to Sun,  assertion is used to test our assumption about programs. That means it validates our program! In another words  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.


Assertions is used to make java-program more understandable and user friendly, because assertions can be used while defining preconditions and post conditions of the program. Apart from this  assertions can use on internal, control flow and class invariants as well to improve the programming experience.



Assertion statements have two form-

assert expression;
This statement evaluates expression and throws an AssertionError if the expression is false. 
To enable assertions at runtime,  -ea command-line option is used
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
Declaring Assertion:
assert expression1 : expression2
This statement evaluates expression1 and throws an AssertionError with expression2 as the error message if expression1 is false.
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.
Example:
import java.util.*;

class AssertionTest
          public static void main( String args[] )
          { 
                   Scanner scanner = new Scanner( System.in ); 

                   System.out.print("Enter your age "); 
                   int value = scanner.nextInt(); 
                   assert value>=18:" Not valid,Only within 18 is allowed."; 
                   System.out.println("value is "+value); 
        }
}
To run the above example,
Compile the example with:  javac AssertionTest.java
Run the example with:  java -ea AssertionTest

*********************************************************************************************



Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mbl: 9953584548
Write us at: - Smruti@apextgi.com and pratap@apextgi.com




No comments:

Post a Comment