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 writes and runs your first Java program, sorts errors into three kinds, and works through exercises that use only print statements and expressions. Afterwards you can compile with javac, run with java, and spot the three classic traps: integer division, overflow and floating-point error. Read the JVM and JDK post first; next up is variables and data types.
At a glance:
flowchart LR
SRC["Greeting.java"] -->|javac| BC["Greeting.class"]
BC -->|"java Greeting"| JVM[JVM runs main]
SRC -.->|javac catches| E1[Compile error]
JVM -.->|exception| E2[Runtime error]
JVM -.->|"silent, wrong result"| E3[Logic error]
E3 --> X["7 / 2 == 3, int overflow"]
1. Hello World and the minimum syntax
Key idea: the smallest Java program is one class with a main method. You compile it to bytecode with javac and run it with java.
public class Greeting {
public static void main(String[] args) {
// Print a line, then a newline
System.out.println("Hello, backend!");
/* print does not add a newline */
System.out.print("Two plus three = ");
System.out.println(2 + 3);
}
}
public class Greeting: a file can contain at most onepublictop-level class, and the file name must match it (Greeting.java).public static void main(String[] args): the program’s entry point. It has to bestaticbecause the JVM calls it before any object exists.printprints without a line break,printlnadds one. String literals go in"..."and every statement ends with;.- Comments:
//for one line,/* ... */for several lines,/** ... */for Javadoc. - Arithmetic operators:
+ - * / %. The first trap: dividing two integers drops the fraction:7 / 2 == 3. If either operand is floating-point, the result is too:7.0 / 2 == 3.5.
Compile and run from the command line at least once to see what the IDE does for you. Bytecode is the intermediate code the JVM (Java virtual machine) understands, not the CPU’s machine code.
mkdir -p ~/code/java-core && cd ~/code/java-core # keep paths free of spaces and accents to avoid trouble
javac Greeting.java # produces Greeting.class (bytecode)
java Greeting # run it: pass the CLASS NAME, without .class
java Greeting.java # Java 11+: compile in memory and run, no .class file written
javap -c Greeting # show the bytecode javac produced
Three kinds of errors
Key idea: the later an error shows up, the more it costs; a logic error never reports itself, so only tests catch it.
| Kind | When it shows up | Example |
|---|---|---|
| Syntax (compile) error | When javac compiles |
A missing ;, a misspelled variable name |
| Runtime error (exception) | While the program runs | 1 / 0 throws ArithmeticException, dereferencing null throws NullPointerException |
| Logic error | Never reported; the output is simply wrong | Using integer / to compute an average |
An exception is an error object the program “throws” when it hits a situation it can’t handle at run time. The cure for logic errors is unit tests that cover edge cases.
Exercises
Each prompt is a short paraphrase. All solutions were run on JDK 21.
Group 1: print statements and expressions only (Intro session)
These exercises forbid variables and loops; you only print the results of expressions.
1.1. Print three welcome lines (about Java, computer science and programming): three System.out.println calls.
1.2. Print the word JAVA in large letters over 4 lines, with each letter drawn using that letter itself (J, A, V, A side by side). Print statements only.
1.3. Print a table of a, a^2 and a^3 for a = 1, 2, 3, 4.
Solutions 1.2–1.3: large JAVA letters, text blocks and printf
System.out.println(" J A V V A");
System.out.println(" J A A V V A A");
System.out.println("J J AAAAA V V AAAAA");
System.out.println(" J J A A V A A");
Output:
J A V V A
J A A V V A A
J J AAAAA V V AAAAA
J J A A V A A
The logic of 1.2 is trivial; the hard part is lining up the columns. Sketch the shape on squared paper (or in an editor with a monospaced font), count the spaces before each character, and only then type the code. Each “A” grows one column wider per row and the “V” shrinks, so you only need to check where the two edges land.
A senior would reach for a text block (Java 15+, a multi-line string in """): the drawing in the source looks exactly like the output, with no escaping. Java strips the common indentation, measured from the least-indented line (including the line with the closing """):
System.out.print("""
J A V V A
J A A V V A A
J J AAAAA V V AAAAA
J J A A V A A
""");
Exercise 1.3:
System.out.printf("%-6s%-6s%-6s%n", "a", "a^2", "a^3");
System.out.printf("%-6d%-6d%-6d%n", 1, 1 * 1, 1 * 1 * 1);
System.out.printf("%-6d%-6d%-6d%n", 2, 2 * 2, 2 * 2 * 2);
System.out.printf("%-6d%-6d%-6d%n", 3, 3 * 3, 3 * 3 * 3);
System.out.printf("%-6d%-6d%-6d%n", 4, 4 * 4, 4 * 4 * 4);
a a^2 a^3
1 1 1
2 4 8
3 9 27
4 16 64
%-6d means left-aligned in a 6-character column; let printf line up the columns instead of counting spaces by hand. Variables and loops are banned here, hence the four repeated lines; in real code you’d write for (int a = 1; a <= 4; a++) around a single printf. Don’t use Math.pow(a, 2) for integers: it returns a double (printing 4.0) and is slower than a multiplication.
1.4–1.5. Perimeter and area of a circle (r = 5.5 cm) and a rectangle (4.5 × 7.9 cm).
1.6. Print the results of four expressions: (a) (9.5 × 4.5 − 2.5 × 3) / (45.5 − 3.5), (b) 1 + 2 + … + 9, (c) 1 + 2 + … + 1,000,000, (d) 4 × (1 − 1/3 + 1/5 − 1/7 + 1/9 − 1/11 + 1/13).
These two exercises hit all three number traps: 4.5 * 7.9 prints 35.550000000000004, (d) typed with integers prints 4, and (c) computed in int goes negative.
Solutions 1.4–1.6: Math.PI, the Leibniz series and Gauss’s formula
System.out.println("Circle perimeter: " + 2 * Math.PI * 5.5); // 34.557...
System.out.println("Circle area: " + Math.PI * 5.5 * 5.5); // 95.033...
System.out.println("Rectangle perimeter: " + 2 * (4.5 + 7.9)); // 24.8
System.out.printf("Rectangle area: %.2f%n", 4.5 * 7.9); // 35.55
Use Math.PI rather than 3.14. Printing 4.5 * 7.9 directly gives 35.550000000000004, because binary floating point can’t represent 0.1 exactly. Format the output with %.2f.
System.out.println((9.5 * 4.5 - 2.5 * 3) / (45.5 - 3.5)); // (a) 0.8392857142857143
System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9); // (b) 45
System.out.println(4 * (1.0 - 1.0 / 3 + 1.0 / 5 - 1.0 / 7
+ 1.0 / 9 - 1.0 / 11 + 1.0 / 13)); // (d) 3.2837384837384844
(a) and (b) are just about precedence: multiplication binds tighter than subtraction, and the denominator needs its own parentheses. Expression (d) is the first seven terms of the Leibniz series, π/4 = 1 − 1/3 + 1/5 − 1/7 + ….
The result, 3.28, is still far from 3.14159 because the series converges very slowly: adding the −1/15 term gives 3.017, and you need millions of terms for six correct digits. The exercise shows how a computer can approximate π by summing terms; real code just uses Math.PI.
For (c), loops are banned, so use Gauss’s formula n(n+1)/2:
System.out.println(1_000_000L * (1_000_000L + 1) / 2); // 500000500000
System.out.println(1_000_000 * (1_000_000 + 1) / 2); // -363189984: int overflow!
This is a lesson in overflow (a result too big for its type): multiplying two ints gives an int, and the result wraps around silently. Make one operand a long and the whole calculation is done in long.
1.7. A runner covers 14 km in 45 minutes 30 seconds. Print the average speed in miles per hour (1 mile = 1.6 km).
1.8. A runner covers 24 miles in 1 hour 40 minutes 35 seconds. Print the average speed in km/h.
1.9. Population forecast for the next five years. Assume one birth every 7 seconds, one death every 13 seconds, one new immigrant every 45 seconds, a current population of 312,032,486, and 365 days per year.
Solutions 1.7–1.9: speed conversions and the population forecast
System.out.println((14 / 1.6) / ((45 * 60 + 30) / 3600.0)); // 1.7: ≈ 11.54 mph
System.out.println((24 * 1.6) / ((1 * 3600 + 40 * 60 + 35) / 3600.0)); // 1.8: ≈ 22.91 km/h
Note the 3600.0: with 3600, dividing seconds by it would be integer division and give 0 or 1.
// seconds per year = 365 * 24 * 60 * 60 = 31_536_000
System.out.println(312_032_486L + 31_536_000L * 1 / 7 - 31_536_000L * 1 / 13 + 31_536_000L * 1 / 45);
System.out.println(312_032_486L + 31_536_000L * 2 / 7 - 31_536_000L * 2 / 13 + 31_536_000L * 2 / 45);
// ... and the same for years 3, 4, 5. Year 1 gives 314812582, year 5 gives 325932970
Compute each year from the total number of seconds. Taking one year’s growth and multiplying it by five lets the integer-division error accumulate.
1.10. Solve a 2×2 linear system with Cramer’s rule. For ax + by = e, cx + dy = f with ad − bc ≠ 0: x = (ed − bf)/(ad − bc) and y = (af − ec)/(ad − bc). The system to solve:
3.4x + 50.2y = 44.5
2.1x + 0.55y = 5.9
Solution 1.10: plugging in, checking back and what a senior adds
So a = 3.4, b = 50.2, c = 2.1, d = 0.55, e = 44.5 and f = 5.9. The determinant ad − bc = 1.87 − 105.42 = −103.55 is non-zero, so there is exactly one solution. Plug the numbers in:
System.out.println("x = " + (44.5 * 0.55 - 50.2 * 5.9) / (3.4 * 0.55 - 50.2 * 2.1)); // 2.623901496861419
System.out.println("y = " + (3.4 * 5.9 - 44.5 * 2.1) / (3.4 * 0.55 - 50.2 * 2.1)); // 0.7087397392563978
Check by substituting back: 3.4 · 2.6239 + 50.2 · 0.7087 ≈ 44.5 and 2.1 · 2.6239 + 0.55 · 0.7087 ≈ 5.9. The exercise prints the coefficient as .55; Java accepts the literal .55 too, but 0.55 is easier to read.
To make sure the formula is typed correctly, try it first on a system with integer roots, such as 2x + 3y = 8, 5x − y = 3 (x = 1, y = 2):
System.out.println("x = " + (8.0 * -1 - 3 * 3) / (2 * -1 - 3 * 5)); // 1.0
System.out.println("y = " + (2.0 * 3 - 5 * 8) / (2 * -1 - 3 * 5)); // 2.0
What a senior would add:
- Print with
printf("%.4f")instead of sixteen decimals. - Test the determinant against a tolerance (
Math.abs(det) < 1e-9) rather than== 0, because withdoublea determinant that is mathematically zero often comes out as something like1e-17. - For larger systems use Gaussian elimination or a library (Apache Commons Math), since Cramer’s rule needs n + 1 determinants, which gets expensive fast.
Remember
- Explain why
mainhas to bepublic static void main(String[] args). - Know what
javacandjavaeach take, and whyjava Greeting.classfails. - Tell the three kinds of errors apart and say why logic errors are the most dangerous.
- Predict
7 / 2,1.0 / 0and1_000_000 * 1_000_001, and know how to fix each. - Know why you don’t compare two
doubles with==.
Interview questions
Junior
Why does main have to be public static void main(String[] args)?
The JVM calls main before any object exists, so it must be static, and it must be public so the JVM can call it from outside the class.
It returns void because a program reports its exit code through System.exit(code), not a return value. args holds the command-line arguments. Since Java 25, small programs may write void main() (no static, no parameters) and the JVM creates an instance and calls it, but production code still uses the full form.
What is the difference between compile errors, runtime errors and logic errors? Which is the most dangerous?
They differ in when they surface: at compile time, at run time, or never. Logic errors are the most dangerous because nothing reports them.
Compile errors are caught by javac (a missing ;, a type mismatch), so the program can’t run yet. Runtime errors happen while the program runs, as exceptions (ArithmeticException on integer division by zero, NullPointerException). Logic errors let the program run and produce wrong results. The defence is unit tests that cover edge cases, plus code review.
Why is 7 / 2 equal to 3 in Java? How do you get 3.5?
Both operands are int, so it’s integer division; make one side floating-point: 7.0 / 2 or (double) a / b.
The fraction is truncated toward zero, so -7 / 2 == -3. 7 / 2.0 works too. Writing (double) (a / b) is wrong, because the integer division has already happened before the cast.
What’s the difference between javac and java? Why does java Greeting.class fail?
javac compiles .java into .class bytecode; java starts the JVM and runs a class by name, so it doesn’t accept a .class path.
java is the launcher: it runs the class that has main. It takes a class name (or, since Java 11, a single .java file), so java Greeting.class is read as a class named class in a package named Greeting, which doesn’t exist.
Mid
Why does 1_000_000 * (1_000_000 + 1) / 2 come out negative? How do you fix it?
The multiplication runs in 32-bit int, overflows and wraps to a negative number; make one operand a long (1_000_000L).
The result (about 10¹²) exceeds Integer.MAX_VALUE and wraps around without any exception. With one long operand the whole expression is computed in long. If you’d rather fail loudly than be silently wrong, use Math.multiplyExact, which throws ArithmeticException on overflow.
Why shouldn’t you compare two doubles with ==?
Binary floating point can’t represent most decimal fractions exactly, so compare within a tolerance: Math.abs(a - b) < 1e-9.
0.1 + 0.2 == 0.3 is false and 4.5 * 7.9 prints 35.550000000000004. The same formula can differ in the last digit depending on evaluation order. Use a relative tolerance for large values. For money, use BigDecimal or integers in the smallest currency unit, never double.
Senior
When would you run java Hello.java directly, and why not for a production service?
For small scripts and quick experiments; production needs a build step, dependency management and a versioned artifact.
Source-file mode (Java 11+) compiles in memory and runs immediately, which is great for small scripts, quickly trying an API, or a file with a #!/usr/bin/java --source 21 shebang. Not for production: it recompiles on every start, skips the build step where tests and checks run, has no dependency management (Maven/Gradle), and produces no versioned JAR or image. A real service needs reproducible builds, a fixed artifact and startup optimizations (CDS, jlink).
Useful phrases for interviews
- “javac compiles source into bytecode; the JVM never sees the
.javafile.” - “A logic error is the worst kind because nothing fails; that’s what our edge-case tests are for.”
- “Both operands are
int, so this is integer division and the fraction is truncated.” - “The product overflowed
intand wrapped around; promoting one operand tolongfixes it.” - “
mainis the entry point; the JVM calls it before any object exists.” - “I never compare doubles with
==; I compare them within a tolerance.” - “A compile error stops the build, a runtime exception stops the request, and a logic error stops nothing, which is the scary part.”
- “For a quick experiment I run the source file directly; for anything real I build a JAR.”
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.