Model G20 2027 at FLAME University, registrations now open

Conditional statements in Java | ICSE Class 9 Computer Applications Notes

28 min read

On this page

This note covers decision making, Boolean conditions, simple if statements, if-else statements, else-if ladders, nested if statements, switch-case selection, default, break, fall-through, menu-driven programs and program termination in Java.

How do conditions change the flow of a Java program?

Flow of control means the order in which a program executes its statements. A statement is an instruction in a program. In a sequence, statements execute one after another. A conditional statement selects a path according to a test, so some statements may be skipped.

A condition is an expression evaluated as true or false. An expression combines values, variables or operators to produce a result. A variable is a named storage location. An operator is a symbol that performs an operation on its operands, the values it acts on.

Definition: A Boolean value is either true or false. Java conditions in if statements must produce a Boolean result; a numeric value by itself is not a Boolean condition.

Which symbols express comparisons and logical tests?

SymbolMeaning
> and <Greater than and less than
>= and <=Greater than or equal to and less than or equal to
== and !=Equal to and not equal to
&&Logical AND: true when both conditions are true
||Logical OR: true when at least one condition is true
!Logical NOT: reverses a Boolean value
=Assignment: stores a value in a variable

Relational operators compare values. Logical operators combine or reverse conditions. Do not confuse assignment with comparison: = stores a value, whereas == tests equality. The symbols +, -, * and / mean addition, subtraction, multiplication and division in the arithmetic used below.

Parentheses, written ( ), enclose an if condition. Curly braces, written { }, group statements into a block. A semicolon, written ;, ends declarations and expression statements. These punctuation marks have different jobs; they cannot be exchanged simply because the lines look similar.

A declaration introduces a variable and its type, which determines the kind of value stored. The Java type int stores integers, meaning whole numbers including negative values and zero. The type double stores floating-point numbers, which can represent fractional values. Initialisation gives a variable its starting value.

How does a simple if statement work?

Syntax: Write if (condition) followed by a statement or a block enclosed in braces. If the condition is true, that controlled statement or block executes. If it is false, it is skipped.

Use a simple if when an action is required for the true result and there is no corresponding alternative action. After the decision, normal execution continues with the next statement outside the if block. A false condition does not mean that the entire program stops.

How should the program structure be read?

The examples use a class, a definition that groups Java members, named Conditional. A method is a named block of instructions; main is the method invoked here. The keyword void means that this method returns no value. A keyword is a word reserved by Java.

Use this classroom form by creating an object, an instance of the class, and invoking its main method in BlueJ, a Java development environment. Each example is a separate program. The class name is reused across examples, so treat each listing independently.

System.out.println is the output method used below: it displays its argument and then starts a new line. An argument is the value supplied to a method. The dot selects a member; parentheses contain the argument. Double quotation marks enclose a string, a sequence of characters.

Worked example 1. Trace the simple if using Num, an integer initially equal to 6. The assignment increases it by 1 before comparison.

class Conditional {
  void main() {
    int Num = 6;
    Num = Num + 1;
    if (Num > 5) {
      System.out.println(Num);
    }
  }
}

Answer: 7

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The declaration creates Num with value 6. The following assignment evaluates 6 + 1 and stores 7 back in Num.
  3. The if line compares the updated value with 5. Since 7 is greater than 5, the condition is true.
  4. The output line executes and displays 7. The brace after it ends the controlled block.
  5. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

Note: Do not put a semicolon immediately after the closing parenthesis of an if condition when you intend the following block to be controlled by that condition. Such a semicolon forms an empty statement.

How does if-else choose between two alternatives?

Property: The condition selects the if or else branch

An if-else statement supplies a true branch and a false branch. A branch is one possible execution path. The if block runs when the test is true; the else block runs when it is false. For a normally completed selection, one of these two alternatives is chosen.

Syntax: Write if (condition) { statements for true; } else { statements for false; }. The else keyword has no separate condition. Its selection depends on the result of the preceding if test.

How can two values be compared?

Worked example 2. Compare num1 and num2, integers holding 5 and 6 respectively. Both messages in the selected block must be printed.

class Conditional {
  void main() {
    int num1 = 5;
    int num2 = 6;
    if (num1 > num2) {
      System.out.println("first number is larger");
      System.out.println("Bye");
    } else {
      System.out.println("second number is larger");
      System.out.println("Bye Bye");
    }
  }
}

Answer: second number is larger
Bye Bye

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The two declarations give num1 the value 5 and num2 the value 6.
  3. The if comparison is false because 5 is not greater than 6. Both output statements in its block are skipped.
  4. The else line selects the alternative block. Its first output line displays the comparison message; its second displays Bye Bye.
  5. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

This comparison has two unequal given values. If it were reused for arbitrary inputs, equality would need attention: the false result of num1 > num2 means num1 is less than or equal to num2. It does not establish that the second value is strictly larger.

How can the selected branch calculate a result?

Worked example 3. Find the difference by subtracting the smaller of 5 and 6 from the larger. The integer diff stores the calculated difference.

class Conditional {
  void main() {
    int num1 = 5;
    int num2 = 6;
    int diff;
    if (num1 > num2) {
      diff = num1 - num2;
    } else {
      diff = num2 - num1;
    }
    System.out.println(diff);
  }
}

Answer: 1

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The first two declarations store the given numbers. The third declares diff without assigning its value yet.
  3. The comparison 5 > 6 is false, so the first subtraction is skipped.
  4. The else assignment stores 6 - 5, which is 1, in diff.
  5. The output statement is outside both branches. It displays the value assigned by the selected branch.
  6. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

The output line is shared by the alternatives because it follows the entire decision. Placing it inside one branch would make its execution depend on reaching that branch. This distinction between controlled statements and following statements matters when tracing both output and calculation.

How does an else-if ladder select among several paths?

Property: An else-if ladder selects the first true condition

An else-if ladder connects several tests in order. Java writes else if as two words. The first condition is tested first. A false result leads to the next test; a true result selects its block and skips the remaining alternatives in that ladder.

Rule: In an else-if ladder, the first true condition determines the selected block. A final else handles the situation where every earlier condition is false. Without a final else, all controlled blocks may be skipped.

How can a number be classified by its sign?

Worked example 4. Classify number, an integer set to 0, as positive, negative or zero. Positive means greater than zero; negative means less than zero.

class Conditional {
  void main() {
    int number = 0;
    if (number > 0) {
      System.out.println("Number is positive");
    } else if (number < 0) {
      System.out.println("Number is negative");
    } else {
      System.out.println("Number is zero");
    }
  }
}

Answer: Number is zero

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The declaration initialises number to 0.
  3. The first test asks whether 0 is greater than 0. It is false, so the positive message is skipped.
  4. The else-if test asks whether 0 is less than 0. It is also false, so the negative message is skipped.
  5. The final else block therefore executes and prints Number is zero.
  6. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

Order of conditions is part of the logic. Where conditions overlap, an earlier true test prevents a later test from being reached. Before writing a ladder, decide which alternatives the program must distinguish and check that the order expresses those alternatives correctly.

Several separate if statements behave differently from one ladder. Each independent if is reached and tested in sequence unless execution is interrupted. A ladder links its alternatives so that later tests are skipped after a successful earlier test. Count the actual keywords, not merely the number of comparisons.

For sign classification, equality with zero belongs to the final alternative. Writing only greater-than and less-than branches without an else would leave zero without a message. A boundary value lies where a condition changes result; zero is the boundary being checked here.

How does nested if express a decision inside another decision?

A nested if is an if statement placed inside the controlled part of another decision. The outer decision determines whether execution reaches the inner decision. An inner test is not evaluated merely because its text appears somewhere in the program.

Rule: Read a nested decision from the outside towards the inside. First identify the outer branch taken. Then trace only the statements inside that branch, including any further condition encountered there.

How do logical OR and an inner comparison interact?

Worked example 5. Use Number1 = 7 and Number2 = 8. The outer condition uses logical OR; the inner condition compares Number1 with 7.

class Conditional {
  void main() {
    int Number1 = 7, Number2 = 8;
    if (Number1 > 0 || Number2 > 5) {
      if (Number1 > 7) {
        System.out.println("Code Worked");
      } else {
        System.out.println("Code MightWork");
      }
    } else {
      System.out.println("Code will not Work");
    }
  }
}

Answer: Code MightWork

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The declaration introduces both integer variables and their stated initial values. A comma separates the two variable declarations within this int statement.
  3. The outer test is true because Number1 > 0 is true. Logical OR needs at least one true operand.
  4. The inner test checks 7 > 7, which is false. The Code Worked output line is skipped.
  5. The inner else prints Code MightWork. The outer else is skipped because execution entered the outer true branch.
  6. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

Indentation means spaces at the beginning of a line to show its level within the structure. It makes nested code easier to read. Java uses braces to group statements; indentation alone does not change which statements belong to a block.

Without braces, an else belongs to the nearest preceding unmatched if permitted by the structure. This is why aligning an else visually is not enough to establish its partner. Explicit blocks make the intended association clear and reduce mistakes when another statement is added.

An else-if ladder asks successive alternative questions. Nesting asks a further question within a path already selected. Trace their structure rather than assuming they are interchangeable. In the program above, the inner false result still occurs within the outer true branch, not within its false branch.

How do switch, case and default choose an entry point?

A switch statement selects an entry point by matching a selector value against case labels. The selector is the expression in parentheses after switch. A case label marks a possible matching value. The colon, written :, ends the label and introduces its following statements.

The examples here use an integer selector. A traditional colon-style switch compares that value with the case values. Use if tests for inequalities or ranges instead of writing a relational condition as a case label. Case labels in this form use constant values, not changing variable tests.

Syntax: Write switch (selector) { case constant: statements; break; default: statements; }. The default label supplies an entry point when no case value matches. It is optional, but can provide useful handling of unmatched choices.

How does break prevent additional case statements from running?

Worked example 6. Set Number, the integer selector, to 10 and trace the switch. The displayed words are fixed messages associated with the labels, not numerical conversions.

class Conditional {
  void main() {
    int Number = 10;
    switch (Number) {
      case 10:
        System.out.println("Ten Thousand");
        break;
      case 20:
        System.out.println("Twenty Thousand");
        break;
      default:
        System.out.println("Not enough!!!");
    }
  }
}

Answer: Ten Thousand

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The declaration stores 10 in Number. The switch line uses this value as its selector.
  3. The case 10 label matches. Its output line displays Ten Thousand.
  4. The following break exits this switch. The statements under case 20 and default are skipped.
  5. The closing switch brace marks the point after the selection. Execution can continue with any subsequent statement in the method.
  6. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

The break statement transfers control out of the enclosing switch in these examples. It does not mean that the whole program terminates. When a switch is followed by another statement, that statement can execute after break has ended the selection.

A default label is not an extra test performed after every case. With the normal break arrangement, it provides the alternative for a selector without a matching label. To predict output accurately, distinguish the entry point selected by matching from the statements executed after entry.

What happens when a switch case falls through?

Fall-through occurs in the colon-style switch when execution continues into following labelled statements because no break or other transfer of control stops it. A later case label does not automatically end the earlier case. After entry, statements execute in their written order.

How can one matching label produce more than one output line?

Worked example 7. Use Number = 20. There is no break after the output under case 20. A break follows the output under case 30.

class Conditional {
  void main() {
    int Number = 20;
    switch (Number) {
      case 10:
        System.out.println("Ten Thousand");
        break;
      case 20:
        System.out.println("Twenty Thousand");
      case 30:
        System.out.println("Thirty Thousand");
        break;
      case 40:
        System.out.println("Forty Thousand");
      default:
        System.out.println("Not enough!!!");
    }
  }
}

Answer: Twenty Thousand
Thirty Thousand

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The declaration supplies selector value 20. The switch enters at case 20, skipping the statements before that label.
  3. The first reached output line displays Twenty Thousand. There is no break immediately after it.
  4. Execution continues past the case 30 label and prints Thirty Thousand. The selector has not changed to 30.
  5. The break following that output ends the switch. The case 40 and default statements are not reached in this run.
  6. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

Use the complete listing above for the following alternative runs. Each row changes only the starting value assigned to Number. The labels and break statements remain exactly as shown. A later label is not rechecked as a condition when execution falls through to it.

NumberOutput in orderReason
10Ten ThousandThe first break ends this path
20Twenty Thousand; Thirty ThousandExecution falls through to case 30
30Thirty ThousandEntry is directly at case 30
40Forty Thousand; Not enough!!!No break separates case 40 and default
50Not enough!!!No case matches, so entry is at default

Note: Default can be reached by fall-through as well as selected when no case matches. In the displayed program, Number equal to 40 matches a case but still reaches the default output because there is no intervening break.

The semicolons in the output table separate successive displayed lines. The actual program prints each message on its own line. Fall-through may be deliberate, but an omitted break can also be a logical error: the program runs while producing an unintended result.

How can a menu-driven calculator combine switch and nested if?

A menu-driven program presents available operations and performs the operation selected by the user. A choice can be represented by a number or character. The type char stores one character; single quotation marks enclose a character literal, a character written directly in the code.

For a four-operation calculator, the menu contains addition, subtraction, multiplication and division. Let val1 and val2 be the two numbers, op be the chosen operator, and result be the calculated value. For subtraction, this calculator subtracts the smaller value from the larger.

The call System.exit(0) requests termination of the running Java program. Here 0 is the exit status, conventionally indicating normal termination. It does not print zero. This call is used below to end an invalid calculation path before the shared result output.

For division, the divisor is the second value, val2. Check it before division. A menu needs both a valid-choice path and an unmatched-choice path; the latter can report an invalid operator. The following run fixes the supplied values and choice so its output can be traced completely.

How does the calculator handle its supplied choice?

Worked example 8. Use val1 = 84, val2 = 4 and op = '/'. The operation menu is printed before the selected operation. No keyboard input is needed for this fixed-input run.

class Conditional {
  void main() {
    double val1 = 84, val2 = 4, result = 0;
    char op = '/';
    System.out.println("+ - * /");
    switch (op) {
      case '+':
        result = val1 + val2;
        break;
      case '-':
        if (val1 > val2) {
          result = val1 - val2;
        } else {
          result = val2 - val1;
        }
        break;
      case '*':
        result = val1 * val2;
        break;
      case '/':
        if (val2 == 0) {
          System.out.println("Please enter a value other than 0");
          System.exit(0);
        } else {
          result = val1 / val2;
        }
        break;
      default:
        System.out.println("Wrong input,program terminated");
        System.exit(0);
    }
    System.out.println(result);
  }
}

Answer: + - * /
21.0

  1. The first line declares Conditional, the class containing this program. The second opens main, the method to invoke to run these statements.
  2. The double declaration supplies the two operands and initialises result to zero. The char declaration supplies the division choice.
  3. The first output line displays the available operator symbols. The switch examines op, whose value is the division character.
  4. The addition label contains an addition assignment and break. The subtraction label contains a comparison, one of two subtraction assignments, and break. Both cases are skipped for this choice.
  5. The multiplication label contains a multiplication assignment and break. It is also skipped.
  6. The division label matches. Its nested if checks whether val2 equals zero. The test is false because val2 is 4, so the message and termination call in that block are skipped.
  7. The inner else assigns 84 / 4 to result. With double operands, the result displayed is 21.0. The following break exits the switch.
  8. The default output and termination call are skipped because division matched and the selected path reached break. The final output line displays result.
  9. The final two closing braces end the main method and the class. Braces within the method close the decision blocks shown above.

For an interactive version, Scanner is a Java class used to read input. Its nextDouble() method reads a double value. The expression next().charAt(0) reads the next token, a whitespace-delimited input item, and takes its first character; index 0 denotes the first position.

Replace the fixed initial values with the values read from the user, while preserving the same menu rules and validation. A single selection does not automatically redisplay a menu. Repeating the menu would require a separate repetition structure, beyond the single decision illustrated here.

How do break and System.exit(0) differ?

Program termination means ending the running program. The call System.exit(0) requests termination of the Java virtual machine, the runtime that executes the Java program. The argument 0 is a status value conventionally used to indicate normal termination; it is not text to display.

Property: A break transfers control beyond the switch

Rule: In these switch programs, break leaves the switch and allows execution to continue afterwards. System.exit(0) terminates the running program in normal use, so the later output statement is not reached.

Why does the location of the exit call matter?

In the calculator, the termination call is inside the zero-divisor block. It is reached only if division was chosen and the second value equals zero. Choosing division alone does not terminate the program: the inner condition must also select that path.

After a valid operation, break reaches the statement that displays result. For the zero-divisor and invalid-operator paths, termination prevents that shared statement from displaying the initial result as though it were a successful calculation. This control-flow difference is separate from the wording of the error message.

InstructionEffect hereLater result output
break;Leaves the selected switchCan be reached
System.exit(0);Terminates the running programIs not reached after normal termination
System.out.println(result);Displays the stored resultDoes not itself terminate execution

Printing a message that says a program has terminated does not itself cause termination. The method call, not the wording of a string, changes execution. Likewise, a comment describing an intended action cannot substitute for the statement that performs that action.

How should a conditional program be traced and checked?

A dry run is a manual trace of a program using stated inputs. Follow executed statements, keeping track of current variable values and output. Do not evaluate every condition in the listing when the chosen path skips some of them.

Which steps make a trace reliable?

  1. Record the supplied starting values and the meaning of each variable. If input is read, record the exact supplied input.
  2. Perform each reached assignment before using that variable in a later condition. Assignment can change which branch is selected.
  3. Write true or false for each reached test, and identify the corresponding selected block. Skip the statements on the other path.
  4. For a switch, identify the matching entry label or default, then follow statements until a break, termination call or the end of the switch.
  5. Copy each reached output in its actual order. Separate messages printed on different lines and omit messages in skipped blocks.

Check boundary cases, especially equality. A strict greater-than test excludes equality, while greater-than-or-equal-to includes it. For a ladder, check that every required category has a path. For a nested decision, check the false path of the outer condition as well as the inner alternatives.

A syntax error breaks the language rules and prevents successful compilation, the translation process that checks and prepares source code. A logical error can remain in code that compiles: a wrong comparison, misplaced statement or unintended fall-through may produce an incorrect answer.

Braces should reflect the intended controlled blocks. Review every else association, every case colon and every break. Check that variables have usable values before a reached output or calculation. In the difference program, both alternative assignments supply diff before its shared output line.

Finally, distinguish what the program actually does from what its messages claim. Check the operations and conditions themselves. A comparison message can be misleading for an unhandled equality case, and a termination message alone does not stop the execution of later statements.

Glossary

  • Flow of control — The order in which the statements of a program are executed.
  • Condition — An expression whose true or false result guides a programming decision.
  • Boolean — A type of value having exactly two possibilities, true and false.
  • Block — A group of Java statements enclosed together within a pair of curly braces.
  • Branch — One possible path followed during execution of a conditional programming structure.
  • If-else statement — A selection structure providing alternatives for the true and false results of a condition.
  • Else-if ladder — A linked sequence of conditional tests that selects the first true alternative.
  • Nested if — An if statement placed within a controlled part of another decision structure.
  • Selector — The expression whose value is matched against case labels in a switch statement.
  • Case label — A marker identifying a value at which execution can enter a switch.
  • Default — The switch label providing an entry point when no case value matches.
  • Fall-through — Continuation into following labelled switch statements when no intervening control transfer stops execution.
  • Break — A statement that leaves the enclosing switch in the programs discussed here.
  • Menu-driven program — A program that performs an operation according to a choice from available options.
  • Dry run — A manual trace that records variable values, decisions and output for stated inputs.

Common errors and misconceptions

  • Misconception: A false if condition ends the whole program. Correct: It skips the controlled true branch; execution follows the false alternative, if present, and can continue afterwards.
  • Misconception: = and == perform the same task. Correct: = assigns a value, while == tests equality; use a Boolean expression for an if condition.
  • Misconception: Indentation groups Java statements. Correct: Braces group statements into blocks. Indentation helps readers recognise the structure but cannot replace the required braces.
  • Misconception: Every true condition in a ladder executes its block. Correct: The first true condition selects its block and skips the remaining alternatives in that ladder.
  • Misconception: Every case label stops the preceding case. Correct: Execution can fall through to later labelled statements unless break or another control transfer prevents it.
  • Misconception: Default is reached only when no case matches. Correct: It can also be reached through fall-through from an earlier matching case.
  • Misconception: break terminates the entire application. Correct: In these examples it leaves the switch. System.exit(0) is the program termination call.
  • Misconception: Printing a termination message stops execution. Correct: A printed message is output; an actual termination statement or other control transfer is needed to change execution.

Exam-style questions with model answers

Q1. Distinguish the roles of = and == in Java. [2 marks]
  1. The assignment operator = stores the value of the expression on its right in the variable on its left.
  2. The equality operator == compares its operands and produces a Boolean result, true or false.
Q2. An integer Num starts at 6. The program executes Num = Num + 1; then if (Num > 5) { System.out.println(Num); }. State the updated value, condition result and output. [3 marks]
  1. The assignment evaluates Num + 1 using the original value 6. It stores 7 in Num before the condition is reached.
  2. The comparison uses the updated value, so it evaluates 7 > 5. This is true and selects the controlled output statement.
  3. The statement displays 7 on one line. There is no alternative output in the supplied code.
Q3. Given int number = 0; and the ladder if (number > 0) print "Number is positive"; else if (number < 0) print "Number is negative"; else print "Number is zero", explain both tests and the output. [3 marks]
  1. The first condition tests whether number is greater than zero. With number equal to 0, the condition is false and its message is skipped.
  2. The next condition tests whether number is less than zero. This is also false, so its negative message is skipped as well.
  3. The final else executes because both earlier conditions are false. The output is Number is zero.
Q4. Trace this complete decision: int Number1 = 7, Number2 = 8; if (Number1 > 0 || Number2 > 5) { if (Number1 > 7) { System.out.println("Code Worked"); } else { System.out.println("Code MightWork"); } } else { System.out.println("Code will not Work"); }. Give the outer result, inner result, selected branch and output. [4 marks]
  1. The outer OR condition is true because Number1 is 7 and 7 > 0 is true, so execution enters its controlled block.
  2. The inner condition then compares Number1 with 7. The expression 7 > 7 is false because equality does not satisfy a strict greater-than comparison.
  3. The inner else is selected. The outer else is skipped because the outer condition was true.
  4. The only output is Code MightWork, followed by a new line. Neither of the other two messages is printed.
Q5. Trace this switch and explain the entry, fall-through, stopping point and complete output: int Number = 20; switch (Number) { case 10: System.out.println("Ten Thousand"); break; case 20: System.out.println("Twenty Thousand"); case 30: System.out.println("Thirty Thousand"); break; default: System.out.println("Not enough!!!"); }. [5 marks]
  1. The selector Number has the supplied value 20. Matching therefore selects the case 20 entry point; the earlier case 10 output is skipped.
  2. The first statement reached after entry prints Twenty Thousand. This becomes the first output line because System.out.println starts a new line afterwards.
  3. There is no break after that output. Execution therefore continues past the case 30 label without requiring the selector to equal 30.
  4. The next output statement prints Thirty Thousand as the second line. The break following it leaves the switch and prevents the default output.
  5. The complete output consists of Twenty Thousand followed by Thirty Thousand on separate lines. Number remains 20; fall-through did not assign it a new value.
Q6. A calculator has double val1 = 84, val2 = 4, result = 0; and char op = '/'. It switches on op. The division case executes if (val2 == 0) { System.out.println("Please enter a value other than 0"); System.exit(0); } else { result = val1 / val2; } followed by break. After the switch it executes System.out.println(result). Other cases end in break. Explain the selected path, test, calculation, break and output. [5 marks]
  1. The selector op contains the division character, so execution enters the division case. The other case operations are not selected for this supplied choice.
  2. The nested condition compares val2 with zero. Since val2 is 4, the comparison is false, and the zero-divisor message and System.exit(0) call are skipped.
  3. The else block calculates val1 / val2 using the double values 84 and 4. It assigns the resulting value 21.0 to result.
  4. The break statement then exits the switch. It does not terminate the entire program, so the statement following the switch can still be reached.
  5. The final System.out.println statement displays 21.0 on a line. The initial value zero has been replaced by the selected calculation before this output occurs.
Q7. Explain one difference between break inside a switch and System.exit(0). State whether a statement after the switch can execute in each case. [2 marks]
  1. A break inside the switch leaves that switch, so execution can continue with a following statement.
  2. System.exit(0) terminates the running program in normal use, so the following statement is not reached after termination.

Key takeaways

  • A Java if condition produces a Boolean result, which selects whether its controlled statement or block executes.
  • An if-else statement supplies two alternatives; a false result selects else rather than ending the program.
  • An else-if ladder tests conditions in order and skips later alternatives after selecting the first true condition.
  • A nested if is reached through an outer branch, so trace the outer decision before any inner test.
  • A switch selects an entry label; subsequent execution depends on statement order and control transfers such as break.
  • Missing break statements can cause fall-through, including execution of default after an earlier case has matched.
  • A menu needs a defined choice and operation rules, including handling for unmatched choices and invalid operands.
  • A reliable dry run records current values, reached conditions, selected branches and each output line in its actual order.

Test yourself

What kind of result must an if condition produce?

It must produce a Boolean result, meaning either true or false.

Does a final else need its own condition?

No. It handles the false outcome left by the preceding linked condition or conditions.

What happens after the first true test in an else-if ladder?

Its controlled block executes, and the remaining alternatives in that ladder are skipped.

What must happen before an inner if can be tested?

Execution must reach the outer branch containing that inner if statement.

Which punctuation groups multiple Java statements into a block?

A matching pair of curly braces groups the statements into a block.

Can default execute after a case value has matched?

Yes. Fall-through can carry execution from an earlier case into the default statements.

Does break inside a switch print or terminate the program?

Neither. It leaves that switch and allows execution to continue afterwards.

Why should equality be checked when tracing a comparison?

A strict comparison excludes equality, while a comparison including equals treats that boundary differently.