What does the Java assert keyword do, and when should it be used?

前端 未结 19 1737
眼角桃花
眼角桃花 2020-11-22 15:58

What are some real life examples to understand the key role of assertions?

19条回答
  •  误落风尘
    2020-11-22 16:30

    Assertions are disabled by default. To enable them we must run the program with -ea options (granularity can be varied). For example, java -ea AssertionsDemo.

    There are two formats for using assertions:

    1. Simple: eg. assert 1==2; // This will raise an AssertionError.
    2. Better: assert 1==2: "no way.. 1 is not equal to 2"; This will raise an AssertionError with the message given displayed too and is thus better. Although the actual syntax is assert expr1:expr2 where expr2 can be any expression returning a value, I have used it more often just to print a message.

提交回复
热议问题