Java .

Java Assertions

TestAssertions - Shows the basic useage of assertions

//new assert statement & keyword in Java 1.4
//compile with -source 1.4 flag
//run with -ea flag

public class TestAssertions { static boolean goodHalOpen = true; static boolean badHalOpen = false; static boolean openPodDoor = false; //set up assertion test static void testPodDoor() { //note: in the assert statement, // the expression before the colon is evaluated and // a false will make the assert throw a // java.lang.AssertionError. //The expression after the colon (if there is one) // will be added to the output // text when the AssertionError is thrown. assert openPodDoor : "bad Hal"; System.out.println("after assertion"); System.out.println(" "); }

public static void main(String[] args) { System.out.println("test one"); openPodDoor = goodHalOpen; testPodDoor(); System.out.println("test two"); openPodDoor = badHalOpen; testPodDoor(); } }

Compiling and Running

javac -source 1.4

java -ea TestAssertions

The Output

test one
after assertion

test two Exception in thread "main" java.lang.AssertionError: bad Hal at TestAssertions.testPodDoor ( at TestAssertions.main(


The Java 2 Platform Specification
Sign in to be the first to comment on Java Assertions.