-1
$\begingroup$

I am just starting to study Java and was wondering why the following code

if(x>2) x*=2; if(x>4)x=0; System.out.println(x);

returns 0 for any value of x greater than 2. For example, when x=3, why would 6 not be returned?

$\endgroup$
  • $\begingroup$ Java questions are off-topic here. $\endgroup$ – Yuval Filmus Apr 22 '18 at 5:43
0
$\begingroup$

Let me rewrite your program in pseudocode:

  1. If $x > 2$ then $x \gets 2x$.
  2. If $x > 4$ then $x \gets 0$.
  3. Print $x$.

Let us denote the value of $x$ at the beginning of line $i$ by $x_i$. If $x_1 > 2$ then the condition $x > 2$ in line 1 holds, and so $x_2 = 2x_1$. But then $x_2 = 2x_1 > 2 \cdot 2 = 4$, and so the condition $x > 4$ in line 2 holds. As a consequence, $x_3 = 0$, and so line 3 prints 0.

| cite | improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.