Conditions and Loops in Java

Learn how a Java program makes decisions and repeats work. Write conditions with comparison and logical operators, choose between paths with if, else if chains and switch expressions, and repeat statements with while, do-while and for loops, using break and continue where they help. Then apply the standard loop patterns for counting, summing, averaging, finding the largest value, searching and printing tables, and check your loops by tracing them pass by pass.

BeginnerLesson 2 of 11 in Object-Oriented Programming with Java Course

What you will learn

  1. Build true-or-false conditions from comparisons, and combine them with logical operators so that a program tests exactly the situation you mean.
    • Compare values and store the results as booleans
      Use the six comparison operators on numbers and characters, keep results in boolean variables, and compare strings and decimal numbers correctly.
    • Combine conditions with &&, || and !
      Join and negate conditions with the logical operators, predict their results with truth tables, and use short-circuit evaluation and De Morgan's laws to write correct, readable tests.
  2. Make a program run different statements depending on conditions, from a single if to else if chains, the conditional operator and switch.
    • Run code conditionally with if and else
      Write if and if-else statements with correct blocks, avoid the classic brace, semicolon and scope mistakes, and nest decisions or choose a value with the conditional operator.
    • Pick one of several cases with else-if chains
      Use else if chains to choose exactly one of several outcomes, order the conditions correctly, and test the boundaries so that no value falls into a gap or two cases.
    • Select by value with switch
      Use switch statements and switch expressions to choose by the value of one variable, with arrow cases, several labels per case, default and yield, and recognize fall-through in the older colon form.
  3. Write while, do-while and for loops that run the right number of times and stop when they should, and steer them with break and continue.
    • Repeat while a condition holds with while
      Write while loops that start, update and stop correctly, use while (true) with break for open-ended repetition, and trace a loop pass by pass.
    • Run the body at least once with do-while
      Use the do-while loop when the body must run before the first test, as in input checks and menus, and avoid its scope and semicolon pitfalls.
    • Count through ranges with for loops
      Write for loops that count up, down and in steps, predict how many times they run, avoid off-by-one errors, and choose the right kind of loop for a task.
    • Exit or skip iterations with break and continue
      End a loop early with break, skip the rest of one pass with continue, leave nested loops with a labeled break, and keep loops with early exits easy to follow.
  4. Recognize and combine the standard loop patterns: counting and summing, finding extremes, searching, processing digits and nesting loops, and check loops by tracing and testing them.
    • Count, sum and average values
      Use counters and accumulators with sentinel-controlled input, compute averages and percentages without integer-division errors, and guard against empty input and overflow.
    • Find extremes, search and process digits
      Track the largest or smallest value seen so far, search with a flag or an early exit, test whether any or all values meet a condition, and take numbers apart digit by digit.
    • Nest loops, then trace and test them
      Write nested loops for tables and patterns, predict how often the inner body runs, trace loops with a table, and test them with edge cases to find off-by-one and infinite-loop errors.

Conditions and Loops in Java study guide

4 chapters

1

Build true-or-false conditions

A condition turns a question about program data into a true-or-false value. Comparisons let you ask whether a number reaches a limit or text matches a command; logical operators let you join those tests. Read the parts of a condition in the order Java evaluates them, then check the combined result. This makes it possible to express a range, an exception, or a safe division guard without letting a small operator mistake change the rule.

1.1 Comparisons and Boolean values

A condition has type boolean: it produces true or false. Java needs that explicit result in an if or loop condition. An integer by itself is not a condition, so while (count) does not compile; count > 0 asks a clear true-or-false question.

Compare numbers and characters
OperatorQuestion
<Is the left value smaller?
<=Is it smaller or equal?
>Is it larger?
>=Is it larger or equal?
==Are the values equal?
!=Are the values different?

With int a = 7; and int b = 10;, a < b and a != b are true, while a >= b is false. Different numeric types can be compared: 3 == 3.0 is true after Java widens the integer to a double.

A char comparison uses Unicode code numbers. For example, 'a' < 'b' is true. So is 'Z' < 'a': their codes are 90 and 97. All ASCII uppercase letters A through Z precede the lowercase letters a through z in this ordering.

Store a useful answer
int age = 17;
boolean isAdult = age >= 18;
System.out.println(isAdult);

The comparison gives false, which is stored in isAdult and then printed. A meaningful name lets later code say if (isAdult) directly.

Keep assignment and comparison separate. = stores a value; == compares values. For an integer, if (x = 5) fails because the assignment produces an integer. For a boolean, if (done = true) compiles, sets done to true, and takes the branch. To test the existing flag, write if (done).

Compare text and computed decimals

Use command.equals("quit") to compare the characters of a string. Text entered as "quit" matches; "Quit" does not. Use equalsIgnoreCase when letter case should not matter, and !command.equals("quit") to test for different text. The operator == asks whether strings refer to the same object, so it is unsuitable for comparing the contents of user input.

Binary floating-point cannot store many decimal fractions exactly. 0.1 + 0.2 produces 0.30000000000000004, so 0.1 + 0.2 == 0.3 is false. A tolerance comparison checks how far apart the computed values are:

double sum = 0.1 + 0.2;
boolean closeEnough = Math.abs(sum - 0.3) < 1e-9;

Here Math.abs makes the difference nonnegative; the tiny difference is below 1e-9, so closeEnough is true. Choose a tolerance appropriate to the calculation's required precision. Exact comparisons of int values have no floating-point rounding issue.

Test divisibility and ranges

n % 3 == 0 tests whether an integer is divisible by 3. For odd numbers, use n % 2 != 0: the test includes negative odd values, since -7 % 2 is -1.

Write each side of a range test separately: 0 < x && x < 10. Java cannot read 0 < x < 10 as a mathematical chain: its first comparison already produces a boolean, which cannot be compared with 10.

Key Takeaways

  • A condition must produce a boolean.
  • Use = to assign and == to compare numeric values.
  • Compare string contents with equals or equalsIgnoreCase.
  • Compare computed decimals with an appropriate tolerance.
  • Use n % 2 != 0 for odd integers, including negative ones.

1.2 Combined conditions and short-circuiting

Logical operators combine whole true-or-false conditions. Read a combined condition as a rule about the data, then test values that should pass and values that should fail.

Join and negate tests

&& means and: both parts must be true. || means or: at least one part must be true, including when both are. ! means not and reverses one boolean value.

| p | q | p && q | p || q | | --- | --- | --- | --- | | true | true | true | true | | true | false | false | true | | false | true | false | true | | false | false | false | false |

A comfortable temperature from 18 through 24 °C needs both bounds: temp >= 18 && temp <= 24. Outside that interval means temp < 18 || temp > 24. Joining the inside bounds with || accepts every number: below 18 the upper-bound test is true, and above 24 the lower-bound test is true.

Each operand must be a boolean expression. Write x == 1 || x == 2, because x == 1 || 2 puts an integer where a boolean is required. For an integer, !x > 5 is invalid; !(x > 5) negates the whole comparison.

Evaluate only what is needed

Java evaluates && and || from left to right and short-circuits when the left part settles the answer. With &&, a false left side skips the right side. With ||, a true left side skips it.

int total = 36;
int count = 0;
boolean largeAverage = count != 0 && total / count > 10;

The first comparison is false, so division is skipped and largeAverage becomes false. Reverse the operands and division happens before the guard; integer division by zero throws an ArithmeticException. Put the safety check before the calculation it protects.

Make grouping visible

From strongest to weakest, the relevant operators are !, relational comparisons (<, <=, >, >=), equality comparisons (==, !=), &&, then ||. Thus a || b && c groups as a || (b && c). When a is true and b and c are false, that expression is true; (a || b) && c is false. Parentheses show which rule you intend.

De Morgan's laws move a negation across a combined condition:

  • !(p && q) equals !p || !q.
  • !(p || q) equals !p && !q.

Negate each part and swap the joining operator. Applying this to the temperature range gives !(temp >= 18 && temp <= 24) equal to temp < 18 || temp > 24.

Express a rule with an exception

A Gregorian leap year is divisible by 4, except that a century year must be divisible by 400:

boolean leap = (year % 4 == 0 && year % 100 != 0)
        || year % 400 == 0;

The first part accepts 2024. It rejects 1900 because 1900 is a century year; the final test accepts 2000 because it is divisible by 400. The year 2026 fails both parts.

Named booleans help longer tests read clearly, such as isWeekend || isHoliday. For two booleans, ^ is exclusive or: exactly one operand must be true, as with !=. The single & and | also compute boolean and/or, but evaluate both operands; use && and || for short-circuit conditions.

Key Takeaways

  • && requires both conditions; || requires at least one.
  • A short-circuit guard belongs before the expression it protects.
  • && binds more tightly than ||; parentheses can change the result.
  • De Morgan's laws negate both parts and swap && with ||.
  • Each side of a logical operator must be a complete boolean expression.
  • Single & and | evaluate both operands.
2

Choose the path a program takes

A decision sends execution down a selected path. A single test can enable one action, a pair of branches can choose between two actions, and a chain can assign one result from several ranges. When the choice depends on exact values of one variable, switch offers another clear form. Following the path means checking which conditions are reached, which branch runs, and which variables remain available afterward.

2.1 Branches, blocks, and value choices

An if runs a block when its condition is true. An if with an else chooses exactly one of two blocks. After the chosen block finishes, execution continues with the following statement.

Choose a path
int age = 16;
if (age >= 18) {
    System.out.println("Adult ticket");
} else {
    System.out.println("Youth ticket");
}
System.out.println("Next customer");

The condition is false, so the output is "Youth ticket", followed by "Next customer". The last statement belongs to neither branch. Put the boolean condition in parentheses and each branch's statements inside braces.

Without braces, only the next statement belongs to an if. Indentation does not group code. In this faulty example, the second message appears for every score:

if (score < 50)
    System.out.println("Not passed");
    System.out.println("Try again");

Braces around both print statements make both conditional. A different mistake is a semicolon immediately after the condition: if (x > 10); has an empty body. A block following it runs independently, and an else after that independent block has no matching if.

Keep a result available

A variable declared within a block is visible only within that block. Declare a result before the branches when later code needs it:

String ticket;
if (age >= 18) {
    ticket = "Adult ticket";
} else {
    ticket = "Youth ticket";
}
System.out.println(ticket);

Both possible paths assign ticket, so printing it afterward is valid. If only the true branch assigned it, Java would reject the later read: the variable might not have been initialized. Declaring ticket separately inside each branch would also leave no ticket available after the decision.

Place one decision inside another

A nested if runs its test only when execution reaches its enclosing branch:

if (hasTicket) {
    if (age < 12) {
        System.out.println("Child seat");
    } else {
        System.out.println("Standard seat");
    }
} else {
    System.out.println("Buy a ticket first");
}

Someone without a ticket reaches the outer else; the age check is skipped. If both nested tests merely guard the same action and neither has an else, they can become if (hasTicket && age < 12).

The dangling else rule attaches an else to the nearest unmatched if. Without braces, visually aligning it with an outer if does not change that rule. For an outer positive-x test followed by an inner positive-y test, the next else belongs to the y test. Braces around the complete inner decision are needed when the else should belong to the outer test.

Choose a value with ?:

The conditional operator chooses one of two values:

int n = 7;
String label = n % 2 == 0 ? "even" : "odd";

The condition is false, so the expression gives "odd". Its form is condition ? valueIfTrue : valueIfFalse. Use it for a short value choice; use an if when branches perform several actions. Nested conditional expressions quickly make the chosen path hard to follow.

Key Takeaways

  • Braces group all statements that belong to a branch.
  • An else attaches to the nearest unmatched if.
  • A result needed after a decision must be in scope and assigned on every path that reaches its use.
  • ?: chooses a value from two expressions.

2.2 Ordered cases and boundary values

An else if chain tests conditions in order and selects the first true one. Once that branch runs, the remaining conditions are skipped. A final else handles the values left over; without it, the chain can take no action.

Order overlapping thresholds

For scores from 0 to 100, test the highest grade first:

String grade;
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade = "D";
} else {
    grade = "F";
}

For 85, the first test fails and the second succeeds. The program assigns "B" without checking the remaining thresholds. Reaching score >= 80 already means the score is below 90, so an extra upper bound is unnecessary.

If score >= 60 appeared first, every passing score would receive "D". Work from the most restrictive matching case toward the broader ones. This ordering rule matters because several conditions can be true even though only one branch runs.

Handle the combined case first

FizzBuzz has a special case where two rules overlap: multiples of both 3 and 5 need "FizzBuzz". Test that case before either single divisibility test:

if (n % 15 == 0) {
    System.out.println("FizzBuzz");
} else if (n % 3 == 0) {
    System.out.println("Fizz");
} else if (n % 5 == 0) {
    System.out.println("Buzz");
} else {
    System.out.println(n);
}

The test % 15 == 0 accepts 30; 9 reaches "Fizz", 10 reaches "Buzz", and 7 reaches the final branch. Starting with % 3 == 0 would accept 30 too early and print only "Fizz".

Choose one outcome or several actions

Separate if statements are independent decisions. With x = 15, an if (x > 10) can print "big" and a following if (x > 0) can also print "positive". Joining them with else if makes the second test unreachable whenever the first is true. Use independent tests when both actions may be needed; use a chain for one selected outcome.

Check endpoints and invalid values

An integer-temperature chain with temp < 10, then temp > 10 && temp < 25, then temp >= 25 misses exactly 10. Replace the second test with temp < 25: reaching it already means the first test failed, so the value is at least 10. A final else then handles 25 and above.

For each cutoff, try the value just below it, the cutoff itself, and the value just above it. For the score chain, 89, 90, and 91 reveal whether the A boundary is included correctly. Test the overall limits too.

Validate a score before grading it: put score < 0 || score > 100 first and report "Invalid score" there. Later branches then operate only on valid scores; 150 cannot accidentally receive "A". Validation is a separate first case, not a correction after the grade has already been chosen.

Key Takeaways

  • The first true condition in a chain selects the only branch that runs.
  • Put narrower overlapping cases before broader cases.
  • Use separate if statements when several actions may apply.
  • Test the values at and next to every cutoff.
  • Reject invalid inputs before classifying valid ones.

2.3 Switch cases and expression results

A switch selects a case by comparing one value with fixed labels. It fits named commands and numbered choices. Use an else if chain when the choice depends on a range or several variables.

Match exact values

A value switch accepts char, byte, short, int, their wrapper types, String, and enum selectors. Without preview features, long, float, double, and boolean selectors are not supported. Labels must be constants: a condition such as score >= 90 is not a value label.

switch (day) {
    case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
    case 6, 7 -> System.out.println("Weekend");
    default -> System.out.println("Invalid day");
}

An arrow case runs only its own code, with no fall-through. Commas group several labels for one action. A day of 6 prints "Weekend"; a day of 9 matches no listed value and prints "Invalid day".

String labels match exact, case-sensitive contents. A command of "Start" does not match case "start". A duplicate label is a compile error, and one switch cannot mix arrow cases with colon cases.

Produce a value

A switch expression computes a result:

int days = switch (month) {
    case 1, 3, 5, 7, 8, 10, 12 -> 31;
    case 4, 6, 9, 11 -> 30;
    case 2 -> 28;
    default -> 0;
};

In a non-leap year, month 9 gives 30, month 2 gives 28, and invalid month 13 gives 0. The semicolon after the closing brace ends the variable declaration.

An expression must be exhaustive: every possible selector value must have a result. For these int and String examples, include default. A value-switch statement can omit default; an unmatched value then runs no case. A value-producing expression cannot simply skip producing its result.

Give a block a result with yield

A case that calculates before choosing its value needs a block:

int days = switch (month) {
    case 2 -> {
        boolean leap = (year % 4 == 0 && year % 100 != 0)
                || year % 400 == 0;
        yield leap ? 29 : 28;
    }
    case 4, 6, 9, 11 -> 30;
    case 1, 3, 5, 7, 8, 10, 12 -> 31;
    default -> 0;
};

yield supplies the case's value to the switch expression. February gives 29 in 2024 and 28 in 2026. A single expression after an arrow, such as case 2 -> 28;, needs no yield.

Read the older colon form
switch (level) {
    case 1:
        System.out.println("Bronze");
    case 2:
        System.out.println("Silver");
        break;
    case 3:
        System.out.println("Gold");
        break;
}

For level 1, execution enters the first case and continues into the second, printing both "Bronze" and "Silver". This is fall-through: a colon label does not stop execution. break ends the switch. Stacked colon labels can deliberately share an action; a missing break after an action can accidentally run the next one.

A char switch can group 'a', 'e', 'i', 'o', 'u' into a "vowel" result with default giving "other". The same exact-value principle applies to characters, commands, and numeric choices.

Key Takeaways

  • Use switch for fixed labels of one selector.
  • Arrow cases do not fall through.
  • A switch expression must produce a result for every possible selector value.
  • A block case supplies its expression result with yield.
  • A colon case can fall through without break.
  • String cases match exact, case-sensitive contents.
3

Control repetition and stopping

Repetition depends on both a condition and a change in program state. Follow a loop from its starting values through its test, body, and update to see when it stops. The three loop forms put these pieces in different places: before the body, after it, or together in a header. Early exits and skipped passes add useful choices, but they also make the order of execution worth tracing carefully.

3.1 While-loop tests and changing state

A while loop tests its condition before each pass. If the condition is true, Java runs the body and returns to the test. If it is false, execution continues after the loop. A false first test means zero passes.

Follow start, test, body, update
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

The starting value is 1. Each pass prints the current value and then increases it. The fifth pass prints 5 and changes i to 6. The next test is false, so the loop ends. There are five body executions but six condition tests: one before each pass and a final false test.

A counting loop needs a starting value, a test, and an update that moves toward stopping. Leave out i++ and this loop prints 1 forever. A stray semicolon is another trap: in while (i <= 5);, the empty statement is the body. When i starts within the range, the later block is never reached and cannot update it.

Stop when a limit is crossed

Equality is often a fragile stopping test. Starting at 0 and adding 3 visits 0, 3, 6, 9, 12, and so on. The test i != 10 cannot notice crossing 10 because 10 is skipped. The test i < 10 ends after processing 9. Choose a bound that matches the update direction.

Some loops repeat an unknown number of times. For example:

int amount = 1;
int days = 0;
while (amount < 1000) {
    amount *= 2;
    days++;
}

Each pass doubles the amount and counts one day. After nine passes it is 512; after ten it is 1024. The false test at 1024 leaves days equal to 10. A loop can finish above its threshold when the update moves in larger steps.

Read before deciding whether to stop
while (true) {
    String line = scanner.nextLine();
    if (line.equals("stop")) {
        break;
    }
    System.out.println("You wrote: " + line);
}

Here scanner is the input Scanner. The loop reads a line, checks for "stop", and echoes only ordinary lines. The stop command is consumed but not processed. while (true) needs a reachable exit to finish; a loop that keeps repeating without exiting is an infinite loop.

Keep a trace of changing state

Consider a product:

int n = 3;
int product = 1;
while (n > 0) {
    product *= n;
    n--;
}
Pointproductn
Before the loop13
After pass 132
After pass 261
After pass 360

The multiplication uses the old n, and the decrement follows it. Moving the decrement above the multiplication would change which values are multiplied.

Declare a running result before the loop so it survives from pass to pass. A variable declared inside the body is created again whenever execution reaches its declaration. Print inside the body to see intermediate results; print after the closing brace to show the final result once.

Key Takeaways

  • A while loop may execute zero times.
  • Trace the condition before each pass, including the final false test.
  • Counting loops need an update that moves toward a stopping bound.
  • A stop command must be checked before its input is processed.
  • Keep running results outside the loop body.

3.2 Do-while input checks

A do-while loop runs the body before checking whether another pass is needed. Use it when the first action must happen, such as showing a menu or asking for an input value.

Test after the first action
int i = 10;
do {
    System.out.println(i);
    i++;
} while (i < 5);

The body prints 10 and increments i to 11. Only then does Java test i < 5. It is false, so there is no second pass. A while (i < 5) loop starting at 10 would print nothing.

The semicolon after the final while (...) is required. It closes the do-while statement. This differs from the accidental semicolon after a pre-test while header, which creates an empty loop body.

Repeat while input is invalid
int rating;
do {
    System.out.print("Rating (1-5): ");
    rating = Integer.valueOf(scanner.nextLine());
} while (rating < 1 || rating > 5);

The prompt appears before the first check, so the user can provide the value being checked. With input 7, then 0, then 4, the first two conditions are true and trigger another prompt. The last condition is false, so the loop ends with rating equal to 4.

The condition describes continuing, not accepting. A valid rating satisfies rating >= 1 && rating <= 5. The loop repeats while that statement is false, which De Morgan's laws rewrite as rating < 1 || rating > 5. A conjunction between these outside bounds would never be true: one number cannot be below 1 and above 5 at the same time.

Declare the checked variable before the block

The closing brace ends the body's scope before the condition is evaluated. A declaration such as int rating inside the do block would therefore be unavailable in the final condition. Declare it before do and assign the input within the body. The assignment always runs before the first test.

The same placement matters when the accepted value is used afterward. rating remains in scope after the entire loop, and now contains the last value read.

Keep a menu open
String choice;
do {
    System.out.println("a: show status, q: quit");
    choice = scanner.nextLine();
    if (choice.equals("a")) {
        System.out.println("Ready");
    }
} while (!choice.equals("q"));

Every pass displays the menu and reads a choice. Entering "a" prints "Ready" and repeats. Entering "q" skips the action and ends at the condition. An unknown command also repeats because it is not "q".

When its body contains no continue targeting the loop, a do-while can be rewritten as while (true) with a negated-condition break at the bottom. A continue needs special care in such a rewrite: in the original do-while it jumps to the condition, while in a while-true loop it jumps to the top and can skip that added bottom test.

Key Takeaways

  • A do-while body runs before its first test.
  • The final semicolon is required.
  • Declare a variable outside the body when the condition needs it.
  • For input validation, repeat while the value is invalid.

3.3 For-loop ranges and endpoints

A for loop groups the control of a counting task into one header. It is useful when you know the range or number of passes before repetition begins.

Read the header in execution order
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

The initialization runs once, setting i to 1. Java tests i <= 5, runs the body if true, runs i++, and returns to the test. The update is written in the header but executes after the body. The final false test ends the loop.

For ordinary counting, i++ and ++i have the same effect in the update position because neither expression's value is used. Keep the counter's changes in the header so the sequence is easy to predict.

Choose the first and last values
HeaderValues used by the bodyPasses
int i = 0; i < 5; i++0 through 45
int i = 0; i <= 5; i++0 through 56
int i = 10; i >= 1; i--10 through 110
int i = 0; i <= 20; i += 50, 5, 10, 15, 205

For unit upward steps with the end at least the start, an exclusive end gives end minus start passes; an inclusive end adds one. Larger steps require listing or counting the values actually reached. A downward loop must test in the matching direction: starting at 10 with i <= 1 gives zero passes.

An off-by-one error includes or excludes one unwanted endpoint. To print 1 through 10, i < 10 misses 10; use i <= 10. Check the first body value, the last body value, and the first value that fails the condition.

Build a result across a range
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println(sum);

The body adds each integer once, ending with 5050. A product starts differently: initialize product to 1 before multiplying by 1 through 5. That gives 120; starting at 0 would leave the product at 0 after every multiplication.

Watch scope and empty bodies

A counter declared in the header exists throughout that loop, but not after its closing brace. Declare it earlier if later code needs its final value.

A semicolon immediately after the header is an empty body. In for (int i = 0; i < 3; i++);, the empty statement executes three times. A following block that prints "Hello" executes once after the loop, not three times. Braces belong directly after the header.

Any header part can be omitted. for (;;) { ... } has no stopping condition and behaves like while (true); it needs an exit such as break to finish.

Select the clearest loop
TaskUseful formReason
Visit a known rangeforStart, bound, and step sit together.
Repeat until input or state changeswhileThe test can reject the first pass.
Ask first, then checkdo-whileThe first body execution is required.

The forms can express the same repetition, but rewrites must preserve the order of tests and updates, including what a continue skips.

Key Takeaways

  • A for loop executes initialization once, then test, body, and update.
  • Check the start, last included value, and pass count.
  • A header-declared counter is unavailable after the loop.
  • Use for for ranges, while for changing state, and do-while for a required first pass.
  • A semicolon after a for header creates an empty body.

3.4 Early exits and skipped passes

An early exit can stop repetition as soon as its job is complete. A skipped pass can leave out unwanted work while keeping the loop going. Follow their destinations carefully: break and continue do different jobs.

End a search with break
for (int n = 51; n <= 100; n++) {
    if (n % 7 == 0) {
        System.out.println(n);
        break;
    }
}

The values 51 through 55 fail the divisibility test. The next value, 56, is printed and break leaves the loop immediately. The update does not run after that break. Without it, later multiples such as 63 and 70 would also be printed.

An unlabeled break targets the nearest enclosing loop or switch. Execution continues after that construct, not after the entire program.

Skip with continue
for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0) {
        continue;
    }
    System.out.print(i + " ");
}

For 3, 6, and 9, continue skips the print statement. In a for loop, the header update still runs, followed by the condition. The output contains 1, 2, 4, 5, 7, 8, and 10.

For a while or do-while, continue goes to the condition. Any update below it in the body is skipped. If a while counter starts at 0 and the first action is if (i % 3 == 0) { continue; }, an i++ later in the body is never reached. The counter remains 0 and the loop repeats forever. Move the required update before every skipped path, or use a for header to keep the update automatic.

Leave nested loops deliberately

An ordinary break inside an inner loop ends only that inner loop. A label can name an outer loop as the exit target:

outer:
for (int a = 1; a <= 10; a++) {
    for (int b = 1; b <= 10; b++) {
        if (a * b == 24 && a + b == 10) {
            System.out.println("Found " + a + " and " + b);
            break outer;
        }
    }
}

The search visits pairs in order. At a = 4 and b = 6, both tests pass and the labeled break exits both loops. continue outer would instead move to the outer loop's update and then its next test.

Separate switch exits from loop exits

In a menu loop containing a colon-form switch, break inside a case ends the switch. It does not by itself end the surrounding loop. One clear pattern sets a loop flag to false in the quit case, then uses break to leave the switch. The loop ends when its next condition check sees the false flag. Arrow cases need no break to prevent fall-through.

Unlabeled break is legal within a loop or switch; continue is legal within a loop. Placing them elsewhere fails compilation. Keep the normal stopping rule in the loop condition when it fits there. Use while (true) with a break when the stop test naturally belongs after reading input but before processing it. Multiple exits can be useful, but every extra path adds state to follow when tracing.

Key Takeaways

  • break leaves its target immediately.
  • For-loop continue still runs the header update.
  • While-loop continue can skip a necessary body update.
  • An ordinary exit affects the nearest eligible construct.
  • A labeled break can leave an outer loop.
  • A switch break does not directly exit a surrounding loop.
4

Build and check useful loops

A loop becomes useful when it keeps just the information a problem needs: a count, a running sum, a best value, or a flag recording a match. Combining those small patterns solves input-processing and search tasks. Nested loops extend repetition to rows and columns. Trace the changing values, keep state in the right scope, and use empty inputs and boundary cases to check that the result describes all the data.

4.1 Running counts, sums, and averages

A counter records how many values qualify. An accumulator combines values into a running result. Declare both before the loop so each pass builds on the earlier work.

Initialize for the operation

Use int count = 0; and increment when an item qualifies. A sum starts at 0 and uses sum += value;. A product starts at 1, because multiplying an initial 0 would erase every later factor. Initializing a total inside the body resets it on every pass.

For a range, the loop's step can select the values: adding the even integers from 2 through 100 in steps of 2 gives 2550. Or put a condition inside the loop. Counting numbers from 1 through 100 divisible by 3 or by 5 gives 47: the six multiples of 15 must be counted only once.

Stop input before adding it

A sentinel is a special input value that ends reading. It is not an ordinary data value:

int sum = 0;
int count = 0;
while (true) {
    int number = Integer.valueOf(scanner.nextLine());
    if (number == 0) {
        break;
    }
    sum += number;
    count++;
}

For input 12, 7, 5, 0, the sum moves through 12, 19, and 24. The count reaches 3. The final 0 triggers the break before either variable changes. Counting it would create a fourth item and give the wrong average even though adding zero leaves the sum unchanged.

Divide only after checking the count
if (count > 0) {
    double average = (double) sum / count;
    System.out.println(average);
} else {
    System.out.println("No numbers entered");
}

The example prints 8.0. With integer operands, division drops the fractional part: 25 / 4 is 6. Convert before dividing to get 6.25: (double) sum / count. Casting afterward, (double) (sum / count), merely converts the already-truncated result to 6.0.

If the sentinel arrives first, count is 0. Integer division by zero throws an ArithmeticException; a floating-point zero sum divided by zero gives NaN. The count check keeps an empty input from producing a meaningless average.

Track several results in one pass

For scores 55, 72, 90, 48, and 81, a pass mark of 60 produces five scores and three passes. Keep a total counter for every score and a passed counter inside the passing condition. 100.0 * passed / total gives 60.0 percent; 100.0 makes the arithmetic floating-point. Check for a positive total before this division too.

Where printing occurs changes what is shown. Distances of 5, 3, and 8 km give running totals 5, 8, and 16 km when printed inside the loop after the addition. Printing afterward gives only the final 16 km.

Choose a type large enough for the total

An int's maximum is 2,147,483,647. Adding all integers from 1 through 100,000 should give 5,000,050,000, but an int wraps to 705,082,704 without reporting an error. long sum = 0; holds this sum correctly; long's maximum is about 9.2 × 10¹⁸. Widening an already-overflowed result afterward cannot restore the lost value.

Key Takeaways

  • Initialize a sum or count to 0 and a product to 1.
  • Exclude the sentinel from both the sum and count.
  • Convert an operand before division to preserve the fraction.
  • Guard averages and percentages against an empty input.
  • Keep each counter's update beside the condition it counts.
  • Use a sufficiently wide type before accumulating a large total.

4.2 Best values, searches, and digits

Some loops remember a best value; others remember whether a match has occurred. Choose the initial state so it tells the truth before and after every pass.

Keep the best value seen so far

To track a maximum, replace it only when the current value is larger: if (value > max) { max = value; }. Starting with the first reading, temperatures 14, 19, 11, 23, and 17 °C leave successive maxima 14, 19, 19, 23, and 23 °C. A minimum uses < instead.

Starting a maximum at 0 fails on all-negative data: -5, -2, and -9 would incorrectly leave 0 as the result. Initialize from an actual reading, or start at Integer.MIN_VALUE for an int maximum and Integer.MAX_VALUE for an int minimum. Report no result when there were no readings.

To record a position, update the position in the same branch as the value. A strict > retains the first maximum on ties; >= replaces it again and retains the last.

Stop after finding a match
int n = 1;
while (n * n <= 500) {
    n++;
}

At 22, the square is 484, so another pass runs. At 23, it is 529 and the condition fails. The loop has found the smallest positive integer whose square exceeds 500. A bounded search can instead test each candidate in a for loop and break at the first match.

For an any question, start a flag false and make it true at a match. For an all question, start true and make it false at a counterexample. Do not reset either flag in an else branch on later values: a later nonmatch does not erase an earlier negative reading, for example.

Test for a divisor

A prime number is at least 2 and has no divisor from 2 through one less than itself. For a small positive integer, a shorter check tests divisors only through its square root:

int n = 91;
boolean isPrime = n >= 2;
for (int d = 2; d * d <= n; d++) {
    if (n % d == 0) {
        isPrime = false;
        break;
    }
}

A pair of factors cannot both exceed the square root. For 91, divisor 7 gives a zero remainder and changes the flag to false. For 97, no divisor from 2 through 9 divides it, so the flag remains true. Values below 2 begin with a false flag. For large positive ints, use d <= n / d to avoid overflow in d * d.

Remove one decimal digit per pass

For a nonnegative integer, % 10 extracts the last digit and integer / 10 removes it:

int n = 4072;
int sum = 0;
while (n > 0) {
    sum += n % 10;
    n /= 10;
}

The digits are 2, 7, 0, and 4, giving 13. The working n ends at 0. To reverse digits, update reversed = reversed * 10 + n % 10; before removing the digit; 1234 becomes 4321 when the result fits the chosen type.

For digit counting, zero needs one pass even though n > 0 starts false. Use a do-while that increments the count and divides n by 10. It counts one digit for 0 and the usual number for positive values.

Key Takeaways

  • Initialize an extreme from real data or an appropriate type limit.
  • Update an extreme's position together with its value.
  • Keep a search flag true after an any-match, or false after an all-counterexample.
  • A prime test needs no divisors above the square root.
  • For nonnegative integers, % 10 extracts a digit and / 10 removes it.
  • A zero digit count needs a required first pass.

4.3 Nested work, traces, and test cases

Nested loops repeat a whole repetition for each outer pass. They are useful for rows, columns, tables, and shapes. The inner loop must start fresh whenever the outer loop reaches it.

Print a row, then end the line
for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 5; col++) {
        System.out.print(row * col + "\t");
    }
    System.out.println();
}

The first row contains 1, 2, 3, 4, 5; the second contains 2, 4, 6, 8, 10; the third contains 3, 6, 9, 12, 15. The inner print makes columns on one line; the println after the inner loop ends that row. Moving println inside the inner loop puts each product on its own line.

With fixed counts, multiply outer passes by inner passes. Three outer passes and four inner passes execute the inner body 12 times. The table above has three times five, or 15, product prints.

Let row size change
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print("*");
    }
    System.out.println();
}

The inner bound now depends on the row. Its counts are 1, 2, 3, and 4, so the triangle contains 10 stars. A single fixed-count multiplication would be wrong because the inner loop does not run equally often on each row.

Use different names for overlapping loop counters. Declaring another int i within a loop where i is already in scope fails compilation. For an inner while loop, initialize its counter at the start of each outer pass. Initializing it only before the outer loop leaves it past the limit after the first row.

Trace values at a consistent point

For a loop from 1 through 4, subtract odd values from a total starting at 0 and add even ones:

Value processedActionTotal after the pass
1Subtract 1-1
2Add 21
3Subtract 3-2
4Add 42

Record whether a row describes the start or end of a pass. Include the final failed condition when checking termination. A trace that mixes before-update and after-update values can make a correct loop look wrong.

Put separators between items

Five numbers need four commas. Print a separator before every item except the first:

for (int i = 1; i <= 5; i++) {
    if (i > 1) {
        System.out.print(", ");
    }
    System.out.print(i);
}

The output is "1, 2, 3, 4, 5", with no leading or trailing comma. This is a fencepost problem: the number of gaps differs from the number of items.

Test cases that expose mistakes

Try zero passes, one pass, and the values at and next to each boundary. For input loops, try the sentinel first. For nested loops, check whether the second row resets correctly. Temporary prints of the loop variables reveal actual progress. If a program hangs, inspect every path for an update or exit and stop it with Ctrl+C in a terminal or the development environment's stop button.

Key Takeaways

  • The inner loop completes for every outer pass.
  • Multiply pass counts only when both counts are fixed.
  • Reset an inner while counter for every outer pass.
  • Put a row's line break after its inner loop.
  • Use a consistent point in each pass for trace-table rows.
  • Test zero passes, one pass, and both sides of a boundary.
  • Separators go between items, so their count is one fewer.

Conditions and Loops in Java examples

4 Walkthroughs

1

Turn a program rule into a condition

12 steps
Build comparisons, combine them, and check both their truth values and their evaluation order.
  1. 1
    IntroductionStart with a rule about data

    A condition answers one true-or-false question about the current data. Start with simple comparisons, then combine them into a rule that accepts exactly the intended values.

    We will check a temperature range, compare text, and protect an integer division. At each step, distinguish what the condition means from the order in which Java evaluates it.

  2. 2
    ExplanationGive a comparison a name

    A comparison produces a boolean, which can be stored for later use.

    int age = 17;
    boolean isAdult = age >= 18;
    

    Here isAdult stores false. The expression if (isAdult) later tests that value directly. A bare integer cannot serve as the condition: if (age) fails because Java requires a boolean, not a truth-like number.

  3. 3
    ExampleRead the operator precisely

    With a = 7 and b = 10, a < b is true and a >= b is false. The comparisons a != b and a == 7 are true.

    The difference between = and == matters: assignment changes a variable, while comparison asks a question. For a boolean, if (done = true) compiles but overwrites the flag before testing it. Use if (done) to test the existing value.

  4. 4
    TipMatch the characters in input

    A non-null string such as command has text contents and an object identity. command.equals("quit") tests the characters; command == "quit" tests identity.

    Use equalsIgnoreCase only when case differences should be accepted. For example, "Quit" and "quit" match with that method but differ with equals. Negating an exact match gives !command.equals("quit").

  5. 5
    ExampleCheck a decimal difference
    double sum = 0.1 + 0.2;
    boolean close = Math.abs(sum - 0.3) < 1e-9;
    

    The sum is stored as 0.30000000000000004. Exact equality with 0.3 is false, but the absolute difference is below this tolerance, making close true. The tolerance test accepts a small difference; it does not change either stored value or make them exactly equal.

  6. 6
    ChallengeTest a negative odd number

    A program uses n % 2 == 1 to detect odd integers. What does it miss when n is -11, and how can the test be repaired?

    ---reveal---

    -11 % 2 is -1, so the test is false even though -11 is odd. Use n % 2 != 0: divisibility by 2 has a zero remainder, and either positive or negative nonzero remainders identify odd integers.

  7. 7
    ExplanationRequire both bounds

    To accept temperatures from 18 through 24 °C, require both comparisons: temp >= 18 && temp <= 24.

    With 21, both are true. With 17, the first is false; with 25, the second is false. Using || between these inside bounds would accept all three values, because each satisfies at least one of the two tests. Every operand must be a complete boolean expression.

  8. 8
    Key InsightReverse the whole range

    Outside the same range means temp < 18 || temp > 24. One failed bound is enough to be outside.

    This is De Morgan's law in action: !(p && q) equals !p || !q. Negating both parts also changes the joining operator. The companion law is !(p || q) equals !p && !q; keeping the old join would change which inputs pass.

  9. 9
    ExamplePut a guard before division
    int total = 36;
    int count = 0;
    boolean large = count != 0 && total / count > 10;
    

    The false first comparison settles the result, so && skips the division. This is short-circuit evaluation. Reversing the operands would divide by zero before checking count and throw an ArithmeticException. With ||, a true left operand similarly skips the right one.

  10. 10
    ChallengeDistinguish grouping from reading order

    With a = true, b = false, and c = false, do a || b && c and (a || b) && c give the same result? Explain the grouping.

    ---reveal---

    No. The first groups as a || (b && c) because && has higher precedence, so it is true. The second requires the result of a || b and also c; since c is false, that result is false.

  11. 11
    ChallengeCombine a bound and an exception

    A load is accepted if it is from 6 through 14 kg or an override is active, but an integer calculation 100 / count > 5 must also succeed safely. Write the condition so count 0 cannot reach division.

    ---reveal---

    count != 0 && (load >= 6 && load <= 14 || override) && 100 / count > 5

    The first guard rejects zero. The grouped choice accepts the range or override; only a surviving path reaches division.

  12. 12
    RecapCheck a condition from both sides

    Before using a condition, try an input that should pass and one that should fail. For intervals, check the endpoints too.

    Read parentheses and precedence to identify the grouping, then follow left-to-right short-circuit evaluation. This catches both a wrong acceptance rule and a calculation that runs before its guard.

2

Choose one path and produce a result

14 steps
Follow blocks, order overlapping cases, and use switch expressions for exact-value choices.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow the path Java reaches
  2. 2
    ExampleRun exactly one branch
  3. 3
    ExplanationKeep the result after the decision
  4. 4
    ChallengeFind an unconditional print
  5. 5
    TipMake the inner choice explicit
  6. 6
    ExampleVisit thresholds in the right order
  7. 7
    ConnectionSeparate independent actions
  8. 8
    ChallengeRepair a missing endpoint
  9. 9
    ExplanationChoose by one exact value
  10. 10
    ExampleAssign the chosen value
  11. 11
    ExplanationGive a block its value
  12. 12
    ChallengeTrack colon fall-through
  13. 13
    ChallengeChoose a structure for a mixed rule
  14. 14
    RecapInspect the decision boundaries
3

Trace a loop from its first pass to its exit

18 steps
Follow pre-test and post-test loops, counted repetition, skipped passes, and labeled exits.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionWatch the state change
  2. 2
    ExplanationTest before entering
  3. 3
    ExampleTrace a changing product
  4. 4
    ChallengeAvoid a skipped stop value
  5. 5
    ExplanationRun once before deciding
  6. 6
    ExampleRead a rating before testing it
  7. 7
    ChallengePredict an accepted endpoint
  8. 8
    ConnectionMove counting into the header
  9. 9
    ExampleCount steps larger than one
  10. 10
    ChallengeKeep the intended endpoint
  11. 11
    TipCheck for an empty body
  12. 12
    ExampleStop at the first match
  13. 13
    ExplanationSkip the rest of one pass
  14. 14
    ChallengeFind the skipped update
  15. 15
    ExplanationGive an outer loop an exit name
  16. 16
    ConnectionKeep switch and loop exits distinct
  17. 17
    ChallengeCombine a skip and an early exit
  18. 18
    RecapTrace the next destination
4

Build results that describe all processed data

19 steps
Combine counters, extrema, flags, digits, and nested loops, checking their state with traces and edge cases.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what must survive a pass
  2. 2
    ExplanationSeparate a count from a sum
  3. 3
    ExampleRead and reject the sentinel
  4. 4
    ExampleFollow the state through input
  5. 5
    ExplanationPreserve the average fraction
  6. 6
    ChallengeAverage only accepted readings
  7. 7
    TipMake arithmetic wide early enough
  8. 8
    ExampleKeep the best reading
  9. 9
    ChallengeRecord where a tie occurs
  10. 10
    Key InsightLet a flag remember a match
  11. 11
    ExplanationSearch for a divisor
  12. 12
    ExampleExtract digits in a fixed order
  13. 13
    ChallengeKeep a negative reading remembered
  14. 14
    ExplanationComplete every row before advancing
  15. 15
    ExampleCount changing row sizes
  16. 16
    ChallengeFix a separator at the first item
  17. 17
    TipChoose revealing trace rows
  18. 18
    ChallengeCombine a changing bound with selection
  19. 19
    RecapCheck the meaning of each result

Conditions and Loops in Java practice questions

50 Practice Questions in 5 sets

Set 1: Trace loop tests, updates, and exits10 Practice Questions

Question 1 of 10

How many times does the body run?

int n = 12;
while (n < 8) {
    n++;
}
  1. 1 time
  2. 4 times
  3. 0 times
  4. 5 times
Show answerHide answer
Answer: C
A while loop checks its condition before entering the body. The initial comparison 12 < 8 is false, so there is no increment and no body execution. A compulsory first pass belongs to do-while, whose test follows the body.

Question 2 of 10

What is printed?

int level = 9;
do {
    level -= 2;
} while (level > 8);
System.out.println(level);
  1. 7
  2. 9
  3. 8
  4. 5
Show answerHide answer
Answer: A
The do-while body runs first and subtracts 2, changing level to 7. Its condition is then false, so the loop ends. Keeping 9 would treat this as a pre-test while loop and skip the first body execution.

Question 3 of 10

How many body executions occur?

for (int k = 2; k <= 17; k += 4) {
    System.out.println(k);
}
  1. 3
  2. 5
  3. 6
  4. 4
Show answerHide answer
Answer: D
The body uses 2, 6, 10, and 14. The next update produces 18, which fails the inclusive upper-bound test. Including 17 just because the condition uses <= would be a mistake: the step never reaches that value.

Question 4 of 10

What is printed, ignoring the final space?

for (int k = 2; k <= 7; k++) {
    if (k % 2 == 0) {
        continue;
    }
    System.out.print(k + " ");
}
  1. "2 4 6"
  2. "3 5 7"
  3. "3"
  4. "3 4 5 6 7"
Show answerHide answer
Answer: B
Even values take continue and skip the print; odd values reach it. The for-loop update still runs after continue, so the counter keeps advancing. Printing only 3 would confuse skipping one pass with ending the entire loop.

Question 5 of 10

What are amount and steps after this loop?

int amount = 3;
int steps = 0;
while (amount < 40) {
    amount *= 2;
    steps++;
}
  1. amount = 24, steps = 3
  2. amount = 40, steps = 4
  3. amount = 48, steps = 5
  4. amount = 48, steps = 4
Show answerHide answer
Answer: D
The amount progresses through 6, 12, 24, and 48, with one step recorded per doubling. The test fails only after reaching 48. Stopping at 24 confuses the last value that passes the condition with the value left after the last body execution.

Question 6 of 10

What is the final value of total?

int total = 0;
for (int k = 1; k <= 8; k++) {
    if (k % 3 == 0) {
        continue;
    }
    total += k;
    if (total > 12) {
        break;
    }
}
  1. 12
  2. 13
  3. 19
  4. 15
Show answerHide answer
Answer: C
The additions are 1, 2, 4, 5, and 7 because 3 and 6 are skipped. They leave totals 1, 3, 7, 12, and 19; the final addition triggers break. Ending at 12 would incorrectly read > as >= or check the limit before adding.

Question 7 of 10

A do-while loop reads an integer from 2 through 6. What condition makes it repeat exactly while the value is invalid?
  1. value < 2 || value > 6
  2. value >= 2 && value <= 6
  3. value < 2 && value > 6
  4. value <= 2 || value >= 6
Show answerHide answer
Answer: A
Invalid values are below 2 or above 6, so either outside bound must trigger another pass. Using <= and >= would reject the allowed endpoints. Joining the two outside tests with && would never repeat because no integer satisfies both.

Question 8 of 10

A for header declares int index. Where can code read that variable?
  1. Anywhere in the main method.
  2. Only in the header update.
  3. Only after the loop ends.
  4. Within that for loop only.
Show answerHide answer
Answer: D
A variable declared in a for header is in scope in the header and loop body, but its scope ends with the loop. Reading it afterward fails compilation. To retain the final counter value, declare the variable before the for statement.

Question 9 of 10

What is printed?

int hits = 0;
outer:
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= 4; col++) {
        if (row + col == 5) {
            break outer;
        }
        hits++;
    }
}
System.out.println(hits);
  1. 6
  2. 3
  3. 9
  4. 12
Show answerHide answer
Answer: B
On row 1, columns 1, 2, and 3 increment hits. Column 4 makes the sum 5, and the labeled break exits the outer loop before another increment. Counting later rows would treat the labeled break as an ordinary break of only the inner loop.

Question 10 of 10

Why does this loop never finish?

int n = 1;
while (n != 12) {
    n += 2;
}
  1. The update makes n smaller each pass.
  2. The condition is checked only once.
  3. The sequence stays odd and skips 12.
  4. The body resets n to 1 each pass.
Show answerHide answer
Answer: C
Starting at 1 and repeatedly adding 2 produces only odd numbers, so n never becomes 12. The inequality stays true even after n passes the intended limit. A bound such as n < 12 would detect crossing the limit instead of requiring an exact hit.
Set 2: Read conditions and choose a path10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What is the value of -13 % 2 != 0?
  1. false
  2. true
  3. -1
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A non-null String command contains text read from input. What expression tests whether its contents are exactly "pause"?
  1. command == "pause"
  2. command.equalsIgnoreCase("pause")
  3. !command.equals("pause")
  4. command.equals("pause")
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What condition accepts a mass from 4 through 9 kg, including both endpoints?
  1. mass >= 4 && mass <= 9
  2. mass > 4 && mass < 9
  3. mass >= 4 || mass <= 9
  4. mass < 4 || mass > 9
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does this print?

boolean ready = true;
boolean locked = false;
boolean expired = false;
System.out.println(ready || locked && expired);
  1. false
  2. true false
  3. true
  4. false false
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does this code print?

int stock = 0;
if (stock > 0) {
    System.out.print("available ");
} else {
    System.out.print("empty ");
}
System.out.print("checked");
  1. "available checked"
  2. "empty checked"
  3. "empty"
  4. "available empty checked"
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What is printed?

int load = 74;
if (load >= 50) {
    System.out.print("medium");
} else if (load >= 70) {
    System.out.print("high");
} else {
    System.out.print("low");
}
  1. "medium"
  2. "high"
  3. "mediumhigh"
  4. "low"
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What value is stored in mode?

String command = "RUN";
int mode = switch (command) {
    case "run" -> 1;
    case "wait" -> 2;
    default -> 3;
};
  1. 1
  2. 2
  3. 0
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

With int sum = 15; and int count = 0;, what happens when evaluating count == 0 || sum / count > 4?
  1. It evaluates to false without division.
  2. It evaluates to true without division.
  3. It throws an ArithmeticException.
  4. It evaluates to true after division.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Why does this code fail to compile?

int value = 8;
String label;
if (value > 5) {
    label = "large";
}
System.out.println(label);
  1. label is outside its declared scope.
  2. An if cannot assign a string value.
  3. label is not assigned on every path.
  4. The comparison must use >= instead.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A program allows entry when member && !blocked || guest && codeValid is true. What condition rejects exactly those entries it would allow?
  1. (!member || blocked) && (!guest || !codeValid)
  2. (!member && blocked) || (!guest && !codeValid)
  3. (!member || blocked) || (!guest || !codeValid)
  4. (!member && blocked) && (!guest && !codeValid)
Show answerHide answer

Save this lesson to see this answer.

Set 3: Compute results across repeated input10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What initial value should an accumulator use before multiplying the integers from 2 through 6?
  1. 0
  2. 2
  3. 6
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A loop reads 9, 4, 8, then sentinel -1. It checks the sentinel before updating sum and count. What average should it report?
  1. 5.0
  2. 7.0
  3. 5.25
  4. 6.666666666666667
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

With int sum = 17; and int count = 4;, what does (double) (sum / count) evaluate to?
  1. 4.25
  2. 4.5
  3. 4.0
  4. 5.0
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A maximum-reading loop will process only negative integers. Why can initializing max to 0 give the wrong answer?
  1. No negative input can replace that initial value.
  2. Every negative input will replace that initial value.
  3. Zero prevents the input loop from starting.
  4. Comparing negative integers causes overflow.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What is printed?

int n = 6205;
int sum = 0;
while (n > 0) {
    sum += n % 10;
    n /= 10;
}
System.out.println(sum);
  1. 12
  2. 56
  3. 13
  4. 5026
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

How many stars are printed in total?

for (int row = 2; row <= 5; row++) {
    for (int col = 1; col < row; col++) {
        if (col == 2) {
            continue;
        }
        System.out.print("*");
    }
}
  1. 6
  2. 9
  3. 10
  4. 7
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What are best and position afterward?

int best = Integer.MIN_VALUE;
int position = 0;
for (int day = 1; day <= 5; day++) {
    int value = day % 3 - 4;
    if (value >= best) {
        best = value;
        position = day;
    }
}
  1. best = -2, position = 2
  2. best = -2, position = 5
  3. best = -3, position = 4
  4. best = -4, position = 3
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A loop counted 7 accepted readings out of 12 readings. What expression calculates the accepted percentage with a fractional result?
  1. 100.0 * accepted / total
  2. accepted / total * 100.0
  3. (double) (accepted / total) * 100
  4. (double) (100 * (accepted / total))
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What is the output?

for (int k = 3; k <= 5; k++) {
    if (k > 3) {
        System.out.print(", ");
    }
    System.out.print(k);
}
  1. ", 3, 4, 5"
  2. "3, 4, 5, "
  3. "3, 4, 5"
  4. "345"
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What does this code print?

boolean allPositive = true;
for (int k = 1; k <= 4; k++) {
    int value = k - 2;
    if (value <= 0) {
        allPositive = false;
    } else {
        allPositive = true;
    }
}
System.out.println(allPositive);
  1. false, because an earlier value was nonpositive.
  2. true, although not all values were positive.
  3. true, because every generated value was positive.
  4. false, although every generated value was positive.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Combine decisions with loop patterns10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A validation loop accepts integers from 10 through 14. It reads inputs 8, 14, then 11 with do { ... } while (value < 10 || value > 14);. How many inputs does it consume?
  1. 1
  2. 3
  3. 2
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What keyword supplies a result from a multi-statement block case in a switch expression?
  1. yield
  2. break
  3. continue
  4. default
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What is printed?

int result = 0;
switch (2) {
    case 1:
        result += 2;
    case 2:
        result += 3;
    case 3:
        result += 5;
        break;
    default:
        result = -1;
}
System.out.println(result);
  1. 3
  2. 10
  3. 8
  4. -1
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What is total after the loop?

int total = 0;
for (int k = 1; k <= 5; k++) {
    switch (k % 3) {
        case 0:
            break;
        default:
            total += k;
    }
    total++;
}
  1. 14
  2. 17
  3. 16
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What is the final total?

int total = 0;
for (int n = 1; n <= 9; n++) {
    if (n % 2 == 0) {
        total += 2;
    } else if (n % 3 == 0) {
        total += 3;
    } else {
        total--;
    }
}
  1. 14
  2. 8
  3. 9
  4. 11
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What is printed?

int n = 58;
int result = 0;
do {
    int digit = n % 10;
    if (digit % 2 == 0) {
        result = result * 10 + digit;
    }
    n /= 10;
} while (n > 0);
System.out.println(result);
  1. 8
  2. 85
  3. 5
  4. 58
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A nested loop prints four rows of six values. The line-break call is after the inner loop but inside the outer loop. How many value prints and line-break calls execute?
  1. 24 value prints and 24 line-break calls.
  2. 10 value prints and 4 line-break calls.
  3. 24 value prints and 6 line-break calls.
  4. 24 value prints and 4 line-break calls.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Why can Math.abs((0.1 + 0.2) - 0.3) < 1e-9 be true while (0.1 + 0.2) == 0.3 is false?
  1. The tolerance changes the stored sum into exactly 0.3.
  2. The computed difference is nonzero but below the tolerance.
  3. The equality operator compares double object identities.
  4. The absolute-value call rounds every difference to zero.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A sentinel loop should average positive integers until 0. Its body reads a value, increments count, checks for 0 and breaks, then adds the value. For inputs 6, 10, 0 it prints (double) sum / count. What is the result and the needed repair?
  1. About 5.3333; count only after the stop test.
  2. 8.0; move the sum update before the stop test.
  3. 16.0; initialize count to 1 before reading.
  4. About 5.3333; cast the completed quotient instead.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What does this code print?

for (int n = 4; n > 0; n--);
{
    System.out.print("done");
}
  1. "done" four times
  2. Nothing at all
  3. "done" indefinitely
  4. "done" once
Show answerHide answer

Save this lesson to see this answer.

Set 5: Find errors and predict combined behavior10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What is !(false || true)?
  1. true
  2. 0
  3. false
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What is printed?

int a = -2;
int b = 5;
if (a > 0)
    if (b > 0)
        System.out.print("both");
    else
        System.out.print("one");
System.out.print("end");
  1. "oneend"
  2. "end"
  3. "bothend"
  4. "bothoneend"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What value is assigned?

int level = 3;
int result = switch (level) {
    case 1, 2 -> 4;
    case 3 -> {
        int base = level * 2;
        yield base + 1;
    }
    default -> 0;
};
  1. 6
  2. 4
  3. 0
  4. 7
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What is the final count?

int count = 0;
outer:
for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        if (row == col) {
            continue outer;
        }
        count++;
    }
}
  1. 3
  2. 6
  3. 0
  4. 9
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

For n = 143, a prime-checking loop starts at divisor 2 and continues while d * d <= n, breaking on a zero remainder. At what divisor does it first break?
  1. 7
  2. 11
  3. 12
  4. 13
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What is count at the end?

int count = 0;
int col = 1;
for (int row = 1; row <= 3; row++) {
    while (col <= row) {
        count++;
        col++;
    }
}
  1. 6
  2. 1
  3. 9
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An input loop stops at sentinel -9 and must average only positive values. Starting sum and count at 0, it checks for the sentinel, then adds every data value to sum but increments count only for positives. For inputs -4, 6, -2, 10, -9, what does (double) sum / count print, and what repair is needed?
  1. 5.0; add and count only positive values.
  2. 8.0; add and count only positive values.
  3. 2.5; add and count every data value.
  4. 5.0; sum positives but count every data value.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What digit count does this produce for n = 0?

int n = 0;
int digits = 0;
do {
    digits++;
    n /= 10;
} while (n > 0);
  1. 0
  2. 10
  3. 1
  4. It never stops.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A chain rejects score < 0 || score > 40, then labels score >= 30 as "high", score >= 18 as "middle", and the rest as "low". What labels do scores 40, 41, and 18 receive, in order?
  1. "invalid", "invalid", "low"
  2. "high", "invalid", "middle"
  3. "high", "high", "middle"
  4. "high", "invalid", "low"
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A search prints the first integer from 25 through 75 that is divisible by 4 or 7, but not by both. What does it print?
  1. 28
  2. 35
  3. 32
  4. 36
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

63 Key Terms, each with its definition

A

Accumulator
An accumulator stores a running result across loop passes, adding or multiplying each accepted value into the previous result.
An accumulator initialized before the loop keeps the total distance traveled over several days.
Assignment operator
The assignment operator = stores a value in a variable; the resulting expression has that assigned value, not a comparison result.
Using the assignment operator in if (done = true) changes the flag before the branch runs.

B

Block
A block groups statements between braces so a branch or loop can treat the group as its body, with its own local variable scope.
A block around two print statements makes both of them conditional on the same if test.
Boolean value
A Boolean value is either true or false; comparisons produce it, and Java conditions require an expression of this type.
The Boolean value stored in isFull becomes true when a container reaches its capacity.
Boundary test
A boundary test checks a value at or next to a cutoff, helping reveal gaps, overlaps, and a wrongly included or excluded endpoint.
A boundary test using 29, 30, and 31 checks the transition into a category starting at 30.
Branch
A branch is one path through a decision; an if-else statement selects one of its two branches according to a boolean condition.
The false branch prints "Try again" when the entered rating does not meet the required condition.
Break
A break exits its target immediately; without a label, its target is the nearest enclosing loop or switch in which it appears.
A break stops the search when the first candidate satisfying the required tests is found.

C

Case label
A case label names a fixed value accepted by a switch case; several comma-separated labels can share one arrow action.
A case label for 6 can share a weekend action with the label for 7 in an arrow switch.
Comparison operator
A comparison operator tests how two values relate and produces a boolean, such as whether one number is larger than another.
The comparison operator <= includes a score equal to the upper limit in a permitted range.
Conditional operator
The conditional operator ?: selects one of two expression values from a boolean condition, allowing a short two-way value choice.
The conditional operator sets label to "even" or "odd" according to a remainder test.
Continuation condition
A continuation condition describes when another loop pass should occur; a true result repeats and a false result ends repetition.
The continuation condition for rating input is true outside the interval from 1 through 5.
Continue
A continue skips the rest of the current loop body and moves toward its next pass, including the update of a basic for loop.
A continue skips the print for an unwanted value but still lets the for counter advance.
Counter
A counter records how many events or qualifying values have occurred, usually starting at zero and increasing once per match.
A counter increases only for accepted readings, keeping the denominator of their average correct.
Counterexample
A counterexample is one value that makes an all-values claim false; an all-match flag stays false after encountering it.
A zero reading is a counterexample to the claim that every recorded value is positive.

D

Dangling else
A dangling else is an else whose visual grouping may be unclear; Java attaches it to the nearest preceding unmatched if.
Braces resolve the dangling else when an outer ticket check contains an inner age check.
De Morgan's laws
De Morgan's laws negate a combined boolean test by negating both operands and switching its joining operator between and and or.
De Morgan's laws turn a test for not inside a closed interval into an or of two outside bounds.
Digit extraction
Digit extraction takes the final decimal digit of a nonnegative integer with % 10, ready to use before division removes it.
Digit extraction visits the digits from right to left when a loop repeatedly divides by 10.
Do-while loop
A do-while loop runs its body before testing its condition, so at least one pass takes place before it can stop repeating.
A do-while loop asks for a rating before checking whether another attempt is needed.

E

Early exit
An early exit ends a loop before its condition would normally stop it, often because a search result or stop command has been found.
An early exit prevents an input sentinel from being added to a running total or counted as data.
Edge case
An edge case is an input or starting state near a limit, such as empty data, one pass, or an endpoint, that can expose a hidden error.
An edge case with the sentinel entered first checks that an averaging loop handles no data.
Else-if chain
An else-if chain tests several conditions in order and runs only the first true branch, or its final else when no test succeeds.
An else-if chain assigns one grade even when the score satisfies several lower thresholds.
Equality operator
The equality operator == compares primitive values, but on object references such as strings it tests whether the objects are identical.
The equality operator accepts 3 == 3.0 because numeric conversion makes their values equal.
Exclusive or
Exclusive or is true when exactly one of two boolean operands is true; Java expresses this operation with the operator ^.
Exclusive or rejects a value divisible by both tested numbers when exactly one divisibility rule must hold.
Exhaustiveness
Exhaustiveness means a value-producing switch accounts for every possible selector value, so no input is left without a result.
A default case provides exhaustiveness for an int switch with only a few explicit labels.

F

Fall-through
Fall-through is execution continuing from one colon case into later case statements until an exit or the switch ends.
A missing break causes fall-through, so matching the first case prints its status message and then the next case's message too.
Fencepost problem
A fencepost problem arises when items and gaps have different counts, such as five printed values needing four separators.
A fencepost problem is avoided by printing a comma before every number except the first.
Flag
A flag is a boolean variable recording whether a condition has been met, such as a match found or a counterexample encountered.
A flag for any negative reading stays true after a match even if the final reading is positive.
For loop
A for loop groups initialization, a repeated condition test, and an update in one header, making counted repetition easy to follow.
A for loop visits the integers from 1 through 12 and adds each value to a running sum.

I

Infinite loop
An infinite loop keeps repeating without an exit, often because a required update is missing or a stopping value is never reached.
A counter that stays at 1 while testing i <= 5 produces an infinite loop unless another path exits.
Initialization
Initialization gives a variable its starting value; a for-loop initialization executes once before its first condition test.
Initialization sets a countdown to 8 before its header begins testing and decreasing it.
Inner loop
An inner loop is enclosed by another loop and performs a repeated task, such as visiting each column of the current row.
The inner loop starts again at column 1 on every row when its counter is correctly reset.
Input validation
Input validation checks whether an entered value meets the program's allowed conditions before that value is classified or processed.
Input validation rejects a score above 100 before a grade chain could classify it as "A".
Integer division
Integer division divides integral operands and discards any fractional part, so converting its completed result cannot restore that part.
Integer division gives 4 for 17 / 4, which is why an averaging calculation converts an operand first.
Iteration
An iteration is one execution of a loop body; the loop condition determines whether another pass can begin or repetition ends.
One iteration doubles the stored amount and increases the number of elapsed days by one.

L

Labeled break
A labeled break names an enclosing labeled statement as its exit target, allowing a nested search to leave an outer loop.
A labeled break ends both search loops immediately when the required pair is discovered.
Labeled continue
A labeled continue targets an enclosing labeled loop, abandoning the current work and proceeding toward that loop's next pass.
A labeled continue moves to the outer for update instead of checking the remaining columns.
Logical and
Logical and joins two boolean expressions and is true only when both are true; Java writes its short-circuit form as &&.
A logical and joins the lower and upper bounds when both must hold for an accepted temperature.
Logical or
Logical or joins two boolean expressions and is true when at least one is true, including when both are; its short-circuit form is ||.
A logical or accepts a command when it matches either of two allowed text labels.
Loop variable
A loop variable holds changing state used to control or describe repetition, such as the current count or candidate value.
The loop variable advances by three, so a bound check can stop even when an exact target is skipped.

M

Maximum
A maximum is the largest value in the processed data; a loop retains it by replacing the stored best value only when appropriate.
The maximum of several negative temperatures must start from data or a sufficiently low initial value.
Minimum
A minimum is the smallest value in the processed data, tracked by replacing the stored best value when a lower reading appears.
The minimum remains unchanged on a warmer day because the new reading is not smaller.

N

Negation
Negation reverses a boolean value with !, turning true into false and false into true without changing the underlying data.
Negation in !command.equals("stop") is true while the entered text differs from "stop".
Nested loop
A nested loop is a loop placed inside another loop, so its complete repetition is reached on each pass of the enclosing body.
A nested loop prints all columns of one row before the outer loop advances to the next row.

O

Off-by-one error
An off-by-one error makes a loop run one time too many or too few, commonly because its starting value or endpoint test is wrong.
An off-by-one error omits the final value when a loop uses < 12 but must include 12.
Operator precedence
Operator precedence determines how expressions group without parentheses; logical and groups more tightly than logical or.
Operator precedence makes a || b && c mean a || (b && c), even though or appears first.
Outer loop
An outer loop encloses another loop and controls how often the inner repetition begins, commonly advancing one row per pass.
The outer loop runs four times when a table needs four rows with a line break after each.
Overflow
Overflow occurs when an integer result exceeds its type's range and wraps to a different value without reporting an arithmetic error.
Overflow in an int accumulator corrupts a large sum even though every individual input fits an int.

P

Post-test loop
A post-test loop checks for another pass after its body has run; Java's do-while form places the condition after the closing brace.
A post-test loop can display a menu once even when the first command immediately ends it.
Prime number
A prime number is an integer at least 2 with no positive divisors other than 1 and itself; finding another divisor rules it out.
The prime number test rejects 91 when it reaches divisor 7, because the remainder is zero.

R

Remainder
A remainder is the value left by % after integer division; a zero remainder identifies a value divisible by the divisor.
The remainder in -13 % 2 is -1, so testing for a nonzero remainder recognizes this odd integer.
Running total
A running total is the sum of all values processed so far, updated on each pass and available for an intermediate or final report.
A running total printed after each addition shows progress before the last input is entered.

S

Scope
The scope of a local variable is the part of the program where that variable can be named; a block declaration ends at its closing brace.
The scope of a result declared before an if allows the following print to read the assigned value.
Search
A search examines candidates until it finds a required match or exhausts the available candidates without finding one.
A search can stop at the first number whose square exceeds the chosen limit.
Selector
A selector is the value evaluated by a switch and matched against its case labels to choose which code or expression runs.
The selector command sends the text "wait" to a case with that exact string label.
Sentinel
A sentinel is a designated input value that signals the end of a sequence and is checked before ordinary data processing.
A sentinel of -1 ends reading without becoming an extra item in the data count or sum.
Short-circuit evaluation
Short-circuit evaluation skips the right operand of && or || when the left operand already determines the whole result.
Short-circuit evaluation makes count != 0 && sum / count > 5 safe when both variables are ints.
Switch expression
A switch expression chooses and produces a value from matching cases, so its result can be assigned or used in another expression.
A switch expression assigns the number of days by selecting the case for the current month.

T

Threshold
A threshold is a cutoff separating outcomes; its comparison operator determines whether the cutoff itself belongs to a case.
A threshold written as score >= 30 includes 30, while score > 30 leaves that exact score out.
Tolerance
A tolerance is an allowed size of difference used when comparing computed numbers that may contain small rounding errors.
A tolerance of 1e-9 accepts the tiny difference between 0.1 + 0.2 and 0.3 in this calculation.
Trace table
A trace table records selected program values at consistent points during execution, making changing state and loop paths visible.
A trace table shows the total after each pass and the condition that eventually stops the loop.

U

Update
An update changes the loop's control state after a normally completed body; a for header places that operation after its condition.
The update i += 4 moves the counter from 2 to 6 after the first for-loop body finishes.

W

While loop
A while loop tests a boolean condition before each body execution and may perform zero passes when its first test is false.
A while loop keeps doubling an amount until the amount reaches or exceeds its target.

Y

Yield
The yield statement supplies a value from a block case of a switch expression, after any preceding calculations in that block.
A yield statement supplies 29 after a February case determines that the year is a leap year.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started