Assertions in Java



Assertions has introduced in 1.4 version. The main objective of assertions is to perform debugging. The traditional way of debugging is to use System.out.println’s. But the main disadvantage of this approach is compulsory we should remove these S.O.P’s after fixing the problem other wise these will execute at run time. Which may effect performance of the system. It may reduce readability of the code and disturbs logging mechanism.

To resolve all these problems sun people has introduces Assertions concept in 1.4 version. The main advantage of assertions is we can enable or disable assertions based on our requirement. But by default assertions are disabled.
Assertions concept we have to use in Test environment or in Development environment but not in the production.


Identifier Vs Keyword
Assert keyword has introduced in 1.4 version hence from 1.4 version on words we are not allowed to use assert as identifier.
Example:-

class Test {
 public static void main(String[] args) {
  int assert = 10;
  System.out.println("assert");
 }

}

in 1.4 or 1.5 if we compile javac assert.java then we will get the following C.E as of release 1.4 assert is a keyword and may not used as an identifier.

javac –source 1.3 assert.java
java Test


Types of assert statement
1) simple assert.
2) Augmented assert.

Simple assert
Syntax: assert <boolean expression> ;
assert(b);

If b is true then normal continuation follows. Else the program will terminate abnormally can rise assertion error.
Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;
  :
  :
  assert(x > 10)
  System.out.println(x);
 }

}

1) javac Test.java
2) java Test
in this case assert statement won’t be executed because it is disable by default.
3) java –ea Test

Then generates assertion error.
Augmented Version Syntax: assert <boolean expression> : <message expression> ;
Assert e1:e2;
‘e1’ - should be boolean type.
‘e2’ - any thing is allowed including method calls also
Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;
     ;
     ;
  assert(x > 10): "here the value of x should be > 10 but it is " + x;
  System.out.println(x);
 }

}

javac Test.java
java –ea Test

Note: assert e1:e2
Here ‘e2’ will be executed iff ‘e1’ is false.

Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;;;
  assert(x == 0): ++x;
  System.out.println(x);
 }

}

javac Test.java
java –ea Test


assert(e1):e2;

for e2 any thing is allowed including method calls also But void return type method calls are not allowed. Violation leads to compile time error.
Example:-

class Test {
 public static void main(String[] args) {
  int x = 10;;;
  assert(x > 0): m1();
  System.out.println(x);
 }
 public static void m1() {
  return;
 }
}

javac Test.java
java –ea Test


Various Run Time Flags
1) -ea - To enable assertions in every non-system class(i.e user defined
class)
2) -enableassertions - To enable assertions in every non-system class(Exactly similar
to -ea)
3) -da - To disable assertions in every non-system class.
4) -isableassertions - To disable assertions in every non-system class.(Exactly similar to -da)
5) -esa - To enable assertions in every system class
6) -enablesystemassertion - similar to -esa
7) –dsa - To disable assertions in every system class.
8) -disablesystemassertions - similar to ‘-dsa’
Ex:-
java –ea –esa –da –dsa –ea Test
All the flags will execute from left to right and there is no priority difference b/w enabling and disabling

- To enable assertions only in the ‘A- Class’
java -ea:Pack1.A
- To enable assertions only in B and D
java -ea:Pack1.B -ea:Pack1.Pack2.D
- To enable assertion in all classes of Pack1 and its sub package classes also.
java –ea:Pack1…
- To enable assertions in all classes present in pack1 but not those present in pack2
java -ea:Pack1… -da:Pack1.Pack2…
Note:- we can enable assertions either class wise or package wise also.

Proper and Improper Use of assertions
1) It is improper to use assert statement for validating the arguments of a public method.

public void withdraw(double amount) {
 assert(amount >= 100);
}

C.E:- No C.E, R.E it is improper use.

2) It is improper to use assertions for validating command line argument also, because these are arguments
to public main method.
3) It is proper to use assertions for validating private method argument.
4) It is improper to mix programming language with assert statement.
5) In our code if there is any place where the control is not allowed to reach. It is the best place to use the
assert statement.
Pack1
A.class
B.class
C.class
D.class
Pack2

Ex:-

switch (month) {
 case 1:
  ....
  ....
  case 2:
   ....
   ....
  case 3:
   ....
   ....
  case 4:
   ....
   ....:
   :
   :
   case 12:
  ....
  ....
  default:
   assert(false);
}

AssertionError
It is the child class of Error and it is unchecked.
It is not recommended to catch AssertionError by using catch Block. It is stupid type of activity.
Example:-

class Test {
 public static void main(String arg[]) {
  int x = 10;;;;
  try {
   assert(x > 10);
  } catch (AssertionError e) {
   System.out.println("I am stupid...Because I am catching
    Assertion ");
   }
  }
 }


6 comments:

  1. This is a very nice one and gives in-depth information. I am really happy with the quality and presentation of the article. I’d really like to appreciate the efforts you get with writing this post. Thanks for sharing.
    Java classes in Chennai

    ReplyDelete
  2. Let’s face it, in today’s current economic climate, particularly when you consider current events for the last 18 months or so, finding employment is tough. It doesn’t matter whether you’re looking for a job to help you stay on top of your bills, or if you’ve decided that you want to forge a new career path, a well-written and professional resume will drastically increase your chances of obtaining employment. So find best online resume writing services here

    ReplyDelete
  3. Thanks for sharing valuable info……
    simplyaweeb

    ReplyDelete
  4. This article aims to investigate the legitimacy of elza energy app a website and mobile application that claims to be a source of online income.

    ReplyDelete
  5. very informative blog, Thanks for shearing this information. Java Training In Pune

    ReplyDelete
  6. However, it is important to note that webtechmantra operates in a legal gray area. The site provides access to copyrighted material without the permission of the copyright owners. Streaming or downloading copyrighted material without permission is illegal, and users could face legal consequences for doing so.

    ReplyDelete