Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following code <em>is</em> legal:</p> <pre><code>int x = 5; int y = 2; int z = 0; if (x == y) z = x * y; else z = y - x; </code></pre> <p>As Sean Bright mentioned, your problem is that you are trying to test a non-boolean expression. You should be using the <code>==</code> operator instead of the <code>=</code> operator in your <code>if</code> clause.</p> <p>Another thing to mention is that it is considered, by many, bad practice to skip using the curly braces in an <code>if-then-else</code> statement. It can lead to errors down the road, such as adding another statement to the body of the <code>if</code> or <code>else</code> code blocks. It's the type of bug that might be a pain to figure out.</p> <p>This isn't really an issue when using an <code>if-else</code> statement, because Java will catch this as a syntactic error (<code>else</code> statement without a preceding <code>if</code>). However, consider the following <code>if</code> statement:</p> <pre><code>if (x == y) z = y * x; </code></pre> <p>Now, suppose later on you need to do more things if <code>x == y</code>. You could easily do the following without realizing the error.</p> <pre><code>if (x == y) z = y * x; w = x * y - 5; </code></pre> <p>Of course, the second statement <code>w = x * y - 5</code> will be executed regardless of the outcome of the <code>if</code> statement test. If you had curly braces to begin with, you would have avoided the problem.</p> <pre><code>if (x == y) { z = y * x; w = x * y - 5; // this is obviously inside the if statement now } </code></pre>
 

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