Java basics: Hello World, compiling, the three kinds of errors and the first exercises
Why an error found later costs more: compile errors, runtime errors and silent logic errors such as integer division and overflow; javac, java and Java 25 compact source files; how to read error messages and review AI-written fixes.
On this page
1. The problem
A learning progress page shows 0% for every learner for a week, including those who finished 37 of 40 lessons. Logs are clean, tests are green. The culprit is one line, done / total * 100, with two ints.
2. Key idea
Every error is stopped at one of three checkpoints; the farther from the keyboard, the more it costs and the harder it is to find.
| Kind | Who finds it | Points to the bug | Time to fix |
|---|---|---|---|
| Compile | compiler, IDE | yes: file, line, column | seconds |
| Runtime | the running program | yes: stack trace | minutes |
| Logic | tests, or users | no | sometimes days |
A logic error isn't Java's fault: the code does exactly what you wrote, not what you meant. Plain Python and JavaScript have no compile checkpoint.
2.1 How do you push errors to the left?
| Approach | Use when | Don't use when |
|---|---|---|
long instead of int |
money totals, accumulated counts, ids | huge arrays where memory is measured as tight |
Math.multiplyExact, addExact |
overflow is a bug (money, stock) | hashes that wrap on purpose |
One floating-point operand (done * 100.0 / total) |
ratios, displayed averages | money: use long or BigDecimal |
Compare double with a tolerance |
measurements, coordinates | money, comparison keys |
java Greeting.java |
quick tries, scripts, learning | production services: build a JAR with Maven or Gradle |
3. In Java
Compile, run, then read errors in a fixed order.
// Progress.java: javac Progress.java && java Progress
public class Progress {
static double percent(int done, int total) {
return done * 100.0 / total; // 37, 40 -> 92.5; done / total * 100 gives 0
}
public static void main(String[] args) {
System.out.println(percent(37, 40)); // 92.5
System.out.println(1_000_000L * 1_000_001); // 1000001000000
System.out.println(Math.multiplyExact(1_000_000, 1_000_001));
// Exception in thread "main" java.lang.ArithmeticException: integer overflow
// at java.base/java.lang.Math.multiplyExact(Math.java:...)
// at Progress.main(Progress.java:9)
}
}Reading a stack trace: the first line is the error type and reason; the at lines go from where it was thrown up to main. Skip JDK frames (java.base/...) and stop at the first frame with your class name. Python is the opposite: the failing line is last in the traceback.
Hello World, division by zero and common compile errors
- A
publicclass must live in a file with the same name, case included:public class Greetingingreeting.javareportsclass Greeting is public, should be declared in a file named Greeting.java. macOS and Windows often ignore case, so the error may only show up on Linux CI. 1 / 0throwsArithmeticException: / by zero;1.0 / 0givesInfinity,0.0 / 0givesNaN, with nothing thrown.4.5 * 7.9prints35.550000000000004: binary floating point can't represent every decimal exactly.1 + 2 + ... + 1_000_000inintturns negative because it exceedsInteger.MAX_VALUE(2,147,483,647).java Greeting.javacompiles in memory and runs immediately, producing no.classfile.
4. Working with AI
AI is very good at fixing compile errors, but often "fixes" runtime errors by hiding them, and doesn't notice logic errors on its own.
Hand to AI: explaining unfamiliar error messages, generating edge cases for tests (0, negatives, Integer.MAX_VALUE, empty lists).
Check in AI-written code:
- Every
/between two integers is intentional; ratios and averages have a floating-point operand. - Multiplying or accumulating money or quantities uses
longorMath.*Exact. - No
doublecompared with==; no money indouble. - No new
try/catchthat only swallows exceptions (return 0,return null). - Tests cover a zero denominator, empty lists, very large numbers.
5. Exercises
Exercise 1: Review a runtime-error fix
Last night's report stopped with ArithmeticException: / by zero at Progress.average(Progress.java:11). The AI proposes wrapping average in try { ... } catch (ArithmeticException e) { return 0; }, calling it "fully handled". Do you approve?
Solution to Exercise 1
No. The first frame in your code is line 11: sum / scores.length on an empty array. The fix turns a runtime error (with a stack trace) into a logic error (silent): a learner with no scores shows an average of 0, which looks like failing.
Root fix: make a business decision for the empty case (return an OptionalDouble, or show "no scores yet"), write a test with an empty array, and if you need a fraction use (double) sum / scores.length.
Exercise 2: Pick one of three fixes
percent(int done, int total) returns 0.0 for 37, 40. The AI offers three versions; pick one and reject the others with reasons.
return (double) (done / total) * 100; // A
return done * 100.0 / total; // B
return done / total * 100.0; // CSolution to Exercise 2
Pick B: done * 100.0 is floating point from the start, giving 92.5. A casts after integer division: (double) 0 * 100 is still 0.0; subtle, because the double makes it look fixed. C also divides integers first (37 / 40 == 0).
Test: assertEquals(92.5, percent(37, 40), 1e-9) fails for A and C. With total == 0, B returns NaN or Infinity instead of throwing; guard against it first.
Summary
javacproduces bytecode;javaruns by class name.- Three kinds of errors; logic errors are the most dangerous because nothing reports them.
- Reading a stack trace: the first line, then the first frame in your own code.
7 / 2 == 3; numbers that may overflow uselongorMath.multiplyExact.- Reject fixes that hide exceptions behind a
catchreturning a default.
Read more: Part 3: Variables and types.
Practice interview questions on this topic
- How does integer overflow work in Java, and does it throw an exception? How do you prevent it?
- What is the difference between JDK, JRE and JVM? How does a Java program go from source to main?
- What are the common Java operator traps: integer division, %, a++ vs ++a, && vs &, bitwise operators?
- Why is 0.1 + 0.2 != 0.3, and why not use double for money? How do you use BigDecimal correctly?
Comments
Community rules