Syntax, types & control flow
Write and run small Java programs comfortably.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
Java is a statically typed language: every variable has a type that the compiler checks before the program runs. Source files are compiled to bytecode, which the JVM runs on any operating system.
Think of it like this: Bytecode is like sheet music: any JVM can play it, whatever the instrument.
Explained simply
To write Java you install a JDK (Java Development Kit). It contains javac, the compiler, and java, the program that starts the JVM. You write code in a .java file, the compiler checks it, and the JVM runs it. Use a long-term support (LTS) version such as Java 21 or Java 25, because they get updates for years.
Java is strict about types. When you write int age = 30, the variable age can only ever hold whole numbers. If you try to put text in it, the compiler stops you before the program even runs. This feels slow at first, but it catches many bugs early.
A Java program is made of classes, and classes contain methods. A method is a named block of code, like a small machine: values go in, a result may come out. The JVM starts your program by calling a special method named main.
Inside methods you make decisions with if and switch, and you repeat work with for and while loops. Arrays hold a fixed number of values of one type. With just these tools you can already solve many small puzzles, and that practice is the fastest way to get comfortable.
Press Play on a diagram to walk through it one step at a time.
- 1Write Main.java
Plain text source with a class and a main method
- 2javac compiles
Checks types and syntax, reports errors early
- 3Main.class bytecode
Platform-independent instructions for the JVM
- 4JVM loads class
Class loader reads and verifies the bytecode
- 5main() runs
JIT compiler turns hot code into fast machine code
- Primitives (8)
- int, long, short, byte
- double, float
- boolean
- char
- References
- String
- Arrays like int[]
- Classes and interfaces
- Can be null
- 1Init
int i = 0 runs once, before anything else
- 2Check condition
If i < n is false, the loop ends
- 3Run body
The statements inside the braces
- 4Update
i++ runs, then back to the check
- Back to step 1
- Falls through without break
- Does not return a value
- Easy to forget a break
- Still valid in all Java versions
- Never falls through
- Returns a value directly
- Several labels: case 1, 2 ->
- Use yield inside a block
In depth
Installing a JDK and three ways to run code
Any OpenJDK build works the same way. Popular free builds are Eclipse Temurin, Amazon Corretto and Oracle OpenJDK. On Linux and macOS, SDKMAN (sdk install java) makes switching versions easy. Check your setup with java -version and javac -version, and set JAVA_HOME so build tools find the right JDK.
There are three common ways to run code. The classic way compiles with javac Main.java and runs with java Main. Since Java 11 you can skip the separate step: java Main.java compiles in memory and runs at once, which is perfect for exercises. For one-line experiments, jshell gives you an interactive prompt where each line runs immediately.
- java -version prints the runtime version
- javac -d out Main.java puts .class files in out/
- java -cp out Main runs a compiled class
- jshell then /exit to leave
- Two steps: compile, then run
- Leaves .class files on disk
- How build tools work
- Needed for multi-file projects
- One step, compiles in memory
- Java 11 and later
- Great for single-file exercises
- No .class files left behind
- Interactive prompt
- No class or main needed
- Instant feedback per line
- Best for trying an API
Primitive numbers: sizes, overflow and decimals
Each primitive has a fixed size. An int is 32 bits and holds about plus or minus 2.1 billion. A long is 64 bits; write long literals with an L, like 3_000_000_000L. When an int goes past its maximum, it does not crash. It silently wraps around: Integer.MAX_VALUE + 1 equals Integer.MIN_VALUE. Use Math.addExact or Math.multiplyExact when you want an ArithmeticException instead.
Decimals use double, which stores numbers in binary. Many decimal values, like 0.1, cannot be stored exactly, so 0.1 + 0.2 prints 0.30000000000000004. That is fine for physics, but not for money. For money, use long cents or BigDecimal.
- byte 8 bits, short 16, int 32, long 64
- float 32 bits, double 64 bits
- char is a 16-bit UTF-16 code unit
- Underscores in literals are allowed: 1_000_000
Strings are immutable objects
A String is an object, not a primitive, and it can never change after it is created. Methods like toUpperCase() or replace() return a new String and leave the old one untouched. So s.trim() on its own line does nothing useful; you must write s = s.trim().
Because every change makes a new object, building a long string with += inside a loop creates lots of garbage. Use StringBuilder for that: append in the loop, then call toString() once. String literals with the same text share one object in the string pool, which is why == sometimes seems to work on strings and then fails on text read from a user or a file. Always compare text with equals(), or equalsIgnoreCase() when case should not matter.
- Text blocks (Java 15) use triple quotes for multi-line strings
- String.format("%.2f", x) prints two decimals
- s.isBlank() is true for empty or whitespace-only text
- String.valueOf(42) and Integer.parseInt("42") convert both ways
Methods, arrays and pass-by-value
Java always passes arguments by value. For a primitive, the method gets a copy of the number, so changing it inside the method does not affect the caller. For an object or array, the method gets a copy of the reference. Both references point to the same array, so writing arr[0] = 99 inside the method is visible to the caller. But assigning a brand new array to the parameter only changes the local copy.
Arrays have a fixed length, read from the length field (no brackets). New arrays are filled with default values: 0 for numbers, false for boolean, and null for objects. Arrays.toString(arr) prints the contents, Arrays.sort(arr) sorts in place, and Arrays.copyOf makes a bigger copy when you need to grow.
- int[] a = new int[5] creates five zeros
- a.length, but s.length() for a String
- Overloading: same method name, different parameter types
Control flow details that trip people up
Conditions must be boolean. Java has no truthy values, so if (count) does not compile; write if (count > 0). The operators && and || short-circuit: in if (s != null && s.length() > 3), the length check only runs when s is not null.
The classic switch with colons falls through to the next case unless you write break. The arrow form (case 1 ->) never falls through and can return a value as a switch expression. When a branch needs several statements, use a block and give back the value with yield. Loops come in four shapes: classic for, the enhanced for-each, while, and do-while, which always runs its body at least once. break leaves a loop and continue skips to the next round.
Learn it in 5 short steps
About 1h 10m each. Track them with a timer in your plan.
- 1Install a JDK and run a program~1h 10m
- 2Learn primitives, strings and operators~1h 10m
- 3Write if, switch and loops~1h 10m
- 4Use arrays and methods~1h 10m
- 5Solve 10 small console exercises~1h 10m
Key points
- Java has 8 primitive types; everything else is a reference to an object.
- Compare strings with equals(), because == compares references, not text.
- Integer division drops the remainder: 7 / 2 is 3, not 3.5.
- Switch with arrow labels (case X ->) never falls through to the next case.
Key terms
Tap a card to flip it. 0/5 known
Examples
public class Main {
public static void main(String[] args) {
int[] nums = {3, 8, 1, 5};
int max = nums[0];
for (int n : nums) {
if (n > max) max = n;
}
String size = switch (nums.length) {
case 0 -> "empty";
case 1, 2, 3 -> "small";
default -> "large";
};
System.out.println("Max: " + max + ", size: " + size);
}
}Run it with: java Main.java (single-file launch, Java 11+).
A small console program with a method and a loop
Goal: print a Celsius to Fahrenheit table from 0 to 100 in steps of 20. Step 1: put the formula in its own method so it can be tested and reused. Step 2: loop with a step of 20 instead of 1. Step 3: format the output with printf so the columns line up. Note the 9.0: with 9 / 5 in int maths you would get 1, not 1.8. Run it with java Table.java.
public class Table {
static double toFahrenheit(double c) {
return c * 9.0 / 5 + 32;
}
public static void main(String[] args) {
for (int c = 0; c <= 100; c += 20) {
System.out.printf("%3d C = %5.1f F%n", c, toFahrenheit(c));
}
}
}
// Output starts: 0 C = 32.0 FAdding up prices without rounding errors
A shop adds ten items costing 0.10 each and expects 1.00, but a double total prints 0.9999999999999999. Step 1: notice the cause: 0.1 has no exact binary form. Step 2: switch to BigDecimal and create it from a String, not from a double, so the value is exact. Step 3: use add() because BigDecimal is immutable, just like String. Many teams instead store whole cents in a long, which is fast and also exact.
import java.math.BigDecimal;
public class Prices {
public static void main(String[] args) {
double d = 0;
for (int i = 0; i < 10; i++) d += 0.10;
System.out.println(d); // 0.9999999999999999
BigDecimal total = BigDecimal.ZERO;
BigDecimal price = new BigDecimal("0.10");
for (int i = 0; i < 10; i++) total = total.add(price);
System.out.println(total); // 1.00
}
}Quick reference
- java Main.java runs a single source file directly (Java 11+)
- int holds about plus or minus 2.1 billion; use long for bigger whole numbers
- 7 / 2 is 3, 7 % 2 is 1, 7 / 2.0 is 3.5
- Compare text with equals(); == compares references
- Use StringBuilder to build strings inside loops
- Arrays.toString(arr) prints an array; arr.length gives its size
- Arrow switch never falls through; use yield to return from a block
- Use BigDecimal (from a String) or long cents for money, never double
Common mistakes
- Using == to compare String values instead of equals().
- Reading nums[nums.length], which throws ArrayIndexOutOfBoundsException.
- Expecting int division to keep decimals; cast to double first.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a program that prints the numbers 1 to 20, but prints Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
- Exercise 2medium
Write a method static int[] reversed(int[] a) that returns a new reversed array without changing the original, and print both arrays.
- Exercise 3hard
Write static boolean isPalindrome(String s) that ignores case and any character that is not a letter or digit, so "A man, a plan, a canal: Panama" returns true. Do it without creating a new String.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Which Java version should a beginner install in 2026?
- Install a current LTS release, Java 21 or Java 25. Both are supported by Spring Boot and all major tools, and everything in this path works on Java 21.
- What is the difference between the JDK and the JRE?
- The JDK is the full kit for developers: compiler, JVM and tools. The JRE was only the runtime; modern Java ships just the JDK, and apps often bundle a trimmed runtime made with jlink.
- Why does my program say "Could not find or load main class"?
- Usually the class name and file name do not match, you ran it from the wrong folder, or the classpath is wrong. Check that public class Main lives in Main.java and run java from the folder that contains the compiled classes.
- Should I use var for local variables?
- var (Java 10) lets the compiler infer the type, as in var list = new ArrayList<String>(). Use it when the type is obvious from the right side, and write the type when it helps the reader.