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

Popular posts from this blog

Android: where to run keytool command in android

Can not connect to git using ssh (Permissions 0644 for '/root/.ssh/id_rsa' are too open.

Upload file on Google cloud storage using Java servlet on google app engine