IT Certificaions

Google Cloud Platform

Monday, October 3, 2011

Assertion in Java

Assertion is like an statement which enable you to test your assumption that you have made in your program.

For example,

See the test positive number....

if(num >=0){

Now if you assume that this number will always be positive then you are not required to test this expression.
Just use...

assert  num>=0;

So here we are assuming that the number will always be positive and if it is negative then it will throw AssertionError with a detailed message.

You can also append your message to error. Use second flavor of assertion.
assert   num>=0 : "Sorry ! this is a negative number." ;

Complete Example:

import java.util.Scanner;

public class AssertionTestExample {

   public static void main(String argv[]) throws IOException {
      Scanner reader = new Scanner(;      
      System.out.print("Enter a positive number : ");
      int num= reader.nextInt();
      assert num>=0 : "Sorry ! this is a negative number";
      System.out.println("Yes, You have entered a positive number");

Save this file as "" 
Compile it as : javac -source 1.4 
Run it as :   java  -ea AssertionTestExample