2

I am new to the assertions concept in java. Where ever i read about the assert concept in java, it is always saying like, if we use assert expression1:expression2, it will use the default constructor or one of the seven constructors in AssertionError class in case it fails. But what my doubt is Who is actually throwing this AssertionError error when the assert statement fails ? Will the compiler adds the "throw new AssertionError(---)" or the JVM will check for the expression and throw the AssertionError (like ArithmeticException, NullPointerException etc...) ?

  • Hi Jarrod, My question is who is exactly taking care of assert statement. Whether the Compiler or the JVM. But the above example is saying how to use the assert statement. – Vinod Kakumani Dec 31 '15 at 06:59

2 Answers2

6

The assertion proposal explains it:

The assert statement [is] merely syntactic sugar for this if statement:

if ($assertionsEnabled && !(Expression1))
    throw new AssertionError(Expression2);

$assertionsEnabled is a synthetic boolean field that also gets added by the compiler.

kapex
  • 28,903
  • 6
  • 107
  • 121
1

Thanks Kapep and David for your quick response.

Finally I got the practical proof :)

Foo.java

package pack1;
public class Foo {
    public void m1( int value ) {
        assert 0 <= value;
        System.out.println( "OK" );
    }
    public static void main( String[] args ) {
        Foo foo = new Foo();
        System.out.print( "foo.m1(  1 ): " );
        foo.m1( 1 );
        System.out.print( "foo.m1( -1 ): " );
        foo.m1( -1 );
    }
}

And when I try with javap command finally I can see the following output with assertion related information added by compiler.

C:>javap pack1.Foo

Compiled from "Foo.java"

public class pack1.Foo {
  static final boolean $assertionsDisabled;
  public pack1.Foo();
  public void m1(int);
  public static void main(java.lang.String[]);
  static {};
}