Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are assert statements in Java? [duplicate]

Tags:

java

assert

Possible Duplicate:
What does assert do?

Please give me some details with at least one example.

like image 601
Vijay Bhaskar Semwal Avatar asked Aug 26 '10 06:08

Vijay Bhaskar Semwal


2 Answers

Try this:

public class AssertionTest {

  public static void main(String args[]) {
     boolean assertTest = true;
     assert assertTest;
     assertTest = false;
     assert assertTest;
  }
}

If you compile and run this, you should have an idea of how the assertion statement works.

Update:
As correctly pointed out in the comments, after compilation, you run this as java -ea AssertionTest - the -ea flag enables assertions.

like image 190
Noel M Avatar answered Sep 22 '22 02:09

Noel M


You use the assert keyword to verify if something you believe about your code is true.

The assertion in not a substitute for code validations, because it can be disabled at runtime ( it is disabled by default ) So, if the assertion is disabled and you use it to control your logic, you'll have undesired results.

For instance:

class SomeClass {
    public void someMethod( String input ) {
         // do something with the input... 
         String result = processs( input );
         assert result.startWith("OK");
         // continue with your code.. 
         return result;
     }
    ....
 }

In that code, the program does something with the input. Your assumption is, that the result string starts with "OK" always. You put the assertion, to make sure that happens, but you don't put any logic around that ( you don't do anything if that doesn't happens )

When you're testing your code, with assertion enabled, if you notice your result doesn't start with "OK", then the program will stop it's execution.

To enable/disble assertions, you have to pass the flag -ea to the java

See : http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html for more information.

like image 22
OscarRyz Avatar answered Sep 20 '22 02:09

OscarRyz