Java about assert

Source: Internet
Author: User
Tags assert

Yesterday in the view of the NIO source code, see such a sentence, immediately confused forced:

ASSERT (i >= 0);

Assert keyword I have an image, Chinese is called assertion. But has never been to understand its function, today in the cold to take time, put my summary of the code out:

1. The JVM turns off assert by default and can be opened by the-ea command

(1) The Java command turns on assert

Java-ea $classname

(2) Enable Assert in eclipse

On the project right-click Run as---run configurations-Arguments Tab in the VM Arguments fill in-ea and apply

or Windows-Preferences, Java-installed JREs Select JDK Click Edit, enter-ea in default VM arguments: and finish

2. How assert is used
    1. Assert expression;
    2. Assert Expression1:expression2;

Expression2 is the errormsg of Java.lang.AssertionError.

assert(1>2): (1>2? ") Correct ":" This is the ErrorMsg ");
SYSTEM.OUT.PRINTLN ("Success");

Exception in thread "main" Java.lang.AssertionError:This is the errormsg

(Oh shit, the egg hurts the editor, it doesn't work)

3. Assert the applicable scenario
    1. Where the program is not expected to arrive under normal circumstances: assert false;
    2. Parameter values that can be used to check private methods
    3. Preconditions and post conditions for the test method
    4. Used to check the invariant state of a class to determine that in any case, a variable state must meet
4. Assert does not apply to the scene
    1. Do not use assert as a parameter check for the public method, the parameters of the public method are always executed
    2. Assert statements must not have any boundary effects, do not use ASSERT statements to modify variables and change the return value of a method.

Summarize:

Assert is often used to check for some key that has a significant impact on the program.

Java about assert

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.