01 · Java foundations / LESSON 2 OF 102
Types, conditions, and loops
Express small business rules with ordinary Java.
Before this lesson: Set up Java and run a program
Understand the topic
Use int or long for whole numbers and boolean for conditions. String is a reference type; compare contents with equals rather than ==. Integer division truncates: 5 / 2 produces 2. Use BigDecimal for exact decimal money rather than double.
An if chooses a branch; a for or while repeats work. Local variables must be initialized before use. Trace values through each iteration rather than guessing from the last line.
EXAMPLE · JAVA
Main.java
public class Main {
public static void main(String[] args) {
int completed = 0;
for (int day = 1; day <= 7; day++) {
if (day % 2 == 1) completed++;
}
System.out.println(completed >= 4 ? "On track" : "Keep going");
System.out.println(completed);
}
}What to expect
On track, then 4 on the next line.
YOUR TURN
Put it into practice
- 01Replace for with while.
- 02Read a target with Scanner and handle zero.
- 03Predict 5 / 2 and 5 / 2.0 before running.
Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.
UNDER THE HOOD
Build the mental model
A variable has a declared type, a current value, and a scope. Operations follow type rules rather than the mathematical intention in your head.
- 01In 5 / 2, both operands are integers, so the result is 2 before any later assignment to double. Cast one operand before division to preserve the fraction.
- 02A condition must be boolean. Use braces to make branch boundaries explicit; nested if statements are easier to debug when each branch has one responsibility.
- 03A loop has an initial state, continuation condition, and update. Prove the update eventually makes the condition false.
A mistake worth avoiding
Comparing strings with == may appear to work for interned literals and fail for input values.
DEBUGGING ROOM
Something broke. Where do you look?
A progress percentage stays at zero until all tasks are complete.
Before revealing the diagnosis, write down your first investigation step.
CHECK YOUR UNDERSTANDING
What is double ratio = 3 / 2;?
BUILD IT YOURSELF
Build a progress calculator
- 1.Read completed and total from input.
- 2.Reject negative values or completed greater than total.
- 3.Print one decimal place; define the empty-list result.
Acceptance checklist
Lab completion is your self-report. Knowledge checks do not certify project quality.
RETRIEVE IT FROM MEMORY
When does Java choose the type of an arithmetic expression?
Revisit this lesson in three days after a successful check or lab.
Ready for the next step?
Choose types and trace a loop correctly.
Reading is separate from passing a knowledge check or completing a lab.