Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you launch your program with <code>-enableassertions</code> (or <code>-ea</code> for short) then this statement</p> <pre><code>assert cond; </code></pre> <p>is equivalent to</p> <pre><code>if (!cond) throw new AssertionError(); </code></pre> <p>If you launch your program without this option, the assert statement will have no effect.</p> <p>For example, <code>assert d &gt;= 0 &amp;&amp; d &lt;= s.length();</code>, as posted in your question, is equivalent to</p> <pre><code>if (!(d &gt;= 0 &amp;&amp; d &lt;= s.length())) throw new AssertionError(); </code></pre> <p>(If you launched with <code>-enableassertions</code> that is.)</p> <hr> <p>Formally, the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.10" rel="noreferrer">Java Language Specification: 14.10. The <code>assert</code> Statement</a> says the following:</p> <blockquote> <p><strong><em>14.10. The <code>assert</code> Statement</em></strong><br/> <em>An assertion is an <code>assert</code> statement containing a boolean expression. An assertion is <strong>either enabled or disabled</strong>. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and <strong>an error is reported</strong> if the expression evaluates to <code>false</code>. If the assertion is disabled, execution of the assertion has no effect whatsoever.</em></p> </blockquote> <p>Where <em>"enabled or disabled"</em> is controlled with the <code>-ea</code> switch and <em>"An error is reported"</em> means that an <code>AssertionError</code> is thrown.</p> <hr> <h2>And finally, a lesser known feature of <code>assert</code>:</h2> <p>You can append <code>: "Error message"</code> like this:</p> <pre><code>assert d != null : "d is null"; </code></pre> <p>to specify what the error message of the thrown AssertionError should be.</p> <hr> <p>This post has been rewritten as an article <a href="http://programming.guide/java/how-does-assert-work.html" rel="noreferrer">here</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload