# Beginner question in Java [closed]

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?

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

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.