Basic Operations in Java: Arithmetic and Logical. Practical Tasks
Below are six practice tasks on the basic Java operations: arithmetic, bitwise, logical, the ternary conditional operator, increment/decrement, and assignment. They reinforce the material of this section — from the classic even-number check to a «garland» built on bit masks. Every task has a solution on Patreon, and the garland also comes with a video walkthrough.
Check if a Number Is Even
- Create a program that tells whether an integer entered by the user is even or not.
- Use the Scanner class to read the number.
- If the user enters a non-integer, display an error message.
Hint
You don’t have to catch InputMismatchException to report a bad input: the scanner.hasNextInt() method checks in advance that the next token is an integer, and only then is it safe to call nextInt().
Minimum by Absolute Value
- Create a program that displays the smallest (by absolute value) of three real numbers entered by the user.
- Use the ternary conditional operator to calculate the absolute value.
- Read the numbers with the Scanner class.
Garland, Part 1
You have a garland of 32 bulbs. Each bulb has two states — on or off — so the whole garland fits neatly into a single int variable: it holds exactly 32 bits. At the start of the program, randomly determine which bulbs are on. Control the garland with bitwise operations. Implement the following methods:
- the
blinkmethod, which makes the garland blink once (the~operator); - the
runmethod, which starts a running light effect (the<<or>>operator); - the
isFirstLampOnmethod, which checks whether the bulb in the first position is on (bit masking with&); - a method that prints the current state of the garland. Use
Integer.toBinaryString(a)to get the binary representation of the number.
Subtle point
If the highest (32nd) bulb is on, the int value is negative, and the >> shift will «multiply» it: new ones will keep appearing on the left. For a running light in that direction, use the unsigned shift >>>.
Watch the solution in the video.
Average of Numbers
Calculate the average value of three real numbers passed to the program as command-line arguments. To convert from String to double, use Double.parseDouble(String s).
Countdown with an Accumulator
- Create a program that asks the user for a number
N— how many numbers to read. - Run a countdown using decrement (
n--): on each step, read one real number with Scanner and add it to a running total using a compound assignment operator (sum += x). - After each step, print a message such as
"Steps left: " + n + ", running total: " + sum.
Quirk
The loop condition while (n-- > 0) uses postfix decrement: n is compared to 0 at its current value first, and only decremented afterward. Because of this, the loop body still runs when n starts at 0 — if that's not what you want, use prefix --n or check before the loop.
Discount Eligibility
- Create a program that asks for a customer's age and purchase amount.
- A discount applies if (age ≥ 65 or age ≤ 12) and the purchase amount ≥ 1000 — express this with logical operators
&&,||, and parentheses. - Print the result using string concatenation:
"Age: " + age + ", amount: " + amount + ", discount: " + (eligible ? "yes" : "no").
Subtle point
Drop the parentheses around age ≥ 65 || age ≤ 12 and the result can change: && binds tighter than ||, so the unparenthesized expression parses as (age ≥ 65) || (age ≤ 12 && amount ≥ 1000) — a completely different rule.
Verify your code
While writing your programs, keep an eye on the Code Style Recommendations.
Frequently Asked Questions
How do I check whether a number is even in Java?
The classic way is the remainder: n % 2 == 0. A quirk with odd numbers: the condition n % 2 == 1 fails for negative values (for -3 the remainder is -1), so oddness is checked as n % 2 != 0. The bitwise variant (n & 1) == 0 works for any sign.
How do I get the absolute value without Math.abs()?
With the ternary operator: x < 0 ? -x : x. For real numbers that is enough. For int there is an edge case: the absolute value of Integer.MIN_VALUE does not fit into an int, so -x returns the same negative number.
Why is int a good fit for a garland of 32 bulbs?
An int in Java takes exactly 32 bits, so each bulb is one bit of the number: 1 means on, 0 means off. The inversion ~ blinks all the bulbs, shifts move the light, and a mask with & reads the state of a specific bulb. For 64 bulbs you would use a long.
Why does Scanner reject a number with a decimal point?
The nextDouble() method parses the number using the system locale: in many European locales the decimal separator is a comma, so typing 3.14 throws an InputMismatchException. To accept the dot regardless of the system settings, configure the scanner: scanner.useLocale(Locale.US).
What's the difference between n-- and --n?
Postfix n-- returns the current value of n and decrements it afterward; prefix --n decrements first and returns the new value. In while (n-- > 0) that means the loop body still runs when n is 0 — the comparison uses the old value.
What happens if you drop the parentheses in a && / || condition?
The result can change: && has higher precedence than ||, so Java groups the operands around && first. For example, a || b && c means a || (b && c), not (a || b) && c — if you need the second reading, parentheses are required.
Comments