For nested if statements to be tested by the computer in java, does the if statement above it need to be true?

I am a beginner to java programming (so pardon how stupid this question might seem)

I am currently writing a while loop that uses if else statements.

so say there is

if(a>=c)

System.out.print("hi");

{

if(a=6)

System.out.println("bi")

}

else

a=2

For the if statement in the brackets, would the first if statement have to be true for it(the one within the brackets) to be tested? or will it always go through it regardless of the first one is true or not?

2 Answers

Relevance
  • Steven
    Lv 4
    8 years ago

    YES. If an if statement is true, everything within that statement's brackets get evaluated by the computer. If the statement is false (so if a is less than c in this case) the program doesn't even look at the stuff in the brackets.

    So, if a < c, a becomes 2.

  • 8 years ago

    Be careful here because the code as you provided it does NOT contain a nested if.

    You have a simple statement, System.out.print("hi"), as the body of the first if and then you have an unrelated block that is unconditional. Because of the block, the else clause here represents a syntax error because it is not associated with an if.

    Furthermore, the condition for your second if needs to be "(a == 6)" (a test), not "(a = 6)" (an assignment).

    To answer your original question:

    if (condition1) {

    // this block executes if condition1 is true

    if (condition2) {

    // this block executes if condition1 and condition2 are both true

    } else {

    // this block executes if condition1 is true and condition2 is false

    }

    } else {

    // this block executes if condition1 is false

    if (condition3) {

    // this block executes if condition1 is false and condition3 is true

    } else {

    // this block executes if condition1 and condition3 are both false

    }

    }

Still have questions? Get your answers by asking now.