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?
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?
Let me rewrite your program in pseudocode:
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.