Operators. Practical Tasks
Below are fourteen hands-on Java exercises on control flow: the conditional statements if, if-else, if-else-if, the switch statement, the while, do-while, for, and for-each loops, and the break, continue, and return statements plus the System.exit() method. The tasks progress from a simple even-number check to a factorial, an array search, and a properly guarded program exit. Most tasks have a ready solution on Patreon, and some also come with a video walkthrough. Before you start, we recommend reviewing the lessons on the if statement, the switch statement, loops in Java, the break and continue statements, the return statement, and the System.exit() method.
Even or Odd Number
- Pass a number as a program argument.
- If the number is odd, print it.
- Use the if statement.
- Use Integer.parseInt() to convert the String to int.
Number between 0 and 10
- Use the Scanner class to read an integer.
- If the number is between 0 (inclusive) and 10 (exclusive), print "Positive number less than 10 or zero". Otherwise, print "Positive number greater than 10 or negative".
- Use the if-else statement.
Common mistake
Decide carefully whether the boundary values (0 and 10) belong to the range. An off-by-one slip in a condition like n >= 0 && n < 10 is one of the most frequent beginner errors: mixing up < and <= sends the number 10 to the wrong branch.
Days of the Week with if-else-if
- Pass a number from 1 to 7 as a program argument.
- Print "Monday" if the number is 1, "Tuesday" for 2, and so on. Print "Weekend" for 6 or 7.
- Use the if-else-if structure.
Watch the solution in the video.
Days of the Week with switch
Rewrite the previous task using the switch statement. Pay attention to the "6 or 7" case: in a switch it is convenient to write it as two case labels leading to the same action.
Watch the solution in the video.
Ten Lines with a while Loop
Print 10 lines: "Task1", "Task2", …, "Task10". Use the while loop.
Watch the solution in the video.
Multiples of 5 with a do-while Loop
Print all numbers from 1 to 100 that are divisible by 5 using the do-while loop.
Keep in mind
The body of a do-while loop runs at least once — the condition is checked only after the first iteration. In this task the difference from while is invisible, but remember it: if the starting number were already greater than 100, do-while would still process it once.
Watch the solution in the video.
Five Characters with a for Loop
Print 5 characters in a row starting with 'h'. Use the for loop.
Hint
A for loop counter does not have to be an int — a char works too: for (char c = 'h'; c < 'h' + 5; c++). Characters in Java are an integral type, so arithmetic and the increment operator apply to them.
Watch the solution in the video.
Garland, Part 2
Extend the Garland, Part 1 task with the following:
- Use the Scanner class to input a number from 1 to 4.
- If the input is 1 – run the blink method, 2 – check the first bulb, 3 – run the running-light method, 4 – print the garland state to the console.
- Use the switch statement for mode selection.
- Update the blink method: it should blink the garland 10 times (use the for loop).
- Update the running-light method: it should repeat the operation 10 times (use the for loop).
Factorial with a for Loop
Calculate the factorial using a for loop. Example:
n! = 1*2*...*n;
0! = 1;
5! = 1*2*3*4*5; The number n is generated randomly — use (int) (Math.random() * 6). It must be in the range from 0 to 5.
Array Sum with a for-each Loop
- Create an int[] array with a few numbers, for example {2, 4, 6, 8, 10}.
- Calculate the sum of all its elements.
- Use a for-each loop.
- Print the result to the console.
Array Search with break
- Create an int[] array with a few numbers and a target variable holding the number to search for.
- Iterate over the array with a for loop.
- As soon as the current element equals target, print its index and stop the loop immediately with the break statement.
- If the element is not found after the loop, print "Not found".
Odd Numbers from 1 to 20 with continue
- Set up a for loop from 1 to 20 inclusive.
- If the current number is even, skip the iteration with the continue statement.
- Print the remaining (odd) numbers to the console.
Primality Check with an Early return
- Write a method public static boolean isPrime(int n).
- Check possible divisors from 2 to n − 1.
- As soon as a divisor is found, immediately return false with the return statement, without waiting for the loop to finish.
- If no divisor is found, return true.
- Call the method for a few numbers (for example, 7, 15, 23) and print the result.
Guarded Program Exit with System.exit()
- Use the Scanner class to read an integer from the console.
- If the number is negative, print "Error: the number must not be negative" and immediately terminate the program by calling System.exit(1).
- If the number is non-negative, print its square to the console.
Frequently Asked Questions
What is the difference between while and do-while in Java?
A while loop checks the condition before entering the body: if it is false right away, the body never runs. A do-while loop checks the condition after each iteration, so its body is guaranteed to run at least once. do-while is handy for menus and for re-prompting the user for input.
When should I use switch instead of an if-else-if chain?
switch fits when one variable is compared against a set of specific values (a day number, a menu option): the code reads more easily and repeats the variable name less. An if-else-if chain is needed when the conditions are heterogeneous — ranges, comparisons of several variables, or compound boolean expressions.
What happens if you forget break in a switch statement?
Execution “falls through” to the next case: after the matching label, all subsequent branches run until the nearest break or the end of the block. Sometimes this is intentional — for example, letting the values 6 and 7 lead to the same "Weekend" action — but more often a missing break is a hard-to-spot bug.
How do I generate a random integer between 0 and 5 in Java?
Use (int) (Math.random() * 6): Math.random() returns a double from 0 (inclusive) to 1 (exclusive), multiplying by 6 gives a range from 0 to 5.999…, and the cast to int drops the fractional part. The multiplier is 6, not 5 — otherwise the number 5 could never appear. An alternative is new Random().nextInt(6).
Why can a factorial calculation return a wrong result?
Factorials grow extremely fast: 13! already does not fit into an int, and 21! does not fit into a long. Overflow in Java happens silently — the result simply becomes incorrect (it may even turn negative). For n up to 5, as in this task, int is enough; for larger n use long or BigInteger.
Comments