Java Syntax Cheat Sheet: Core Rules With Short Examples
Quick answer
Java syntax cheat sheet: primitives, literals, loops, switch expressions, classes, records, text blocks and try-with-resources, checked against Oracle's docs.
Quick answer: Java syntax rests on a few rules. Every program lives inside a class. Variables have a declared type, and there are eight primitive types plus objects such as String. Control flow uses if, switch, for, while and do-while. Newer features worth knowing are switch expressions, records and text blocks. Below is each rule in a short example, checked against Oracle's documentation.
Last updated: 4 December 2026.
It is the night before a Java exam, a lab test or a first technical round. You do not need a fresh tutorial. You need one page that reminds you what the loop looks like, how a constructor is written, and what you forgot about long literals.
That is what this page tries to be. I am not a Java developer by trade and I will not claim hours of production experience. What I did was read Oracle's language tutorials and its Java 25 language guide, and wrote down the rules and the mistakes those pages themselves warn about. I then compiled and ran every example below with JDK 25, the current long-term-support release, so each one is known to work.
One note on age. Oracle's classic tutorials say they were written for JDK 8, and they point to Dev.java for newer material. So I use the old tutorials for the basics and the Java 25 pages for the newer features.
The skeleton of a Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java");
}
}A public class must be saved in a file of the same name (Hello.java). The main method is where execution starts. Statements end with a semicolon, and blocks sit inside curly braces.
Java 25 also accepts a shorter form for small programs, called a compact source file with an instance main method. Save this as Hello.java and run it with java Hello.java:
void main() {
IO.println("Hello, Java");
}It is handy for practice, but most textbooks, exams and existing code still use the full form above, so learn that first.
If you want to pass values from the terminal into args, see our post on command line arguments in Java.
Primitive types and what each can hold
Oracle's tutorial lists exactly eight primitive types.
| Type | Size | Range or note |
|---|---|---|
| byte | 8-bit signed | -128 to 127 |
| short | 16-bit signed | -32,768 to 32,767 |
| int | 32-bit signed | -2^31 to 2^31-1 |
| long | 64-bit signed | -2^63 to 2^63-1 |
| float | 32-bit | single-precision decimals |
| double | 64-bit | default choice for decimals |
| boolean | not precisely defined | true or false only |
| char | 16-bit Unicode | '\u0000' to '\uffff' |
Two lines of advice from the same page are worth memorising. Do not use float or double for currency; Oracle recommends java.math.BigDecimal. And String is not a primitive, though the language gives it special support. String objects are immutable, which means a String's contents cannot change once created.
Declaring variables and writing literals without surprises
int count = 26;
long population = 1_400_000_000L;
double price = 123.4;
float ratio = 3.14f;
char grade = 'A';
String name = "Asha";
int binary = 0b11010;
int hex = 0x1a;The rules the Oracle page states, which exam questions love:
- An integer literal is
longonly if it ends inL. Otherwise it isint. Prefer uppercaseL, since lowercasellooks like the digit 1. - A decimal literal is
floatonly if it ends inf. Otherwise it isdouble. - Underscores can separate digits for readability, but not at the start or end of a number, next to a decimal point, or before an
Lorfsuffix. - Fields get default values (0, 0.0, false, null), but local variables get none. Using an uninitialised local variable is a compile-time error.
Decisions and loops, in one block
Oracle groups control flow into decision-making (if-then, if-then-else, switch), looping (for, while, do-while) and branching (break, continue, return).
int score = 62;
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int[] nums = {1, 2, 3};
for (int n : nums) {
System.out.println(n);
}
int k = 3;
while (k > 0) {
k--;
}
do {
k++;
} while (k < 3);The do-while loop runs its body at least once, because the test comes after the body. That is the usual one-line answer when a viva asks the difference between while and do-while.
Switch expressions: the modern form
Oracle's Java language guide shows switch as an expression that produces a value. With arrow labels there is no fall-through and no break. In this example day is a value of an enum Day with the seven weekdays.
String type = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> "six letters";
case TUESDAY -> "seven letters";
default -> throw new IllegalStateException("Invalid day: " + day);
};Three rules to remember. A switch expression must be exhaustive, usually through a default, though an enum switch that lists every constant gets an implicit default. A block inside a switch expression must end with yield to hand back its value. And old-style colon labels still fall through unless you use break or yield, which is why the docs recommend arrow labels.
Classes, constructors and inheritance
Oracle's class page says a class holds fields, constructors and methods.
public class Bicycle {
public int gear;
public int speed;
public Bicycle(int startSpeed, int startGear) {
gear = startGear;
speed = startSpeed;
}
public void speedUp(int increment) {
speed += increment;
}
}
public class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int height, int startSpeed, int startGear) {
super(startSpeed, startGear);
seatHeight = height;
}
}Each public class goes in its own file (Bicycle.java and MountainBike.java). extends makes MountainBike inherit the fields and methods of Bicycle, and super(...) calls the parent constructor. Up to Java 24, an explicit super(...) had to be the first statement. Java 25 made flexible constructor bodies permanent, so you may now put statements before it, such as checking an argument, as long as they do not use the object being built.
Records: a class for plain data
A record declares its data in a header and lets the compiler write the rest.
record Rectangle(double length, double width) { }
Rectangle r = new Rectangle(4, 5);
System.out.println(r.length());According to Oracle's language guide, the compiler generates private final fields, public accessors named after the components, a canonical constructor, equals, hashCode and toString. A record is implicitly final, so it cannot be extended, and it cannot declare extra instance fields. A compact constructor lets you validate input without repeating the parameter list.
Text blocks for multi-line strings
String html = """
<html>
<body>Hello</body>
</html>
""";The opening triple quote must be followed by a line break; putting text after it on the same line is a compile error. The compiler removes the leading whitespace shared by all lines, and the position of the closing delimiter counts towards that.
Exceptions and try-with-resources
When you open a file or a stream, put it in the parentheses after try. This method needs import java.io.*; at the top of the file.
static String firstLine(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}Oracle's tutorial says each resource must implement AutoCloseable, and each is closed automatically, in reverse order of declaration, whether the block ends normally or with an exception. If the body and the close both throw, the body's exception is the one you see, and the close exceptions are suppressed.
Collections in two lines
These lines need import java.util.*;.
List<String> names = new ArrayList<>();
names.add("Ada");
Collections.sort(names);Oracle describes the Collections Framework as interfaces, implementations and algorithms, and the main benefit is that code written against an interface can switch implementations later.
Which Java version added which feature
Oracle's page of language changes by release gives these versions as the point where each feature became permanent, after earlier preview releases.
| Feature | Permanent from |
|---|---|
| Switch expressions | Java 14 |
| Text blocks | Java 15 |
| Records, pattern matching for instanceof | Java 16 |
| Sealed classes | Java 17 |
| Pattern matching for switch, record patterns | Java 21 |
| Compact source files and instance main methods, flexible constructor bodies | Java 25 |
If your college lab still runs Java 8 or 11, none of these will compile there, so ask which version your exam uses.
What Java syntax do I need to revise the night before an exam or interview?
This is the long question behind most last-minute searches, so here is a checklist ordered by how often these slips cost marks.
- The
mainsignature and the file name rule. - Eight primitive types and their sizes.
Landfsuffixes, and underscores in literals.- Local variables have no default; fields do.
- Strings are immutable.
- while versus do-while.
- Arrow switch with
yield, and exhaustiveness. extends,super(...)and constructor order.- A record's generated members.
- try-with-resources and closing order.
If you can write each of these from memory, you are ready.
Where Java sits if your goal is AI work
Many people learning Java are also curious about AI. It helps to be clear about the difference in tools. IIT Patna's Certification in Artificial Intelligence and Machine Learning is offered by Vishlesan i-Hub, IIT Patna, with a delivery partner. Its official page describes an online format of about 10 hours a week over 8 months, open to 12th pass and above.
The page's curriculum names Python, Git and GitHub, SQL, NumPy and Pandas first, then machine learning, deep learning, generative AI and deployment. It does not mention Java. So if AI engineering is your goal, plan to learn Python alongside your Java, which is also useful for general programming practice. Admission is a 60-minute qualifier test, counselling for shortlisted candidates, then learning. Check the page for fees and current dates.
For a wider view of the developer path, read how to become a software developer.
How I checked this sheet
I read Oracle's Language Basics trail, its pages on primitive data types, control flow, classes and try-with-resources, the Java 21 and Java 25 language guides on records, switch expressions, text blocks and flexible constructor bodies, Oracle's list of language changes by release, and Dev.java's learning page, on 4 and 5 December 2026. Some code lines above are my own short examples built on those rules, and all of them compiled and ran on JDK 25. The OpenJDK enhancement pages blocked automated reading, so the version table rests on Oracle's documentation. Confirm against the version your course or employer uses.
Official references: Oracle's primitive data types page, the control flow page, records in the Java 25 guide, Oracle's language changes by release, try-with-resources and Dev.java's learning page.
Frequently asked questions
What is the basic syntax of Java?
A Java program is a class containing methods, with execution starting at the main method. Statements end with semicolons and blocks use curly braces. Variables are declared with a type, such as int or String. Control flow uses if, switch, for, while and do-while. Learn this skeleton first and add other features one at a time.
How many primitive data types are there in Java?
Eight: byte, short, int, long, float, double, boolean and char. Oracle's tutorial lists them with sizes from 8 bits for byte to 64 bits for long and double. String is not a primitive, though it has special language support and its objects are immutable.
Should I use float or double for money in Java?
Neither. Oracle's tutorial says float and double should not be used for precise values such as currency, and it recommends java.math.BigDecimal instead. Binary floating point cannot represent many decimal amounts exactly, so use BigDecimal for prices, balances and anything that is added up and compared.
What is the difference between while and do-while loops?
A while loop checks its condition before running the body, so it may never run. A do-while loop runs the body first and checks afterwards, so it always runs at least once. Use do-while when the action must happen once before you can decide whether to repeat it.
When should I use a record instead of a class?
Use a record when the type only carries data, such as coordinates or a result with two fields. Oracle's guide says the compiler generates the accessors, constructor, equals, hashCode and toString. Use a normal class when you need changeable state, inheritance or extra instance fields, since records cannot extend or add them.
Do I need to learn Java before AI and machine learning?
Not necessarily. The AI programme page I read lists Python, SQL, NumPy and Pandas as its foundation and does not mention Java. Java remains valuable for general software development, so learn it if your course or target job needs it, and add Python when your goal is data or AI work.