Java basics series: 1. JVM and JDK · 2. Hello World and the three kinds of errors · 3. Variables and types · 4. Operators and branching · 5. Loops and methods · 6. Arrays and strings · 7. Console and text files · 8. Byte streams and serialization
This post covers two things every program needs: doing something many times (loops) and splitting code into small reusable pieces (methods). Afterwards you’ll be able to explain the call stack, variable scope and why Java is always pass-by-value, three interview favourites. Read operators and branching first; next up is arrays and strings, and this lays the groundwork for the data structures and algorithms posts.
1. Loops
Key idea: when some statements need to run repeatedly, wrap them in a loop instead of copying them. Every loop needs a stop condition and a statement that changes it, so the loop is guaranteed to end.
A recipe for any loop: (1) identify the statements that repeat, (2) wrap them in a loop, (3) write the stop condition and the statement that updates the control variable.
while and do-while
// while: checks the condition FIRST, so the body may never run
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--; // forget this line and the loop never ends
}
// do-while: runs the body FIRST, then checks, so it always runs at least once
Scanner in = new Scanner(System.in);
int choice;
do {
System.out.print("Pick 1-3: ");
choice = in.nextInt();
} while (choice < 1 || choice > 3);
do-whilefits the “keep asking until the input is valid” pattern.- Loop bugs usually come from two places: a wrong condition (
<=instead of<, the classic off-by-one, being out by exactly one) or a body that never changes the condition (an infinite loop). - An empty body is legal, as in
while (!ready()) ;. But this kind of busy-waiting (the CPU spinning just to ask “done yet?”) burns CPU.
for and for-each
for (int i = 0; i < 5; i++) { // init; condition; update
System.out.print(i + " ");
}
int[] prices = {120, 80, 45};
for (int price : prices) { // for-each: no index, and you can't reassign elements
System.out.print(price + " ");
}
Nested loops
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%d×%d=%-3d", j, i, i * j);
}
System.out.println();
}
The inner print runs 1 + 2 + … + 9 = 45 times, which is n(n+1)/2. Counting operations like this is how you estimate complexity: two nested loops are usually O(n²), and with n = 10⁵ that’s 10¹⁰ operations, which won’t finish in time.
The course’s rule of thumb: don’t nest more than three levels; beyond that, extract a method or change the algorithm (a HashMap, sorting…). The triangle above is a variant; the full 9×9 multiplication grid is exercise 3.
break, continue and labels
for (int n : numbers) {
if (n < 0) continue; // skip the rest of this iteration
if (n == 0) break; // leave the loop entirely
process(n);
}
outer:
for (int[] row : grid) {
for (int cell : row) {
if (cell == target) break outer; // leave the outer loop too
}
}
break leaves the nearest loop; break outer leaves the loop carrying the label (a name written before the loop) outer. continue only skips the rest of the current iteration.
Two classic textbook examples: predict the output before you run them
int sum = 0, number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100) break; // stop once the total reaches 100
}
// number = 14, sum = 105 (1 + 2 + … + 13 = 91 < 100; adding 14 crosses it)
sum = 0; number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11) continue;
sum += number;
}
// sum = 189: 1..20 adds up to 210, minus 10 and 11
In the second example, number++ comes before continue, so the while loop can’t get stuck. Move it to the end of the body and you walk straight into the trap below.
2. Methods
Key idea: group a block of code that does one thing into a method so it’s reusable, readable and testable. In Java every “function” is a method, because it has to live inside a class.
// modifier return type name parameters
static double bmi(double weightKg, double heightM) {
return weightKg / (heightM * heightM);
}
static void printReceipt(String customer) { // void: returns nothing
if (customer == null) return; // return; ends a void method early
System.out.println("Customer: " + customer);
}
static methods are called through the class name; instance methods are called on an object (see the OOP post). A signature is the name plus the parameter types. The return type isn’t part of it, so you can’t overload two methods that differ only in return type.
The parts of a method, with the English terms you’ll meet:
public static int max(int num1, int num2) { // method header
int result = num1 > num2 ? num1 : num2; // method body: everything inside {}
return result; // return value
}
int z = max(x, y); // x and y are arguments
| Term | Meaning | In the example |
|---|---|---|
| Method header | modifiers, return type, name, parameter list | public static int max(int num1, int num2) |
| Method body | the statements inside {} |
the two lines inside |
| Formal parameter (usually just parameter) | a variable declared in the header | num1, num2 |
| Actual parameter / argument | the value passed at the call site; it is copied into the parameter, which is why Java is pass-by-value | x, y |
| Method signature | name + parameter types | max(int, int) |
| Return value | what return hands back to the caller |
assigned to z |
The call stack and stack frames
Each method call pushes a stack frame (a slot holding the parameters, the local variables and the return address) onto the current thread’s stack. When the method finishes, its frame is popped. Think of a stack of plates: the last one put on is the first one taken off (LIFO, last in first out).
sequenceDiagram
participant main
participant total
participant tax
main->>total: total(items) [push frame total]
total->>tax: tax(subtotal) [push frame tax]
tax-->>total: return 8.0 [pop frame tax]
total-->>main: return 108.0 [pop frame total]
What this means in practice:
- Every thread has its own stack (roughly 512 KB–1 MB by default, tuned with
-Xss). Recursion that goes too deep throwsStackOverflowError. - Local variables live on the stack, so each thread has its own copy and needs no synchronization. Objects live on the heap and can be shared between threads.
- In an exception’s stack trace, the top line is the most recently pushed frame.
- Since Java 21, virtual threads (lightweight threads managed by the JVM) keep their stacks on the heap, which is how you can have millions of them. The frame model is unchanged.
Variable scope
- A local variable lives only inside the method (or
{}block) that declares it; other methods can’t see it. - A parameter is really a local variable that gets its value at call time.
- A variable declared in
for (int i...)or inside a loop body exists only within that loop, so two separate loops can both usei. - Java forbids shadowing a local variable that is still in scope: you can’t declare
iin a loop if a localiwas declared above it. A localideclared after the loop is fine, because the loop’siis out of scope by then.
static void demo() {
for (int i = 0; i < 3; i++) { }
for (int i = 0; i < 3; i++) { } // OK: separate scopes
int i = 10; // OK: the loop variables are out of scope
// for (int i = 0; ...) { } // ERROR: i already exists in this scope
}
Local variables captured by a lambda or an anonymous class must be effectively final, meaning assigned exactly once.
Java is always pass-by-value
flowchart LR
subgraph main
d[data: ref]
end
subgraph reassign
p[arr: copy of ref]
end
H1[(array 20, 10)]
H2[(new array 0, 0)]
d --> H1
p -. before assignment .-> H1
p --> H2
Exercises
Each prompt is a short paraphrase. All solutions were run on JDK 21.
Loops and methods
1. Read numbers until the user enters 0, then print the sum.
2. Addition quiz: generate two random numbers and keep asking for their sum until the user gets it right.
Solutions to exercises 1–2
Scanner in = new Scanner(System.in);
long sum = 0;
int n;
do {
n = Integer.parseInt(in.nextLine().trim());
sum += n;
} while (n != 0);
System.out.println("Sum = " + sum);
do-while fits exercise 1 because you always read at least one number, and adding the final 0 doesn’t change the sum.
var random = java.util.concurrent.ThreadLocalRandom.current();
int a = random.nextInt(1, 100), b = random.nextInt(1, 100);
Scanner in = new Scanner(System.in);
int attempts = 0;
while (true) {
System.out.printf("%d + %d = ? ", a, b);
attempts++;
if (Integer.parseInt(in.nextLine().trim()) == a + b) break;
System.out.println("Wrong, try again.");
}
System.out.println("Correct after " + attempts + " attempt(s).");
3. Print the full 9×9 multiplication grid: a title line, a header row with 1 … 9, a horizontal rule, then nine rows of the form i | followed by i×1 … i×9. The innermost print runs 9 × 9 = 81 times: O(n²).
The slide’s follow-up question: with for (int i = 0; i < 10; i++) around for (int j = 0; j < i; j++), how many times does the inner print run? The inner loop runs 0, 1, …, 9 times, so 0 + 1 + … + 9 = 45, exactly the number of cells in the triangular table from the nested-loops section.
Solution to exercise 3: the 9×9 grid and what a senior would improve
static void printTable(int n) {
System.out.println("Multiplication Table");
System.out.print(" "); // leave room for the "i | " label column
for (int j = 1; j <= n; j++) System.out.printf("%4d", j);
System.out.println();
System.out.println("-".repeat(4 + 4 * n));
for (int i = 1; i <= n; i++) {
System.out.printf("%d | ", i);
for (int j = 1; j <= n; j++) System.out.printf("%4d", i * j);
System.out.println();
}
}
// printTable(9);
Multiplication Table
1 2 3 4 5 6 7 8 9
----------------------------------------
1 | 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
7 | 7 14 21 28 35 42 49 56 63
8 | 8 16 24 32 40 48 56 64 72
9 | 9 18 27 36 45 54 63 72 81
%4d right-aligns each number in four characters, so the columns line up whether a number has one digit or two. The header row starts with four spaces, exactly the width of the "i | " label, so 1 … 9 sit right above their columns.
What a senior would improve:
- Derive the column width from the largest value (
String.valueOf(n * n).length() + 1) and the label width too, because for n ≥ 10 the label"10 | "is longer and the columns drift. - Move the table building into a method that returns a
String(viaStringBuilder) so it can be unit-tested, keeping the console printing outside.
4. Greatest common divisor of two numbers (16 and 24 give 8). Euclid’s algorithm: gcd(a, b) = gcd(b, a mod b), stopping when b = 0. That is O(log min(a, b)); trying every candidate from min(a, b) downwards is O(n), far slower for 9-digit numbers.
5. Palindromes (strings that read the same both ways): noon and et4554te are true, ronin is false. Use two pointers (one index from the start, one from the end, moving inwards): O(n) time, O(1) extra memory.
6. Print the first 50 primes. The slide’s example starts with “1, 2, 3, 5…”, but 1 is not prime. A prime is greater than 1 and has exactly two divisors, 1 and itself. If you need every prime below a large N, use the sieve of Eratosthenes, O(N log log N).
7. Convert hexadecimal to decimal. Walk from left to right, computing result = result * 16 + digit at each step (Horner’s method). At work, use the built-in Integer.parseInt("1A", 16); write it yourself to understand the algorithm.
Solutions to exercises 4–7: gcd, palindrome, primes, hex
static long gcd(long a, long b) {
a = Math.abs(a); b = Math.abs(b);
while (b != 0) {
long t = a % b;
a = b;
b = t;
}
return a;
}
static boolean isPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) return false;
}
return true;
}
new StringBuilder(s).reverse().toString().equals(s) is shorter but uses O(n) extra memory.
static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
for (int d = 3; (long) d * d <= n; d += 2) { // widen to long so d*d can't overflow
if (n % d == 0) return false;
}
return true;
}
static int[] firstPrimes(int count) {
int[] primes = new int[count];
int found = 0;
for (int n = 2; found < count; n++) {
if (isPrime(n)) primes[found++] = n;
}
return primes; // 2, 3, 5, 7, 11, ..., 229
}
static int hexToDecimal(String hex) {
int result = 0;
for (char c : hex.toUpperCase().toCharArray()) {
int digit;
if (c >= '0' && c <= '9') digit = c - '0';
else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10;
else throw new IllegalArgumentException("Invalid hex digit: " + c);
result = result * 16 + digit;
}
return result; // "1A" -> 26, "FF" -> 255
}
8. GCD and LCM for several pairs (each number has at most 9 digits; the first line gives the number of test cases). Sample: input 2 / 12 34 / 1234 5678 gives output 2 204 / 2 3503326.
9. Count the even divisors of N (N ≤ 10⁹, up to 100 test cases). Checking every number from 1 to N is 10⁹ × 100 operations, far too slow. The insight: an odd N has no even divisors. For an even N, every even divisor has the form 2k where k divides N/2, so you only count the divisors of N/2, in O(√N). Sample: N = 9 gives 0 (9 is odd) and N = 8 gives 3 (the even divisors 2, 4 and 8).
Solutions to exercises 8–9: fast multi-test input and counting even divisors
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
StringBuilder out = new StringBuilder();
while (t-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
long a = Long.parseLong(st.nextToken()), b = Long.parseLong(st.nextToken());
out.append(gcd(a, b)).append(' ').append(lcm(a, b)).append('\n');
}
System.out.print(out); // buffer the output and print once; much faster than println per line
}
static int countEvenDivisors(int n) {
if (n % 2 != 0) return 0;
int m = n / 2, count = 0;
for (int d = 1; (long) d * d <= m; d++) {
if (m % d == 0) count += (d == m / d) ? 1 : 2;
}
return count;
}
I cross-checked countEvenDivisors against brute force for every n < 500.
Loop exercises from the Hỏi Dân IT material
Five short ones: sum 1 to 100 with for, print the even numbers from 2 to 20 with while, ask for a password with do-while until it’s right, find the first multiple of 7 in 1..100 with break, and print the even numbers from 1 to 10 with continue.
- Correction to the original material: the
if (i == 5) break;loop is annotated with the output1 2 4 5. The correct output is1 2 3 4, becausebreakstops before 5 is printed.1 2 4 5belongs to thecontinueexample that skips 3. - A real system never compares plaintext passwords: store a hash (bcrypt, Argon2) and let the library verify it.
Solutions to the five short loop exercises
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i; // 5050, which is also 100 * 101 / 2
int even = 2;
while (even <= 20) { System.out.print(even + " "); even += 2; }
Scanner in = new Scanner(System.in);
String input;
do {
System.out.print("Password: ");
input = in.nextLine();
} while (!"secret".equals(input)); // compare content with equals, not ==
System.out.println("Logged in!");
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) { System.out.println(i); break; } // 7
}
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) continue; // skip odd numbers
System.out.print(i + " "); // 2 4 6 8 10
}
Lab 02: a score manager
The task, paraphrased:
- Let the user keep entering scores from 0 to 10 in a
do-whileloop; reject out-of-range values withcontinue; stop on-1. Keep a running total and count. - Then show a menu driven by
switch: 1 prints the average rounded to 2 decimals; 2 prints the grade (from 9: Excellent, from 8: Very good, from 6.5: Good, from 5: Average, below 5: Weak); 3 exits withreturn.
Three things to notice:
continueinsidedo-whilejumps to the conditionwhile (score != STOP), not back to the top of the body. When the user types-1, the condition is false, so the loop ends without adding-1to the total.- Edge case: if the user types
-1straight away,count == 0; dividing adoubleby zero givesNaN, so check first. The menu sits in a loop so you can pick several options. - What a senior would improve: pull
classifyand the average calculation out so they can be unit-tested (including the boundaries 5, 6.5, 8 and 9), use anenumfor grades instead of strings, and avoidreturndeep insidemainas the program grows: keepmainas a coordinator and put the logic in methods that return values.
Solution to Lab 02 and a sample run
import java.util.Scanner;
public class Lab02 {
static final double STOP = -1;
static String classify(double average) {
if (average >= 9) return "Excellent";
else if (average >= 8) return "Very good";
else if (average >= 6.5) return "Good";
else if (average >= 5) return "Average";
else return "Weak";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double sum = 0;
int count = 0;
double score;
// Feature 1: read scores until -1
do {
System.out.print("Enter a score (0-10, -1 to stop): ");
String raw = in.nextLine().trim();
try {
score = Double.parseDouble(raw);
} catch (NumberFormatException e) {
score = Double.NaN; // letters, empty input... treated as invalid
}
if (score == STOP) continue; // continue jumps to the while condition, which is false, so we stop
if (!(score >= 0 && score <= 10)) { // written this way so NaN also lands here
System.out.println("Invalid score. Try again.");
continue;
}
sum += score;
count++;
} while (score != STOP);
// Feature 2: the menu
while (true) {
System.out.println("===== MENU =====");
System.out.println("1. Average score");
System.out.println("2. Grade");
System.out.println("3. Exit");
System.out.print("Choice: ");
switch (in.nextLine().trim()) {
case "1" -> {
if (count == 0) System.out.println("No scores yet.");
else System.out.printf("Average: %.2f%n", sum / count);
}
case "2" -> {
if (count == 0) System.out.println("No scores yet.");
else System.out.println("Grade: " + classify(sum / count));
}
case "3" -> {
System.out.println("Bye!");
return; // leaves main, which ends the program
}
default -> System.out.println("Unknown option.");
}
}
}
}
Running it with 9, 5, -3, 11, abc, 8.5, -1 and then choosing 1, 2, 7, 3: the values -3, 11 and abc are rejected, the average is 7.50, the grade is Good, option 7 is reported as unknown, and 3 exits.
Remember
- Explain how
while,do-whileandfordiffer and when to use each. - Know where
forandwhilejump aftercontinue, and why awhileloop can then run forever. - Draw the call stack when
maincallstotalcallstax, and say when you hitStackOverflowError. - Prove Java is only pass-by-value using
swapFirstTwoandreassign. - Know why the LCM must be written
a / gcd * b, nota * b / gcd.
Interview questions
Junior
How do while, do-while and for differ?
while checks first, so it may run zero times; do-while runs first, so it always runs at least once; for packs initialization, condition and update into one line.
for suits a known number of iterations. For-each walks arrays or Iterables when you don’t need the index.
What is the difference between break and continue? What happens after continue in a for loop?
break leaves the nearest loop (or a labeled one); continue only skips the rest of the current iteration.
In a for loop, the update (i++) runs next and then the condition is checked. In while/do-while, control jumps straight to the condition.
How do return, break and System.exit differ?
break leaves a loop, return leaves a method, System.exit stops the whole JVM.
breakonly leaves the innermost loop (orswitch); code after the loop still runs.returnends the current method and hands control back to the caller.returninmainends the main thread; the program stops if no non-daemon threads remain.System.exit(code)halts the JVM with an exit code for the OS, skipping any pendingfinallyblocks. Server applications and libraries should almost never call it.
What is the difference between a parameter and an argument?
A parameter is the variable declared in the method header; an argument is the concrete value passed at the call.
num1 and num2 in int max(int num1, int num2) are parameters (formal parameters); x and y in max(x, y) are arguments (actual parameters). On the call, each argument’s value is copied into its parameter, which then lives as a local variable in the method’s stack frame.
Mid
Is Java pass-by-value or pass-by-reference?
Always pass-by-value; for objects, the value being copied is the reference.
So a method can change the contents of the object the caller points to, but reassigning the parameter to another object has no effect on the caller’s variable.
How do the stack and the heap differ? When do you get StackOverflowError versus OutOfMemoryError?
Each thread has its own stack of call frames; the heap is shared, holds objects, and is cleaned up by the GC.
- A stack frame holds locals and parameters and is freed as soon as its method returns.
StackOverflowError: recursion that is too deep or has no base case.OutOfMemoryError: Java heap space: reachable objects exceed-Xmx, typically because of a leak (an unbounded cache, listeners that are never removed).
What does effectively final mean, and why can lambdas only use effectively final locals?
An effectively final local isn’t declared final but is assigned exactly once. Lambdas only copy a local’s value, so the compiler forbids reassignment to keep the copy and the original from drifting apart.
The local lives in a stack frame that may be gone by the time the lambda runs (on another thread, say), so lambdas and anonymous classes must copy the value in. If reassignment were allowed, the copy and the original would diverge and cause confusing bugs. Fields aren’t restricted this way, because the lambda captures this rather than copying the field.
Senior
Recursion versus loops: when should you rewrite recursion as iteration in Java?
When the recursion depth grows with the input size, because Java has no tail-call optimization and every call costs a frame.
Walking a long linked list or a degenerate tree can overflow the stack. Rewrite it as a loop with an explicit stack or queue (ArrayDeque). Recursion is fine when the depth is O(log n), as with balanced trees or divide and conquer.
Useful phrases for interviews
- “The loop is bounded by the input size, so this runs in linear time.”
- “Two nested loops over the same input give me quadratic complexity, so I’d swap the inner loop for a hash lookup.”
- “Java is strictly pass-by-value; for objects, it’s the reference that gets copied.”
- “That method mutates its argument, which is a hidden side effect; I’d rather return a new list.”
- “This recursion depth is proportional to the input, so I’d convert it to an iterative version with an explicit stack.”
- “The loop stops on a sentinel value,
-1, which is never added to the total.” - “
continuein ado-whilejumps straight to the condition, not back to the top of the body.” - “I validate input with an early return so the happy path stays flat.”
- “The method declares two parameters, and the caller passes two arguments; their values are copied in.”
- “The method header gives the modifiers, return type, name and parameter list; the body holds the logic.”
Most of the diagrams in the slides come from Introduction to Java Programming and Data Structures by Y. Daniel Liang (11th edition), a good book if you want to read further.
Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.