- Learn
- Computer Science & IT
- Programming
- Object-Oriented Programming with Java
- Conditions and Loops in Java
Conditions and Loops in Java
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
- 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 booleansUse the six comparison operators on numbers and characters, keep results in
booleanvariables, 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.
- Compare values and store the results as booleans
- Make a program run different statements depending on conditions, from a single
iftoelse ifchains, the conditional operator andswitch.- Run code conditionally with if and elseWrite
ifandif-elsestatements 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 chainsUse
else ifchains 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 switchUse
switchstatements andswitchexpressions to choose by the value of one variable, with arrow cases, several labels per case,defaultandyield, and recognize fall-through in the older colon form.
- Run code conditionally with if and else
- Write
while,do-whileandforloops that run the right number of times and stop when they should, and steer them withbreakandcontinue.- Repeat while a condition holds with whileWrite
whileloops that start, update and stop correctly, usewhile (true)withbreakfor open-ended repetition, and trace a loop pass by pass. - Run the body at least once with do-whileUse the
do-whileloop 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 loopsWrite
forloops 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 continueEnd a loop early with
break, skip the rest of one pass withcontinue, leave nested loops with a labeledbreak, and keep loops with early exits easy to follow.
- Repeat while a condition holds with while
- 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 valuesUse 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 digitsTrack 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 themWrite 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.
- Count, sum and average values
Conditions and Loops in Java study guide
1Build 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
| Operator | Question |
|---|---|
< | 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
equalsorequalsIgnoreCase. - Compare computed decimals with an appropriate tolerance.
- Use
n % 2 != 0for 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.
2Choose 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
elseattaches to the nearest unmatchedif. - 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
ifstatements 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
switchfor 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.
3Control 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--;
}
| Point | product | n |
|---|---|---|
| Before the loop | 1 | 3 |
| After pass 1 | 3 | 2 |
| After pass 2 | 6 | 1 |
| After pass 3 | 6 | 0 |
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
whileloop 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
| Header | Values used by the body | Passes |
|---|---|---|
int i = 0; i < 5; i++ | 0 through 4 | 5 |
int i = 0; i <= 5; i++ | 0 through 5 | 6 |
int i = 10; i >= 1; i-- | 10 through 1 | 10 |
int i = 0; i <= 20; i += 5 | 0, 5, 10, 15, 20 | 5 |
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
| Task | Useful form | Reason |
|---|---|---|
| Visit a known range | for | Start, bound, and step sit together. |
| Repeat until input or state changes | while | The test can reject the first pass. |
| Ask first, then check | do-while | The 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
forfor ranges,whilefor 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
breakleaves its target immediately.- For-loop
continuestill runs the header update. - While-loop
continuecan 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.
4Build 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,
% 10extracts a digit and/ 10removes 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 processed | Action | Total after the pass |
|---|---|---|
| 1 | Subtract 1 | -1 |
| 2 | Add 2 | 1 |
| 3 | Subtract 3 | -2 |
| 4 | Add 4 | 2 |
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
1Turn a program rule into a condition
12 steps
- 1IntroductionStart 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.
- 2ExplanationGive a comparison a name
A comparison produces a
boolean, which can be stored for later use.int age = 17; boolean isAdult = age >= 18;Here
isAdultstoresfalse. The expressionif (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. - 3ExampleRead the operator precisely
With
a = 7andb = 10,a < bis true anda >= bis false. The comparisonsa != banda == 7are 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. Useif (done)to test the existing value. - 4TipMatch the characters in input
A non-null string such as
commandhas text contents and an object identity.command.equals("quit")tests the characters;command == "quit"tests identity.Use
equalsIgnoreCaseonly when case differences should be accepted. For example, "Quit" and "quit" match with that method but differ withequals. Negating an exact match gives!command.equals("quit"). - 5ExampleCheck 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 with0.3is false, but the absolute difference is below this tolerance, makingclosetrue. The tolerance test accepts a small difference; it does not change either stored value or make them exactly equal. - 6ChallengeTest a negative odd number
A program uses
n % 2 == 1to detect odd integers. What does it miss whennis -11, and how can the test be repaired?---reveal---
-11 % 2is-1, so the test is false even though -11 is odd. Usen % 2 != 0: divisibility by 2 has a zero remainder, and either positive or negative nonzero remainders identify odd integers. - 7ExplanationRequire 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. - 8Key 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. - 9ExamplePut 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 anArithmeticException. With||, a true left operand similarly skips the right one. - 10ChallengeDistinguish grouping from reading order
With
a = true,b = false, andc = false, doa || b && cand(a || b) && cgive 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 ofa || band alsoc; sincecis false, that result is false. - 11ChallengeCombine 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 > 5must also succeed safely. Write the condition so count 0 cannot reach division.---reveal---
count != 0 && (load >= 6 && load <= 14 || override) && 100 / count > 5The first guard rejects zero. The grouped choice accepts the range or override; only a surviving path reaches division.
- 12RecapCheck 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.
2Choose one path and produce a result
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow the path Java reaches
- 2ExampleRun exactly one branch
- 3ExplanationKeep the result after the decision
- 4ChallengeFind an unconditional print
- 5TipMake the inner choice explicit
- 6ExampleVisit thresholds in the right order
- 7ConnectionSeparate independent actions
- 8ChallengeRepair a missing endpoint
- 9ExplanationChoose by one exact value
- 10ExampleAssign the chosen value
- 11ExplanationGive a block its value
- 12ChallengeTrack colon fall-through
- 13ChallengeChoose a structure for a mixed rule
- 14RecapInspect the decision boundaries
3Trace a loop from its first pass to its exit
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionWatch the state change
- 2ExplanationTest before entering
- 3ExampleTrace a changing product
- 4ChallengeAvoid a skipped stop value
- 5ExplanationRun once before deciding
- 6ExampleRead a rating before testing it
- 7ChallengePredict an accepted endpoint
- 8ConnectionMove counting into the header
- 9ExampleCount steps larger than one
- 10ChallengeKeep the intended endpoint
- 11TipCheck for an empty body
- 12ExampleStop at the first match
- 13ExplanationSkip the rest of one pass
- 14ChallengeFind the skipped update
- 15ExplanationGive an outer loop an exit name
- 16ConnectionKeep switch and loop exits distinct
- 17ChallengeCombine a skip and an early exit
- 18RecapTrace the next destination
4Build results that describe all processed data
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what must survive a pass
- 2ExplanationSeparate a count from a sum
- 3ExampleRead and reject the sentinel
- 4ExampleFollow the state through input
- 5ExplanationPreserve the average fraction
- 6ChallengeAverage only accepted readings
- 7TipMake arithmetic wide early enough
- 8ExampleKeep the best reading
- 9ChallengeRecord where a tie occurs
- 10Key InsightLet a flag remember a match
- 11ExplanationSearch for a divisor
- 12ExampleExtract digits in a fixed order
- 13ChallengeKeep a negative reading remembered
- 14ExplanationComplete every row before advancing
- 15ExampleCount changing row sizes
- 16ChallengeFix a separator at the first item
- 17TipChoose revealing trace rows
- 18ChallengeCombine a changing bound with selection
- 19RecapCheck the meaning of each result
Conditions and Loops in Java practice questions
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++;
}
Show answerHide answer
Question 2 of 10
What is printed?
int level = 9;
do {
level -= 2;
} while (level > 8);
System.out.println(level);
Show answerHide answer
Question 3 of 10
How many body executions occur?
for (int k = 2; k <= 17; k += 4) {
System.out.println(k);
}
Show answerHide answer
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 + " ");
}
Show answerHide answer
Question 5 of 10
What are amount and steps after this loop?
int amount = 3;
int steps = 0;
while (amount < 40) {
amount *= 2;
steps++;
}
Show answerHide answer
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;
}
}
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
int index. Where can code read that variable?Show answerHide answer
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);
Show answerHide answer
Question 10 of 10
Why does this loop never finish?
int n = 1;
while (n != 12) {
n += 2;
}
Show answerHide answer
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
-13 % 2 != 0?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
String command contains text read from input. What expression tests whether its contents are exactly "pause"?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
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);
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");
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");
}
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;
};
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
int sum = 15; and int count = 0;, what happens when evaluating count == 0 || sum / count > 4?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);
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
member && !blocked || guest && codeValid is true. What condition rejects exactly those entries it would allow?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
int sum = 17; and int count = 4;, what does (double) (sum / count) evaluate to?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
max to 0 give the wrong answer?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);
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("*");
}
}
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;
}
}
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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);
}
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);
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
do { ... } while (value < 10 || value > 14);. How many inputs does it consume?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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);
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++;
}
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--;
}
}
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);
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Math.abs((0.1 + 0.2) - 0.3) < 1e-9 be true while (0.1 + 0.2) == 0.3 is false?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
(double) sum / count. What is the result and the needed repair?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");
}
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
!(false || true)?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");
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;
};
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++;
}
}
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?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++;
}
}
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
(double) sum / count print, and what repair is needed?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);
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulator
Assignment operator
= stores a value in a variable; the resulting expression has that assigned value, not a comparison result.if (done = true) changes the flag before the branch runs.B
Block
Boolean value
true or false; comparisons produce it, and Java conditions require an expression of this type.isFull becomes true when a container reaches its capacity.Boundary test
Branch
Break
C
Case label
Comparison operator
<= includes a score equal to the upper limit in a permitted range.Conditional operator
?: selects one of two expression values from a boolean condition, allowing a short two-way value choice.label to "even" or "odd" according to a remainder test.Continuation condition
Continue
Counter
Counterexample
D
Dangling else
De Morgan's laws
Digit extraction
% 10, ready to use before division removes it.Do-while loop
E
Early exit
Edge case
Else-if chain
Equality operator
== compares primitive values, but on object references such as strings it tests whether the objects are identical.3 == 3.0 because numeric conversion makes their values equal.Exclusive or
^.Exhaustiveness
F
Fall-through
Fencepost problem
Flag
For loop
I
Infinite loop
i <= 5 produces an infinite loop unless another path exits.Initialization
Inner loop
Input validation
Integer division
17 / 4, which is why an averaging calculation converts an operand first.Iteration
L
Labeled break
Labeled continue
Logical and
&&.Logical or
||.Loop variable
M
Maximum
Minimum
N
Negation
!, turning true into false and false into true without changing the underlying data.!command.equals("stop") is true while the entered text differs from "stop".Nested loop
O
Off-by-one error
< 12 but must include 12.Operator precedence
a || b && c mean a || (b && c), even though or appears first.Outer loop
Overflow
P
Post-test loop
Prime number
R
Remainder
% after integer division; a zero remainder identifies a value divisible by the divisor.-13 % 2 is -1, so testing for a nonzero remainder recognizes this odd integer.Running total
S
Scope
Search
Selector
command sends the text "wait" to a case with that exact string label.Sentinel
Short-circuit evaluation
&& or || when the left operand already determines the whole result.count != 0 && sum / count > 5 safe when both variables are ints.Switch expression
T
Threshold
score >= 30 includes 30, while score > 30 leaves that exact score out.Tolerance
1e-9 accepts the tiny difference between 0.1 + 0.2 and 0.3 in this calculation.Trace table
U
Update
i += 4 moves the counter from 2 to 6 after the first for-loop body finishes.W
While loop
Y
Yield
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.