# if else statement

on
My question is why output is 3 and not 2 as I expected?

public class CheckNumber{

public static void main(String []args){
int i = 0;
int j = 0;

if (i > 10)
j = 1;
else if (i == 0)
if (j == 100)
j = 2;
else
j = 3;
else
j = 4;

System.out.println(j);
}
}
Comment
Watch Question

Do more with

EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
j is 3 because i is 0. You haven't modified the i before it hits the nested if, therefore i is not less greater than 10 (so j does not equal 4), and i does not equal 100 (so j does not equal 2), therefore i equals 0 and j equals 3. Try the code below and let me know if that does what you need it to:

``````if (i > 10)
j = 1;
else if (i == 100)
if (j == 0)
j = 2;
else
j = 3;
else
j = 4;
``````
High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Commented:
If you format it like this, does it make more sense?
``````public static void main(String []args){
int i = 0;
int j = 0;

if (i > 10)
j = 1;
else if (i == 0)
if (j == 100)
j = 2;
else
j = 3;
else
j = 4;

System.out.println(j);
}
``````

This is why should always use the enclosing brackets, to make it clear which lines belong to which BLOCK:
``````public static void main(String []args){
int i = 0;
int j = 0;

if (i > 10) {
j = 1;
} else if (i == 0) {
if (j == 100) {
j = 2;
} else {
j = 3;
}
} else {
j = 4;
}

System.out.println(j);
}
``````

Commented:
I got it. thanks a lot lads

Do more with