Explain it simply
Explain it simply
This lesson teaches nothing new. It is four tasks for rewriting, with your own hands, what you learned in the Basic and Intermediate chapters. Nobody learns to play football by watching videos, and nobody learns to code by reading it. You remember it after you write it, run it, get it wrong and fix it.
Spend at least five to ten minutes on each task before you look at the reference answer below. Before running anything, write down on paper what you expect it to print, then compare. Wherever the two differ is exactly the spot you have not understood yet.
Problem → Why → Solution
The problem: it compiles, it runs, and it is wrong
In the first attempt below, all three tasks compile and nothing throws. Yet 30°C comes out as 62.0°F (the right answer is 86.0), and day 3 prints Thursday and "Invalid day" along with Wednesday. For an array of all-negative temperatures, max comes out as 0, a value that is not even in the array.
Testing only with the task's sample data (30.0, day 3, positive numbers) hides some of these bugs. The real work of practice is not getting one answer out; it is hunting for the inputs where your code goes wrong.
double celsius = 30.0;
double fahrenheit = celsius * (9 / 5) + 32; // 9 / 5 is the int 1
System.out.println(fahrenheit); // 62.0, not 86.0
int day = 3;
switch (day) {
case 3: System.out.println("Wednesday"); // no break...
case 4: System.out.println("Thursday"); // ...falls through
default: System.out.println("Invalid day");
}
int[] temps = {-5, -12, -3};
int max = 0; // 0 is not in the array
for (int t : temps) if (t > max) max = t; // max stays 0, not -3Why doesn't the compiler warn you?
All three bugs are legal Java. Dividing two ints yields an int, a case without break falls into the next one, and starting max at 0 is perfectly valid. The compiler checks syntax and types, but it cannot know whether that is what you meant. Only a predicted output and a few boundary tests catch these.
Core concept: the trap inside each task
Each of the four tasks pairs one concept you learned with one trap. Knowing the trap before you start writing saves a lot of debugging time.
Task 1: precedence and types
F = C × 9/5 + 32. In celsius * 9.0 / 5 + 32, * and / evaluate left to right: 30.0 * 9.0 = 270.0, then / 5 = 54.0, then + 32 = 86.0. Putting 9 / 5 in its own parentheses makes it an int division that yields 1. One double literal such as 9.0 keeps the whole calculation in double.
Task 2: two forms of switch
In a classic switch (case 3:), a missing break falls through into the following cases. The arrow form (case 3 -> ...), standard since Java 14, never falls through and can yield a value directly. Used as an expression, String dayName = switch (day) { ... }; must cover every int, so the default branch is required and values like 0 or 8 cannot be forgotten.
Task 3: what an accumulator starts at
sum starts at 0, the neutral value for addition. max should not start at 0; seed it with numbers[0] so an all-negative array still works. Updating both sum and max in the same loop walks the array only once.
Task 4: a class bundles data and behaviour
Book keeps title, author and price as private final fields, filled once by the constructor. printInfo() uses the object's own fields, so main never needs to know a book's internals. Putting the three objects in a Book[] array and looping means adding more books never changes the printing code.
- Write the expected output first
- Run the code
- Compare with your prediction
- Try boundary inputs to break it
When your prediction is wrong, it is your understanding, not only the code, that needs fixing.
General pattern
double result = input * 9.0 / 5 + OFFSET; // keep one operand double
String label = switch (code) {
case 1 -> "first";
case 2 -> "second";
default -> "unknown: " + code; // no fall-through, no break
};
int best = values[0]; // seed with real data
int total = 0;
for (int v : values) { best = Math.max(best, v); total += v; }Avoid integer division with one double literal, avoid fall-through with an arrow switch, and seed accumulators like max with a real element.
Reference answer: all four tasks
The reference answer below solves all four tasks. Its inputs are fixed in the code instead of read from the keyboard with Scanner, so every run prints the same output and no Scanner import is needed. The Book class sits below Practice1, which holds main, so java Practice1.java runs the whole file directly with no separate compile step. Compare only after finishing your own answer; different variable names do not matter, matching output does.
public class Practice1 {
public static void main(String[] args) {
// Task 1: Celsius to Fahrenheit
double celsius = 30.0;
double fahrenheit = celsius * 9.0 / 5 + 32;
System.out.println("Task 1: " + celsius + " C = " + fahrenheit + " F");
// Task 2: switch for the day name
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day: " + day;
};
System.out.println("Task 2: day " + day + " is " + dayName);
// Task 3: max and sum of an array
int[] numbers = {12, 45, 7, 89, 23, 56, 3, 90, 15, 34};
int max = numbers[0];
int sum = 0;
for (int n : numbers) {
if (n > max) {
max = n;
}
sum += n;
}
System.out.println("Task 3: max = " + max + ", sum = " + sum);
// Task 4: three Book objects
Book[] books = {
new Book("Java for Beginners", "Ko Zaw", 12.50),
new Book("Clean Methods", "Ma Hnin", 18.00),
new Book("OOP in Practice", "U Tun", 21.99),
};
System.out.println("Task 4:");
for (Book b : books) {
b.printInfo();
}
}
}
class Book {
private final String title;
private final String author;
private final double price;
Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
void printInfo() {
System.out.printf(" %s by %s - $%.2f%n", title, author, price);
}
}Code breakdown
- Task 1: a double literal
double fahrenheit = celsius * 9.0 / 5 + 32;9.0 is a double, so the division is floating-point and the result is 86.0. Concatenated into a String, the double shows as 86.0.
- Task 2: switch expression
String dayName = switch (day) {The switch produces a value that goes straight into dayName. Arrow cases need no break and never fall through.
- Task 2: the default branch
default -> "Invalid day: " + day;A switch expression must produce a value for every int, so it will not compile without default. With day = 8 you would get "Invalid day: 8".
- Task 3: seed max with real data
int max = numbers[0];Starting from the first element guarantees max is a value from the array, even when every number is negative. For this data, max is 90 and sum is 374.
- Task 4: formatting the price
System.out.printf(" %s by %s - $%.2f%n", title, author, price);%.2f prints 18.0 as 18.00 with two decimals; plain string concatenation would show "18.0".
Task 1: 30.0 C = 86.0 F
Task 2: day 3 is Wednesday
Task 3: max = 90, sum = 374
Task 4:
Java for Beginners by Ko Zaw - $12.50
Clean Methods by Ma Hnin - $18.00
OOP in Practice by U Tun - $21.99In real projects
In real projects
These tasks are small, but their traps show up in production. Weather apps and IoT sensor dashboards are full of unit-conversion formulas, and an integer-division bug that loses the decimals can go unnoticed for a long time because the numbers are only slightly off. Calendar and scheduling code has many switches that turn day or month numbers into names, and a fall-through bug there can show the same day twice.
Model classes like Book are the basis of every online shop. A real shop would not store money in a double, though: doubles drift slightly in sums like 0.1 + 0.2. Shops use BigDecimal or a long count of the smallest unit, such as cents. This practice set uses double only so you can practise formatting.
Common mistakes
Common mistakes
Letting 9 / 5 become an int
celsius * (9 / 5) + 32 evaluates 9 / 5 first and gets the int 1. The result is 62.0 and no error appears. Use 9.0 / 5 or 1.8.
Forgetting break in a classic switch
Without break after case 3:, execution continues from Wednesday into Thursday, Friday and on to default. The arrow form removes this problem entirely.
Starting max at 0
It looks right with positive test data, but for {-5, -12, -3} it returns 0. Start from numbers[0] or Integer.MIN_VALUE.
Putting Book above the class with main
java Practice1.java runs the first class in the file. If Book comes first, you get "can't find main(String[]) method in class: Book".
Best practices
How to practise well
- Split a task into small steps and run after each one, instead of writing 50 lines before the first run
- Test one normal value, one boundary value (0, a negative, 7 and 8) and one invalid value
- Grow Task 3's array to 20 elements and re-check your max and sum logic
- Once the answer is right, rename and extract methods until the code reads clearly
Mini challenge
Three new tasks: leap years, vowels and a bank account
Practise fundamentals and OOP with three more tasks: write isLeapYear(int year), countVowels(String text) and a BankAccount class whose balance can never go negative. Test them with boundary values.
- isLeapYear() returns true for 2024, false for 2023, false for 1900 and true for 2000
- countVowels() counts a, e, i, o and u regardless of case
- BankAccount keeps balance private; deposit and withdraw return false for invalid amounts
- A withdrawal larger than the balance must be refused
public class Practice1b {
static boolean isLeapYear(int year) {
// TODO: divisible by 400 -> true; by 100 -> false; by 4 -> true
return false;
}
static int countVowels(String text) {
// TODO: loop over the characters, count a e i o u (any case)
return 0;
}
public static void main(String[] args) {
// TODO: test 2024, 2023, 1900, 2000; count vowels in "Hello Java";
// deposit 50000, deposit -10, withdraw 80000, withdraw 20000
}
}
class BankAccount {
// TODO: private owner and balance (whole kyat, a long)
// boolean deposit(long amount), boolean withdraw(long amount), getters
}Expected: true/false/false/true for the four years, 4 vowels in "Hello Java", true/false/false/true for the deposits and withdrawals, and finally Su Su has 30000 kyat.
Show hint
Check the leap-year rule starting from the most specific case, 400. For vowels, loop over text.toLowerCase().toCharArray() and use an arrow switch such as case 'a', 'e', 'i', 'o', 'u' -> count++.
Show solution
public class Practice1b {
static boolean isLeapYear(int year) {
if (year % 400 == 0) return true;
if (year % 100 == 0) return false;
return year % 4 == 0;
}
static int countVowels(String text) {
int count = 0;
for (char c : text.toLowerCase().toCharArray()) {
switch (c) {
case 'a', 'e', 'i', 'o', 'u' -> count++;
default -> { }
}
}
return count;
}
public static void main(String[] args) {
for (int year : new int[] {2024, 2023, 1900, 2000}) {
System.out.println(year + " leap? " + isLeapYear(year));
}
System.out.println("Vowels in \"Hello Java\": " + countVowels("Hello Java"));
BankAccount account = new BankAccount("Su Su");
System.out.println("deposit 50000: " + account.deposit(50_000));
System.out.println("deposit -10: " + account.deposit(-10));
System.out.println("withdraw 80000: " + account.withdraw(80_000));
System.out.println("withdraw 20000: " + account.withdraw(20_000));
System.out.println(account.getOwner() + " has " + account.getBalance() + " kyat");
}
}
class BankAccount {
private final String owner;
private long balance; // whole kyats, never negative
BankAccount(String owner) {
this.owner = owner;
}
boolean deposit(long amount) {
if (amount <= 0) return false;
balance += amount;
return true;
}
boolean withdraw(long amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
long getBalance() { return balance; }
String getOwner() { return owner; }
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Predict the output before running and study wherever your prediction was wrong
- One double literal (9.0) avoids the integer-division trap
- Arrow-form switch never falls through, and as an expression it needs a default
- Seed accumulators like max with the array's first element
- Test with normal, boundary and invalid input every time