Overview
This unit introduces conditional statements in Java: how programs make decisions and choose different actions based on conditions. Students learn boolean expressions, relational and logical operators, and how to write if, if-else, nested if, if-else-if ladder, and switch statements. The unit explains how to compare numbers, characters and strings, and how to combine multiple conditions using &&, || and !. It also covers good style, avoiding common errors (such as using = instead of ==), and simple debugging techniques. Conditional statements are essential because they let programs react to user input, validate data, control program flow and implement real-world rules. By the end of the unit, students will be able to design small decision-making programs like grade calculators, number classifiers, and menu-driven choices. This foundation prepares learners for loops, functions and object-oriented programming that follow in later studies.
Learning Objectives
- Understand and explain the purpose of conditional statements in controlling program flow.
- Construct boolean expressions using relational and logical operators to form conditions.
- Write correct Java syntax for if, if-else, nested if, if-else-if ladder, and switch statements.
- Use string and character comparison correctly in conditional statements.
- Combine multiple conditions using logical AND, OR and NOT operators to form complex tests.
- Identify and correct common mistakes in conditional code, such as assignment vs comparison.
- Trace and predict the output of programs that use conditional statements.
- Design and implement small programs that use decision-making to solve problems.
Topics in this chapter
18 topics · tap a topic title to jump straight to it.
Introduction to Decision Making and Booleans
What is decision making?
Decision making in programming means asking questions about data and then letting the program take different actions depending on the answer. These questions are written as boolean expressions — expressions that evaluate to either true or false. Decision making is essential because most useful programs must react to conditions: validate inputs, choose options from a menu, respond to user requests, and map real-world rules into code.
Boolean values and type
Java uses the primitive type boolean which can hold true or false. A boolean value may be the result of a direct assignment, e.g., boolean valid = true; or the result of a comparison like (age >= 18). Booleans are used by conditional statements to decide which statements to execute next.
Relational operators
Relational operators compare primitive values and produce boolean results. The common operators are == (equal), != (not equal), <, >, <= and >=. For example, (x > 0) checks whether x is positive, while (a == b) checks exact equality for primitive types. These operators are the building blocks of conditions.
How conditions control flow
When a conditional statement runs, Java evaluates the boolean expression inside parentheses. If the result is true, the statements in the true-branch execute; if false, they are skipped or the false-branch runs if present. This creates branching in the program flow. On paper we draw this as a decision diamond with two arrows: true and false.
Comparing different kinds of data
Numeric types, characters and booleans use relational operators directly. Strings are objects; to compare their textual content we use methods like equals() rather than ==. We will study string comparison carefully in a later topic.
Why this matters for students
Understanding booleans and decision making enables you to write programs that make choices. Simple examples — checking even or odd numbers, printing pass or fail, or selecting menu operations — all rely on these ideas. Learning to form correct and readable conditions also prepares you for loops and functions later on.
Best practices
Keep conditions clear: prefer descriptive variable names and use parentheses when combining logical operators. Initialize boolean variables explicitly, and avoid confusing assignments inside conditions. Use comments where a condition implements a rule that may not be obvious to a reader. These habits reduce bugs and make your programs easier to understand.
- Example 1: int a = 5; boolean check = (a > 0); // true because 5 is positive
- Example 2: boolean passed = (marks >= 35); // true when marks are 35 or more
- Example 3: boolean match = name.equals("Asha"); // true when name text equals "Asha"
- Relational operators: ==, !=, <, >, <=, >=
- Boolean values: true, false
- String comparison: s.equals(t) returns a boolean
if Statement
Purpose and basic idea
The if statement allows a program to execute a block of code only when a given condition is true. It is the simplest decision-making construct. Use it when there is a single action to perform if the condition holds and nothing specific to do otherwise. An if statement evaluates its condition once and decides whether to run the following statements.
Syntax of if
The general form is: if (condition) { statements; } The condition must be a boolean expression. The statements inside the braces form the true-branch. If the condition is false, those statements are skipped and the program continues after the block.
Examples of conditions
Conditions can compare numbers, characters or booleans. For example: if (age >= 18) { System.out.println("You are eligible"); } Here the message prints only when age is 18 or more. You can also use boolean variables directly: if (isLoggedIn) { showMenu(); }.
Single statement form and braces
If you write a single statement after the if, braces are optional but it is good practice to include them because they prevent bugs when you later add more statements. For example: if (x > 0) System.out.println("Positive"); is correct, but adding another line without braces will change behavior unintentionally.
Evaluating complex conditions
If a condition uses logical operators like && and ||, Java evaluates boolean expressions according to precedence and short-circuit rules. If (a > 0 && b / a > 2) is safe if you know a is not zero or if you arrange the check to avoid division by zero using short-circuiting: if (a != 0 && b / a > 2) the second part is evaluated only when a != 0 is true.
Common mistakes to avoid
A frequent error is accidentally using assignment (=) instead of comparison (==) in languages where assignment returns a value; in Java this usually results in a compile error when types do not match, but avoid confusion by always writing comparisons clearly. Another error is placing a semicolon immediately after the if header: if (x > 0); { ... } which makes the if apply to an empty statement and the block always run. Keep conditions readable and tested with several inputs including boundary values.
When to use if
Use if for simple checks where only one scenario requires an action. When you need two alternative actions, use if-else. When you need multiple alternatives, consider an if-else-if ladder or switch where appropriate.
- Example 1: if (temperature > 37) { System.out.println("Fever"); } prints only for fever condition.
- Example 2: if (age >= 18) { System.out.println("Adult"); } checks adulthood.
- Example 3: if (isOpen) { closeDoor(); } uses a boolean flag directly for a decision.
- if (condition) { statements; }
if-else Statement
Two-way decision
The if-else statement gives two possible paths: a block that runs when the condition is true and another block that runs when it is false. This is useful for binary choices such as pass/fail, positive/negative, or authenticated/unauthenticated. The structure ensures exactly one of the two branches executes.
Syntax and behavior
The form is: if (condition) { // true-branch } else { // false-branch } Java evaluates the condition; if it is true, the true-branch executes and the else is skipped. If false, the else branch executes. After either branch finishes, control continues at the statement after the if-else.
Examples of use
Common uses include checking input validity and responding accordingly: if (marks >= 35) { System.out.println("Pass"); } else { System.out.println("Fail"); } Another example is role-based access: if (isAdmin) { showAdminMenu(); } else { showUserMenu(); }.
Braces and multiple statements
Always use braces for both branches even if they contain a single statement. This avoids errors when adding further lines later. Example: if (x % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); }.
Logical complexity
The condition inside if can be a compound boolean expression. Use parentheses to make precedence explicit: if ((a > b) && (c < d || e == f)) { ... } For readability, break complex tests into boolean variables with descriptive names: boolean eligible = (age >= 18 && hasID); if (eligible) { ... } else { ... }.
Error examples
Misplaced semicolons or braces can change program flow. For example, if (x > 0); { System.out.println(x); } will print x regardless of the condition because the semicolon terminates the if. Also, avoid repeating expensive computations inside both branches; compute once and reuse results stored in variables.
When to prefer if-else
Use if-else when there are exactly two mutually exclusive actions. If there are more than two distinct outcomes, an if-else-if ladder or switch may be clearer. Keep branches short and focused to aid understanding and marking in exams.
- Example 1: if (n % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); }
- Example 2: if (password.equals(input)) { System.out.println("Welcome"); } else { System.out.println("Try again"); }
- if (condition) { statements-if-true; } else { statements-if-false; }
if-else-if Ladder (Multiple Choices)
Handling many choices
When more than two outcomes are possible, an if-else-if ladder allows a sequence of tests. Each condition is checked in order, and as soon as a true condition is found its block executes and the rest are skipped. This structure is useful for grading, age groups, or mapping numeric ranges to labels.
Syntax and evaluation order
if (cond1) { // action1 } else if (cond2) { // action2 } else if (cond3) { // action3 } else { // default action } Conditions are evaluated from top to bottom. If cond1 is true, action1 runs and the ladder ends. If none are true, the optional else provides a default. Because the first true branch runs, order matters: place the most specific or highest-priority conditions first to avoid misclassification.
Designing correct ranges
When using numeric ranges, ensure ranges are non-overlapping and cover all expected values. For example, for grades, use descending checks: if (marks >= 90) grade = 'A'; else if (marks >= 75) grade = 'B'; else if (marks >= 60) grade = 'C'; else if (marks >= 35) grade = 'D'; else grade = 'F'; This avoids gaps and overlaps because each check assumes the earlier ones have failed.
Common mistakes
A common error is to use separate if statements instead of else if. Separate ifs are all checked independently and could allow multiple blocks to run. Also watch boundary conditions: test values exactly on limits to ensure they fall into the intended branch. Use >= or <= consistently to include boundary values deliberately.
Readability and maintenance
Keep each branch short and use comments for complex rules. If the ladder grows very long, consider other designs: switch for equality-based choices, arrays or maps for lookups, or methods to encapsulate rules. For exam programs, a clear if-else-if ladder with correct boundaries and a default else is usually the expected solution.
When to use
Use an if-else-if ladder when the tests are different comparisons or ranges and when each case requires distinct code. For many equality checks based on a single variable, switch may be cleaner. For ranges or complex conditions, if-else-if is flexible and readable when used carefully.
- Example 1: Grade calculator using mark ranges to assign grades A, B, C or F.
- Example 2: if (x > 0) {...} else if (x == 0) {...} else {...} to classify positive, zero or negative.
- if (cond1) { } else if (cond2) { } ... else { }
Nested if Statements
Concept of nesting
Nested if means placing an if (or if-else) inside another if or else block. This lets you make a secondary decision only when the first condition meets a certain requirement. Nesting models hierarchical rules: for example, only if a student attended enough classes do we then check marks to decide eligibility.
Structure and clarity
Example structure: if (outerCondition) { if (innerCondition) { // actions for both true } else { // actions for outer true but inner false } } else { // actions for outer false } Here, innerCondition is checked only when outerCondition is true. This reduces needless checks and organizes dependent logic.
When to nest versus combine
If two conditions are independent, combine them using logical operators: if (outerCondition && innerCondition) { ... } This flattens the code and is often simpler. Nesting makes sense when the second check should occur only in the context of the first or when the inner test needs local values computed within the outer block.
Examples and use cases
1) Membership and purchase amount: if (isMember) { if (amount > 1000) applyExtraDiscount(); else applyBasicDiscount(); } 2) Exam eligibility: if (attendance >= 75) { if (marks >= 35) pass = true; else pass = false; } else { System.out.println("Not eligible due to low attendance"); }
Readability tips
Avoid deep nesting — more than two or three levels becomes hard to read. Use descriptive variable names and comments to explain nested logic. When nested blocks are long, extract inner logic into separate methods with meaningful names. Proper indentation and braces are essential to show block boundaries and prevent logic errors.
Common pitfalls
Misplacing braces or indenting poorly leads to bugs where statements belong to the wrong block. Also, ensure the inner condition's variables are in scope. Test nested code with cases that exercise each branch, including the scenarios where the outer condition is false so the inner code is never reached.
- Example 1: if (isMember) { if (amount > 1000) { discount = 10; } else { discount = 5; } }
- Example 2: if (age >= 18) { if (hasID) { allowEntry(); } else { deny(); } } else { deny(); }
switch Statement
Purpose and advantages
switch provides a clean, readable way to select one of many possible actions based on the value of a single expression. It is often clearer than a long if-else-if ladder when many branches depend on equality checks against simple constant values such as numbers or strings. The switch statement directs control flow to the matching case and keeps related choices grouped together.
Syntax and components
Basic form: switch (expression) { case value1: statements; break; case value2: statements; break; ... default: statements; } The expression is evaluated and compared to the case labels. When a match is found, execution enters that case. break causes immediate exit from the switch; without break execution continues into the next case (fall-through). default handles cases when no label matches, similar to else.
Allowed types
In Java for class 9 use, switch works with int, byte, short, char and String (since Java 7). It does not accept boolean or long directly. Choose switch when the variable being tested is compared against fixed constants rather than ranges or complex conditions.
Fall-through behavior
Fall-through happens when break is omitted: control continues executing the next case statements regardless of the next case label. This can be used intentionally to group multiple labels leading to the same code: case 'A': case 'E': // both vowels case 'I': doVowelWork(); break; But if unintentional, fall-through creates bugs where multiple case blocks run unexpectedly.
When to use default and breaks
Always include a default to handle unexpected values — this helps with input validation. Use break after each case unless you intentionally want fall-through. Keep case blocks short and avoid complex logic; if a case must perform many steps, consider calling a separate method to keep the switch tidy.
Examples and exam expectations
Exam questions often require a switch-based menu or mapping numbers to day names. They expect correct use of case labels, break statements, and a default. For grouped behavior, show intentional fall-through with a comment so readers understand the design. Use switch for clarity when testing one variable against many constants.
- Example 1: Menu selection: switch(choice) { case 1: showBalance(); break; case 2: withdraw(); break; default: System.out.println("Invalid choice"); }
- Example 2: Vowel check: switch(letter) { case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("Vowel"); break; default: System.out.println("Consonant"); }
- switch(expression) { case constant: statements; break; ... default: statements; }
Logical Operators: &&, ||, !
Combining boolean expressions
Logical operators let you join simple boolean expressions into more complex tests. The three main boolean operators are AND (&&), OR (||) and NOT (!). Understanding how they work and how Java evaluates them is essential to write correct and efficient conditions.
AND (&&)
The expression (A && B) is true only when both A and B are true. Use && when multiple conditions must all hold. Example: if (age >= 18 && hasID) { allowEntry(); } Here entry is allowed only if both age check and ID check succeed.
OR (||)
The expression (A || B) is true when at least one of A or B is true. Use || when several alternative conditions are acceptable. Example: if (day == 6 || day == 7) weekend = true; This sets weekend true for either Saturday or Sunday.
NOT (!)
NOT reverses the boolean value: !A is true when A is false. It is helpful to express negative conditions concisely: if (!isValid) { reportError(); } You can also apply it to boolean variables to check the opposite state.
Short-circuit evaluation
Java uses short-circuit logic for && and ||. For (A && B), if A is false, B is not evaluated because the whole expression cannot be true. For (A || B), if A is true, B is not evaluated. Short-circuiting can prevent errors (for example, checking for null or zero before accessing array elements or dividing) and can save time by avoiding unnecessary computations. For example: if (x != 0 && y / x > 2) avoids division by zero because y/x is evaluated only when x != 0.
Precedence and grouping
NOT has higher precedence than AND, which has higher precedence than OR. Use parentheses to clarify combined tests and to ensure correct order of evaluation: if ((A && B) || C) { ... } is clearer than relying on precedence rules alone. When expressions get complex, assign sub-expressions to well-named boolean variables for readability.
Common pitfalls
A common mistake is using single & or | with booleans. Single & and | perform non-short-circuit logical operations (and bitwise operations on numeric types). Prefer && and || for boolean logic because short-circuiting often prevents errors and improves performance. Also, avoid building conditions that are hard to read; break them into named parts when needed.
- Example 1: if (marks >= 35 && attendance >= 75) pass = true;
- Example 2: if (isAdmin || isManager) allowEdit();
- Example 3: if (!(password.equals("abc"))) deny();
- AND: A && B is true when A and B are true
- OR: A || B is true when at least one is true
- NOT: !A is true when A is false
Comparison of Strings and Characters
Comparing characters
Characters (char) in Java are primitive types representing Unicode code points. Comparing chars with relational operators works because Java uses numeric Unicode values under the hood: 'a' < 'b' is true. This is useful when you want to check ordering or ranges on characters.
Comparing strings correctly
Strings are objects, not primitive values. The == operator checks whether two variables refer to the exact same String object in memory (reference equality), which is not the same as the content being the same. To compare the textual content you must use the equals() method: if (s.equals(t)) then s and t have the same characters in the same order. Relying on == may give surprising results since two distinct String objects can contain identical text.
Case sensitivity and ignoring case
equals() is case-sensitive: "Java".equals("java") returns false. To compare ignoring case differences use equalsIgnoreCase(): if (s.equalsIgnoreCase("yes")) { ... } This is handy for user input where letter case should not matter.
Using compareTo for ordering
The compareTo method returns an integer: negative if s comes before t lexicographically, zero if equal, and positive if s comes after t. For class 9, you typically use equals and equalsIgnoreCase, and reserve compareTo for when you need to sort or order strings.
Common mistakes
Students often write if (s == "hello") expecting content comparison. This is incorrect and unreliable. Always use s.equals("hello") for content checks. Also check for null before calling equals on a variable that might be null: if (s != null && s.equals("text")) to avoid NullPointerException. Alternatively, call equals on the constant: "text".equals(s) which is safe when s may be null.
Practical examples and exam tips
Use equalsIgnoreCase for flexible user input checks like yes/no answers. When checking a single character input read as a String, you can use charAt(0) to extract the char and compare with 'a' or 'A' as needed. In exams, demonstrate correct string comparison and mention null-safety if relevant.
- Example 1: if (ch == 'A') ... checks a character
- Example 2: if (input.equals("exit")) quit(); // correct string check
- Example 3: if (name.equalsIgnoreCase("ram")) greet();
- String equality: s.equals(t)
- Case-insensitive: s.equalsIgnoreCase(t)
- Character comparison: 'a' < 'b' is true
Common Errors and Debugging
Types of errors
Programming errors fall into three categories: syntax errors (compile-time), runtime errors (exceptions during execution) and logical errors (program runs but gives wrong result). Conditional statements commonly produce logical errors when conditions are written incorrectly, or runtime errors when expressions inside conditions cause exceptions (e.g., division by zero).
Syntax errors in conditionals
Missing parentheses or braces, misplaced semicolons, and misspelt keywords cause compile-time errors. For example, writing if x > 0 { ... } instead of if (x > 0) { ... } will not compile. Read compiler messages carefully and correct the line number and token indicated; often a missing brace earlier in the file causes many subsequent errors.
Logical mistakes
Logical errors include wrong comparison operators, incorrect boundary tests and improper use of independent ifs instead of else-if leading to multiple branches executing. Examples: using if (marks > 60) ... if (marks > 80) ... will misclassify marks because both may execute for marks above 80. Use else-if to ensure mutual exclusion or order conditions correctly.
Operator misuse
Using single & or | instead of && or || can change behavior because single operators do not short-circuit; they evaluate both operands always. This may cause runtime errors if the second operand assumes the first is true or non-null. Prefer && and || for boolean logic.
String comparison bugs
Using == to compare strings often gives incorrect results. Always use equals() or equalsIgnoreCase(). Also check for null before calling methods on a string variable to avoid NullPointerException.
Debugging techniques
1) Trace on paper: follow each step and evaluate conditions manually for example inputs. 2) Insert print statements to display variable values and branch entries (System.out.println). 3) Test boundary cases and invalid inputs. 4) Use an IDE debugger (step into/over, watch variables) when available. For Class 9, learning to read error messages and add println traces is usually sufficient.
Prevention strategies
Write clear conditions, initialize variables, use parentheses for precedence, and keep blocks small. Add comments describing non-obvious rules. Write small tests for each branch and re-run after changes. Proper design and careful testing reduce debugging time and improve code quality.
- Example 1: Off-by-one: if (i <= n) vs if (i < n) causes loop/condition differences; test boundary values.
- Example 2: Using == for strings leads to unexpected false results; use equals().
- Example 3: if (x > 0 && y / x > 1) safe due to short-circuit; otherwise may divide by zero.
Operator Precedence and Parentheses
Why precedence matters
When a condition combines arithmetic, relational and logical operators, Java evaluates parts in a fixed order called operator precedence. If you do not control this order with parentheses, you may get unexpected results. Understanding precedence helps avoid subtle bugs and makes expressions easier to reason about.
Typical precedence groups
At a high level: parentheses ( ) have the highest precedence and force evaluation order. Then unary operators like ! and unary +/-. Multiplicative operators (*, /, %) come next, followed by additive (+, -). Relational operators (<, >, <=, >=) are after arithmetic, then equality operators (==, !=), then logical AND (&&), and logical OR (||) last. Within the same precedence group, evaluation is left to right for most operators.
Examples showing effects
1) if (a + b > c) compares the sum because + is evaluated before >. 2) if (!flag && x > 0) applies ! to flag before &&, so the condition is clear. 3) Complex example: if (a > b && c < d || e == f) is parsed as ((a > b && c < d) || e == f) because && has higher precedence than ||. Adding parentheses clarifies intent: if ((a > b && c < d) || (e == f)).
Use parentheses liberally
Even when you know precedence rules, parentheses improve readability and guard against mistakes. Use them to group related conditions, especially when mixing && and ||. Parentheses also control evaluation order affecting short-circuit behavior: if ((x != 0) && (y / x > 2)) ensures x!=0 is checked before dividing y by x, thus preventing division by zero.
Refactoring complex expressions
If an expression becomes hard to read, compute sub-parts in well-named boolean variables: boolean validAge = (age >= 18); boolean paidFees = (feePaid == true); if (validAge && paidFees) { ... } This makes the logic easier to understand and test, and eliminates precedence confusion.
Exam advice
In answers, use parentheses to show the intended grouping. When tracing code on paper, apply precedence rules step by step or add parentheses to make the order explicit. Clear expressions are less likely to produce errors and earn full marks in practical exams.
- Example 1: if (a + b > c) compares sum correctly because + runs before >.
- Example 2: if (!flag && x > 0) ! has higher precedence so it applies to flag first.
- Example 3: Use parentheses: if ((x > y) || (z < w && t == u))
Ternary Operator (?:)
What the ternary operator does
The ternary operator ?: is a compact way to write a simple if-else that chooses between two values. It evaluates a condition and then yields one of two expressions according to whether the condition is true or false. Because it is an expression, it can be used where a value is required, such as in assignments or method arguments.
Syntax and behavior
General form: condition ? valueIfTrue : valueIfFalse. Java first evaluates the condition; if it is true, the operator returns valueIfTrue; otherwise it returns valueIfFalse. Both value expressions must be compatible types so the entire ternary expression has a single type that the compiler can determine.
Common uses
Use the ternary operator to assign values concisely: int max = (a > b) ? a : b; String result = (marks >= 35) ? "Pass" : "Fail"; It is useful in print statements as well: System.out.println((n % 2 == 0) ? "Even" : "Odd"); For simple conditional choices it reduces lines and can make code compact.
Readability and limitations
Keep ternary expressions simple. Nesting ternary operators makes code hard to read and should be avoided. If the branches require multiple statements or complex logic, prefer a full if-else. Because ternary returns a value, it cannot replace statements that perform actions rather than compute values unless you call methods in the result expressions.
Type rules and conversions
If valueIfTrue and valueIfFalse are of different types, Java will attempt to find a common type or apply conversions; this can be confusing, so keep the two results of the same type or cast explicitly. For example, mixing int and double will yield a double value overall.
Examples and exam usage
Exam questions may ask for a short expression to choose between two values; the ternary operator shows concise thinking. Show simple, single-level uses in answers, and avoid nesting without a clear reason. Use parentheses when the ternary is part of a larger expression to avoid ambiguity.
- Example 1: int abs = (x < 0) ? -x : x;
- Example 2: String sign = (n > 0) ? "positive" : (n == 0) ? "zero" : "negative"; // prefer avoiding nesting
- condition ? valueIfTrue : valueIfFalse
Decision Making with Input and Output
Reading user input and making decisions
Most practical programs read input from users and then perform decisions based on that input. In Java you commonly use Scanner (java.util.Scanner) to read numbers and text from the console. After reading, always validate inputs before using them in calculations or comparisons. Clear prompts and helpful error messages improve user experience and prevent invalid data from causing wrong results or exceptions.
Input validation
Validation checks ensure inputs lie within expected ranges. For example, marks should be between 0 and 100; age should be positive. Use if or if-else to test these ranges and print an "Invalid input" message if the data is out of bounds. Early validation avoids cascading errors later in the program. For numeric division ensure denominators are not zero before dividing.
Using conditionals after input
A common pattern: prompt the user, read values, validate them, and then use if/if-else/ switch to choose the right action. For example, read marks and then apply an if-else-if ladder to assign grades. For menu-driven programs read the user's menu choice and route with switch or if-else to the appropriate action.
Handling bad types
If a user types text when an integer is expected, Scanner.nextInt() throws InputMismatchException. For class 9, the usual approach is to instruct the user to enter correct types. In more advanced code you catch exceptions and prompt again; this will be taught later. For exams, demonstrate correct use of Scanner and show simple validation checks.
Examples and prompts
Example interactive flow: System.out.print("Enter marks: "); int marks = sc.nextInt(); if (marks < 0 || marks > 100) { System.out.println("Invalid marks"); } else { // classify grade } Always print clear prompts like "Enter your choice (1-4):" and user-friendly messages like "Choice not recognized" when input is outside expected range.
Testing input-based programs
Test with valid, boundary and invalid inputs: e.g., 0, 35, 100, -1, 101, and non-numeric text. Manual tracing and sample runs help verify that all branches work and that the default or error messages appear when they should. This builds confidence and helps catch logic mistakes.
- Example 1: Read an integer and print if it is positive, negative or zero.
- Example 2: Menu using switch to call functions based on user choice 1-4 with default showing error.
Applications: Grade Calculator
Problem statement
The grade calculator reads a student's marks and outputs a grade according to fixed ranges. This task practices reading input, validating it, and using an if-else-if ladder to map numeric ranges to textual grades. It represents a typical board exam question that tests both logic and correct use of conditionals.
Design steps
1) Read marks as an integer. 2) Validate that marks are within 0 to 100; if not, print "Invalid marks". 3) If valid, use descending if-else-if checks to assign grades: highest ranges first ensures correct classification. For example: if (marks >= 90) grade = 'A'; else if (marks >= 75) grade = 'B'; else if (marks >= 60) grade = 'C'; else if (marks >= 35) grade = 'D'; else grade = 'F'. 4) Print the assigned grade.
Why descending order matters
Checking from highest to lowest avoids overlaps and misclassification. If you test marks >= 60 before marks >= 90, a mark like 95 would match >=60 first and be assigned the wrong grade. Using else-if ensures only one branch executes.
Edge cases to consider
Test boundary values: 90, 75, 60, 35 and also 0, 100. Also test invalid inputs like -5 and 120. If input might be non-integer, mention that reading with Scanner.nextInt() will fail on non-numeric input; for class 9 focus on correct integer inputs and validation of ranges.
Example code outline
Scanner sc = new Scanner(System.in); System.out.print("Enter marks: "); int marks = sc.nextInt(); if (marks < 0 || marks > 100) { System.out.println("Invalid marks"); } else if (marks >= 90) { System.out.println("A"); } else if (marks >= 75) { System.out.println("B"); } else if (marks >= 60) { System.out.println("C"); } else if (marks >= 35) { System.out.println("D"); } else { System.out.println("F"); }
Extensions
Later you can extend this program to compute overall percentage from multiple subjects and then grade the percentage. You can also count how many students obtained each grade by processing a list of marks using loops and arrays, topics which are taught after conditionals.
- Example 1: marks=88 -> prints B
- Example 2: marks=34 -> prints F
- Example 3: marks=101 -> prints Invalid marks
Applications: Number Classification (Even/Odd, Positive/Negative)
Purpose
Number classification tasks check basic understanding of arithmetic operators and conditionals. They include determining whether a number is even or odd and whether it is positive, negative or zero. These simple programs are often asked in exams to test boolean logic and modulo arithmetic.
Even and odd numbers
A number n is even if n % 2 == 0; otherwise it is odd. The modulo operator % gives the remainder after division. Note that negative even numbers still have remainder zero for % 2, for example (-4) % 2 == 0, so the same test works for negative numbers too.
Positive, negative or zero
Check sign using relational operators: if (n > 0) it is positive; else if (n == 0) it is zero; else it is negative. Check equality with zero separately before concluding negative to avoid classification errors. Order matters: test for zero explicitly if you write nested tests.
Combining properties
You may want to print both parity and sign. One approach: if (n == 0) print "Zero"; else { if (n % 2 == 0) print "Even" else print "Odd"; if (n > 0) print "Positive" else print "Negative"; } Or combine into a single formatted output like "Even and Positive". Use clear messages and line breaks to improve readability.
Handling input types
Ensure the input is an integer for parity tests. If the user inputs a non-integer, Scanner.nextInt() will cause an InputMismatchException; for Class 9, instruct the user to enter valid integers and show simple validation or exception handling later in advanced topics.
Testing
Try values 0, positive odd (7), positive even (8), negative odd (-5) and negative even (-12). Verify outputs for each case. Also test large values and the smallest negative to ensure the logic holds across the integer range.
- Example 1: n=5 -> Odd and Positive
- Example 2: n=0 -> Zero
- Example 3: n=-12 -> Even and Negative
Menu-Driven Programs
What is a menu-driven program?
A menu-driven program displays options to the user and performs actions based on the selected choice. This pattern is common in console applications and is a practical way to combine input reading, conditionals and simple modular design. It helps learners structure programs with multiple features in an organised way.
Design steps
1) Print a list of numbered choices with clear descriptions. 2) Prompt the user to enter a choice. 3) Read the choice and validate it. 4) Use switch or if-else to call the appropriate action for each choice. 5) Optionally loop back to the menu until the user chooses an exit option. For class 9, simple single-run menus without loops are often sufficient for exercises, but including a loop demonstrates completeness.
Using switch for menus
Switch is a natural fit for menus because each case corresponds to an option. Example: switch(choice) { case 1: addNumbers(); break; case 2: subtractNumbers(); break; case 3: System.exit(0); default: System.out.println("Invalid choice"); } Remember to include a default for invalid entries and to use break to prevent fall-through unless you intend to group cases.
Validating user choice
Check that the entered option falls within the expected range. If not, print an error and prompt again or exit. For simple exam tasks, printing "Invalid choice" is acceptable. Use Scanner to read integers; handle non-integer input carefully by instructing the user or by extending the program to catch exceptions.
User experience and clarity
Make menu options short and descriptive. After performing an action, show results and either return to the menu or exit according to the design. If you implement looping, give the user a clear exit option such as 0 or 4 marked as "Exit".
Examples and extensions
Typical menu programs include a small calculator, student record operations (add, display, search), or simple utilities. You can extend menus with method calls for each action to keep the main menu tidy. Later, when loops and functions are taught, menus become more powerful and reusable.
- Example 1: Calculator menu using switch with cases for add, subtract, multiply, divide and default for invalid input.
- Example 2: A menu to input student details, display them, or exit.
Boolean Variables and Flags
What are boolean flags?
Flags are boolean variables used to record a state or a condition discovered during program execution, such as whether a search found an item, whether a user is authenticated, or whether input was valid. Flags make programs easier to understand because they give meaningful names to conditions and can be checked later in the code.
Typical usage patterns
Initialize a flag to false before starting a search or a validation. While processing data set the flag to true when the target is found or a condition is met. After processing, check the flag to decide the next step: if (found) { System.out.println("Item found"); } else { System.out.println("Item not found"); } Flags simplify control flow and reduce repeated evaluations.
Advantages of using flags
Flags increase clarity: boolean isValid = (age >= 18 && hasID); is more readable than putting the full expression each time. Flags also avoid repeated computation if the same test would otherwise be evaluated multiple times. They are especially helpful in loops (when reading lists) to indicate if a condition ever occurred during iteration.
Proper initialization and resetting
Always initialize flags explicitly before use, for example boolean found = false;. If reusing a flag in repeated operations or loops, reset it appropriately so stale values don’t cause incorrect behavior. Uninitialized or leftover flags are a common source of bugs.
Naming conventions
Use clear, positive names like isFound, isValid, hasAccess instead of negative forms like notInvalid. Positive names read naturally in if statements: if (isValid) { ... } provides immediate understanding. Add small comments where the flag records a non-obvious condition.
Examples and exam relevance
Common textbook examples include searching for an element in an array and using a found flag, or validating multiple inputs and setting an allValid flag. In exams, using a flag with proper initialization and clear checks demonstrates structured thinking and earns marks for clarity and correctness.
- Example 1: boolean isPrime = true; set to false if a divisor is found during checking.
- Example 2: boolean authenticated = password.equals(input); if (authenticated) grant access; else deny;
Combining Conditionals with Arithmetic
Why combine arithmetic and conditionals?
Many decisions depend on computed values such as sums, averages, percentages or remainder checks. You must evaluate arithmetic expressions and then use conditionals to decide actions. Combining both correctly requires awareness of operator precedence, data types (integer vs floating point), and defensive checks such as avoiding division by zero.
Integer vs floating-point arithmetic
Integer division in Java truncates the fractional part. To compute percentages accurately cast values to double: double percent = (double) obtained / total * 100; If you forget the cast and both obtained and total are integers, the result will be truncated and comparisons may fail. Always pick the right type depending on whether fractional results are needed.
Ordering of operations
Use parentheses to enforce the intended arithmetic before applying comparisons: if ((obtained / (double) total) * 100 >= 35.0) { pass } ensures percentage is computed correctly before checking against the pass mark. Also, check for zero denominators: if (total != 0 && (obtained / (double) total) >= 0.35) { ... } Using short-circuiting avoids a division by zero error.
Practical examples
1) Calculating percentage and grading: compute percent then use an if-else-if ladder to determine grade. 2) Using modulo in conditions: if ((a + b) % 2 == 0) to check whether a sum is even. 3) Financial rules: compute tax amount and then decide whether extra surcharge applies if tax exceeds a threshold. Combine arithmetic with boolean logic to express compound business rules.
Testing arithmetic-based conditions
Test boundary and borderline cases: totals of zero, very large or negative values, and values exactly on thresholds. For percentage comparisons check values like exactly 35.0 or 34.999 to ensure your calculations and comparisons behave as expected. Use meaningful debug prints during testing to display intermediate computed values.
Exam tips
When writing code for exam answers show type casts where necessary, validate inputs that could cause runtime errors, and use parentheses to indicate the order of computation. Clear, correct arithmetic combined with conditionals demonstrates good programming practice and earns full credit.
- Example 1: percent calculation using casting to double to avoid integer division.
- Example 2: if ((a + b) % 2 == 0) System.out.println("Sum even");
Writing Clear Conditional Code and Comments
Clarity and maintainability
Conditional code should be easy to read, understand and maintain. Clear code reduces the chance of logic errors and makes it simpler for teachers, peers or future you to follow the program's intent. Use descriptive variable names, consistent formatting and brief comments for non-obvious rules.
Good naming
Choose names that state purpose: isEligible, hasPaidFees, totalMarks. A boolean variable named isValid reads naturally in conditions: if (isValid) { ... } Avoid single-letter names except for common loop indices; descriptive names improve readability and marking in exams.
Formatting and braces
Use consistent indentation and always include braces for if, else and switch cases even when blocks contain a single statement. Braces prevent errors when adding statements later. Put spaces around operators and after commas to make expressions legible. These small formatting choices make code look professional and are rewarded in practical assessments.
Comments and documentation
Add short comments before a complicated conditional explaining the rule, e.g., // Assign grade based on final percentage. Avoid commenting the obvious; instead document important design choices or tricky edge cases. Comments should clarify intent rather than restate code.
Refactoring long conditionals
If a conditional block grows large, extract parts into methods with descriptive names: boolean hasPassed(int marks) { return marks >= 35; } Then the caller reads: if (hasPassed(marks)) { ... } This improves modularity and hides details so the main flow remains clear. For class 9, showing this approach conceptually indicates good coding practice even if not required in simple programs.
Testing and sample inputs
Include example test cases in comments or a brief test plan to show how the code should behave. Test normal, boundary and invalid inputs. Remove debug print statements from final submissions; instead use meaningful output and error messages. Clear, well-commented and properly formatted conditional code scores higher in exams and is easier to debug and extend.
- Example 1: Use boolean isValid = (age >= 18 && hasID); if (isValid) // proceed
- Example 2: Comment: // Check valid marks before grading
Key Concepts
- Boolean
- A data type with two possible values: true or false.
- if statement
- A control structure that executes a block only when a condition is true.
- if-else statement
- A structure that executes one block if a condition is true and another block if it is false.
- if-else-if ladder
- A sequence of condition checks where the first true branch executes and the rest are skipped.
- switch statement
- A multi-way branch that selects a case based on the value of an expression.
- Logical AND (&&)
- An operator that returns true only if both operands are true.
- Logical OR (||)
- An operator that returns true if at least one operand is true.
- Logical NOT (!)
- An operator that inverts the boolean value of its operand.
- equals()
- A String method used to compare the textual content of two strings.
- equalsIgnoreCase()
- A String method that compares two strings ignoring letter case.
- Ternary operator
- A compact conditional expression of the form condition ? valueIfTrue : valueIfFalse.
- Short-circuit evaluation
- Evaluation of logical expressions where the second operand is not evaluated if the first determines the result.
- Fall-through
- Behavior in switch where execution continues into the next case if break is omitted.
- Flag
- A boolean variable used to record a state or condition in a program.
- Input validation
- Checking that user-provided data meets required constraints before using it.
Practice Questions
-
Write a Java program that reads an integer and prints whether it is even or odd. / एक पूर्णांक पढ़ने वाला जावा प्रोग्राम लिखिए और बताइए कि वह सम है या विषम।
Show answer
English answer: Read the integer into variable n, check if (n % 2 == 0) then print "Even" else print "Odd". Example code: int n = sc.nextInt(); if (n % 2 == 0) System.out.println("Even"); else System.out.println("Odd"); / हिंदी उत्तर: पूर्णांक n पढ़िए, यदि (n % 2 == 0) तो "Even" छापिए अन्यथा "Odd". उदाहरण कोड: int n = sc.nextInt(); if (n % 2 == 0) System.out.println("Even"); else System.out.println("Odd");
-
Explain the difference between == and equals() when comparing strings in Java. / जावा में स्ट्रिंग की तुलना करते समय == और equals() में क्या अंतर है, समझाइए।
Show answer
English answer: '==' compares whether two string variables refer to the same object (reference equality). equals() compares the actual sequence of characters (content equality). Use equals() to test if strings have the same text. / हिंदी उत्तर: '==' जाँचता है कि दोनों स्ट्रिंग वेरिएबल एक ही ऑब्जेक्ट को संदर्भित करते हैं या नहीं (संदर्भ समानता)। equals() वास्तविक अक्षरों की सीक्वेंस की तुलना करता है (सामग्री समानता)। स्ट्रिंग का टेक्स्ट मिलाना हो तो equals() का प्रयोग करें।
-
What will be the output of the following code? int x = 5; if (x > 3) if (x < 10) System.out.println("A"); else System.out.println("B"); / निम्न कोड का आउटपुट क्या होगा? int x = 5; if (x > 3) if (x < 10) System.out.println("A"); else System.out.println("B");
Show answer
English answer: Output is A because x>3 is true and then x<10 is true so inner if prints "A". / हिंदी उत्तर: आउटपुट A होगा क्योंकि x>3 सत्य है और फिर x<10 भी सत्य है इसलिए अंदर वाली if "A" छापेगी।
-
Write a program using switch to print the day name for numbers 1 to 7; otherwise print "Invalid". / 1 से 7 तक के नंबर के लिए दिन का नाम switch का उपयोग करके प्रिंट करने वाला प्रोग्राम लिखिए; अन्यथा "Invalid" प्रिंट करें।
Show answer
English answer: Read int day; use switch(day) with cases 1..7 mapping to Monday..Sunday with break after each case; default prints "Invalid". Example: switch(day) { case 1: System.out.println("Monday"); break; ... default: System.out.println("Invalid"); } / हिंदी उत्तर: int day पढ़िए; switch(day) में case 1..7 को Monday..Sunday से जोड़िए और हर case के बाद break लिखिए; default में "Invalid" छापिए। उदाहरण ऊपर दिया गया है।
-
A student passes if marks are at least 35 and attendance >= 75. Write the condition in Java using logical operators. / यदि छात्र पास तब है जब अंक कम से कम 35 हों और उपस्थिति 75% या अधिक हो। Java में उपयुक्त लॉजिक ऑपरेटर का उपयोग कर शर्त लिखिए।
Show answer
English answer: The condition is (marks >= 35 && attendance >= 75). Use this inside an if. / हिंदी उत्तर: शर्त है (marks >= 35 && attendance >= 75). इसे if के अंदर उपयोग करें।
-
Why should break be used in switch cases? What happens if it is omitted? / switch के केस में break क्यों उपयोग करना चाहिए? यदि इसे हटाया जाए तो क्या होता है?
Show answer
English answer: break prevents fall-through; without it execution continues into the following case(s) even if their labels don't match. Omitting break can cause multiple case blocks to run unintentionally. / हिंदी उत्तर: break fall-through को रोकता है; इसके बिना कंट्रोल अगले case में चला जाता है और कई case ब्लॉक बिना चाहे चल सकते हैं।
-
Write a Java statement using the ternary operator to assign max the larger of a and b. / a और b में से बड़े को max में असाइन करने के लिए ternary operator का उपयोग करके Java स्टेटमेंट लिखिए।
Show answer
English answer: int max = (a > b) ? a : b; / हिंदी उत्तर: int max = (a > b) ? a : b;
-
Given boolean found = false; how would you use it as a flag to report if an item was present after searching? / boolean found = false; को एक flag के रूप में उपयोग करते हुए खोज के बाद बताइए कि कोई आइटम उपस्थित था या नहीं।
Show answer
English answer: Set found = true when the item is discovered inside the search loop. After the loop, test if(found) System.out.println("Item found"); else System.out.println("Not found"); / हिंदी उत्तर: खोज के दौरान आइटम मिलने पर found = true कर दीजिए। लूप के बाद if(found) System.out.println("Item found"); else System.out.println("Not found");
-
Trace and give output: int a = 10, b = 0; if (b != 0 && a / b > 1) System.out.println("OK"); else System.out.println("Not OK"); / ट्रेस कीजिए और आउटपुट दीजिए: int a = 10, b = 0; if (b != 0 && a / b > 1) System.out.println("OK"); else System.out.println("Not OK");
Show answer
English answer: Output is "Not OK". Due to short-circuit, b!=0 is false so a/b is not evaluated and program avoids division by zero; else branch runs. / हिंदी उत्तर: आउटपुट "Not OK" होगा। short-circuit के कारण b!=0 गलत है इसलिए a/b का मूल्यांकन नहीं होता और else भाग चलता है।
-
Write code to validate marks (0-100) before grading; if invalid, print "Invalid marks". / ग्रेड देने से पहले अंक (0-100) को वैलिडेट करने वाला कोड लिखिए; यदि अमान्य हो तो "Invalid marks" प्रिंट करें।
Show answer
English answer: if (marks < 0 || marks > 100) System.out.println("Invalid marks"); else { // proceed to grade } / हिंदी उत्तर: if (marks < 0 || marks > 100) System.out.println("Invalid marks"); else { // ग्रेडिंग जारी रखें }
Related Laws & Principles
Explore allFoundational laws & principles connected to this chapter — tap to open in the Laws Explorer.