/home/wpollock1/public_html/AJava/AssertionDemo.java

// Trivial example of using assertions.  Run with:
//    java -ea AssertionDemo
//
// Written 4/2014 by Wayne Pollock, Tampa Florida USA
// From discussions posted on comp.lang.java.programmer, mostly by
// "Lew" and "Partricia" on 9/2011 (I don't recall the thread title).

public class AssertionDemo {
   public static void main ( String [] args ) {
      if ( args == null || args.length < 1 ) {
         System.err.println( "Usage: java [-ea] AssertionDemo <NUM>" );
         return;
      }
      double num = Double.parseDouble( args[0] );
      System.out.println( sqrt( num ) );
      //System.out.println( sqrt( Double.NaN ) );
   }

   public static double sqrt ( double num ) {
     double result = 0.0;
     if ( num < 0.0 )
       throw new IllegalArgumentException(
          "sqrt(): negative argument: " + num );

     // Pre-condition check:
     assert num >= 0.0;
     // rest of method body...
     return result;
   }
}

/*

Discussion:
If we un-comment out the NaN line, the "if" fails to throw any
exception.  But if assertions are enabled, the "assert" catches
it.  This is an illustration that an assertion can be useful
even if you have "confidence" that it could never fire.

Note, this caught a bug in the code; This case should have been
checked with an if statement (and supported by a test case).  The
point here is that the test "arg < 0.0" is not strong enough to
ensure arg is >= 0.0.  Perhaps the test should simply be:

    ! arg >= 0.0

--------------------

Should "sqrt( -0.0 )" should throw an exception?  For what it
is worth, Math.sqrt returns 0 for positive or negative zero
input.

(Negative zero is a strange beast.  As far as I can tell, it exists
mainly to produce negative infinity when it is used as a divisor.
For example, it is equal to zero for comparison purposes.
*/