AssertionDemo.java

Download AssertionDemo.java

 1: // Trivial example of using assertions.  Run with:
 2: //    java -ea AssertionDemo
 3: //
 4: // Written 4/2014 by Wayne Pollock, Tampa Florida USA
 5: // From discussions posted on comp.lang.java.programmer, mostly by
 6: // "Lew" and "Partricia" on 9/2011 (I don't recall the thread title).
 7: 
 8: public class AssertionDemo {
 9:    public static void main ( String [] args ) {
10:       if ( args == null || args.length < 1 ) {
11:          System.err.println( "Usage: java [-ea] AssertionDemo <NUM>" );
12:          return;
13:       }
14:       double num = Double.parseDouble( args[0] );
15:       System.out.println( sqrt( num ) );
16:       //System.out.println( sqrt( Double.NaN ) );
17:    }
18: 
19:    public static double sqrt ( double num ) {
20:      double result = 0.0;
21:      if ( num < 0.0 )
22:        throw new IllegalArgumentException(
23:           "sqrt(): negative argument: " + num );
24: 
25:      // Pre-condition check:
26:      assert num >= 0.0;
27:      // rest of method body...
28:      return result;
29:    }
30: }
31: 
32: /*
33: 
34: Discussion:
35: If we un-comment out the NaN line, the "if" fails to throw any
36: exception.  But if assertions are enabled, the "assert" catches
37: it.  This is an illustration that an assertion can be useful
38: even if you have "confidence" that it could never fire.
39: 
40: Note, this caught a bug in the code; This case should have been
41: checked with an if statement (and supported by a test case).  The
42: point here is that the test "arg < 0.0" is not strong enough to
43: ensure arg is >= 0.0.  Perhaps the test should simply be:
44: 
45:     ! arg >= 0.0
46: 
47: --------------------
48: 
49: Should "sqrt( -0.0 )" should throw an exception?  For what it
50: is worth, Math.sqrt returns 0 for positive or negative zero
51: input.
52: 
53: (Negative zero is a strange beast.  As far as I can tell, it exists
54: mainly to produce negative infinity when it is used as a divisor.
55: For example, it is equal to zero for comparison purposes.
56: */