Java Cheat Sheet
By the Syncfusion DevTutorials team · Last updated
Every topic in the Java course on one page: syntax, the methods used most, and the mistakes that cost the most time.
This page is a quick reference for everything covered in the course. It is written to be scanned, not read through.
Each section gives the syntax, the parts you reach for most, and the one thing people get wrong.
Program Structure
Every Java program lives in a class. Execution starts at main.
A whole program
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
System.out.println(add(4, 6));
}
static int add(int first, int second) {
return first + second;
}
}
Expected output:
Hello
10
| Piece | Purpose |
|---|---|
public class Main | The class; a public class must match its file name, Main.java |
public static void main(String[] args) | Where the program starts |
System.out.println(x) | Prints a line |
System.out.print(x) | Prints without a new line |
// and /* */ | Comments |
; | Ends every statement |
javac Main.java then java Main | Compile, then run |
Every runnable cell on this page is self-contained. Change the values and run it again to check what you remember.
Variables and Data Types
| Type | Holds | Default | Example |
|---|---|---|---|
byte | -128 to 127 | 0 | byte b = 12; |
short | -32,768 to 32,767 | 0 | short s = 2026; |
int | Whole numbers (default choice) | 0 | int count = 10; |
long | Large whole numbers | 0 | long views = 8000000000L; |
float | Decimals, about 7 digits | 0.0 | float r = 4.5f; |
double | Decimals (default choice) | 0.0 | double price = 199.99; |
char | One character | '\u0000' | char grade = 'A'; |
boolean | true or false | false | boolean ok = true; |
String | Text (a class) | null | String name = "Asha"; |
Declaring, constants, var and conversions
public class Main {
public static void main(String[] args) {
int count = 10;
double average = 82.5;
final int MAX_USERS = 100;
var city = "Pune";
double widened = count;
int narrowed = (int) 9.99;
int parsed = Integer.parseInt("42");
String text = String.valueOf(3.5);
System.out.println(count + " " + average + " " + MAX_USERS + " " + city);
System.out.println(widened + " " + narrowed + " " + parsed + " " + text);
}
}
Expected output:
10 82.5 100 Pune
10.0 9 42 3.5
- Widening (small → big type) is automatic. Narrowing needs a cast and can lose data.
(int) 9.99cuts off the decimal part. It does not round.- Parse text:
Integer.parseInt,Double.parseDouble,Boolean.parseBoolean. Turn values into text:String.valueOf.
Input With Scanner
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
String name = sc.nextLine(); // a whole line
int age = sc.nextInt(); // a whole number
sc.nextLine(); // clear the rest of the line after nextInt
Operators
| Group | Operators |
|---|---|
| Arithmetic | + - * / % |
| Increment / decrement | ++ -- |
| Comparison | == != > < >= <= |
| Logical | && || ! |
| Assignment | = += -= *= /= %= |
| Ternary | condition ? a : b |
| Bitwise / shift | & | ^ ~ << >> >>> |
The ones that surprise people
public class Main {
public static void main(String[] args) {
System.out.println(7 / 2);
System.out.println(7 / 2.0);
System.out.println(17 % 5);
System.out.println("Sum: " + 2 + 3);
System.out.println("Sum: " + (2 + 3));
int x = 5;
int y = x++;
System.out.println("x=" + x + ", y=" + y);
}
}
Expected output:
3
3.5
2
Sum: 23
Sum: 5
x=6, y=5
Conditional Statements
if, else if, ternary and switch
public class Main {
public static void main(String[] args) {
int marks = 76;
if (marks >= 90) {
System.out.println("A");
} else if (marks >= 75) {
System.out.println("B");
} else {
System.out.println("C");
}
String result = marks >= 40 ? "Pass" : "Fail";
System.out.println(result);
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}
String size = "M";
int price = switch (size) {
case "S" -> 199;
case "M" -> 249;
default -> 299;
};
System.out.println(price);
}
}
Expected output:
B
Pass
Wednesday
249
- Compare text with
.equals(), never==. - A classic
switchcase needsbreak, or it falls through to the next case. The arrow form->never falls through.
Loops
for, while, do-while, for-each, break and continue
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.print(i + " ");
}
System.out.println();
int n = 3;
while (n > 0) {
System.out.print(n + " ");
n--;
}
System.out.println();
int tries = 0;
do {
tries++;
} while (tries < 0);
System.out.println("do-while ran " + tries + " time");
int[] marks = {72, 35, 88};
for (int m : marks) {
if (m < 40) continue;
System.out.print(m + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++) {
if (i == 4) break;
System.out.print(i + " ");
}
System.out.println();
}
}
Expected output:
1 2 3
3 2 1
do-while ran 1 time
72 88
1 2 3
| Loop | Use when |
|---|---|
for | You know the count |
while | You wait for a condition (may run 0 times) |
do-while | The body must run at least once |
| for-each | You read every item in an array or collection |
Methods
Parameters, returns, overloads, varargs and recursion
public class Main {
public static void main(String[] args) {
System.out.println(area(4, 6));
System.out.println(area(5));
System.out.println(sum(1, 2, 3, 4));
System.out.println(factorial(5));
greet("Ravi");
}
static int area(int w, int h) { return w * h; }
static int area(int side) { return side * side; }
static int sum(int... values) {
int total = 0;
for (int v : values) total += v;
return total;
}
static int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
}
Expected output:
24
25
10
120
Hello, Ravi
- Java is pass by value. A method gets a copy; for objects, a copy of the reference.
voidmethods return nothing. Every path of a non-void method mustreturn.
Arrays
1D, 2D and the Arrays class
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {72, 95, 58};
String[] names = new String[2];
names[0] = "Asha";
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));
System.out.println("Length: " + scores.length);
System.out.println("Second name: " + names[1]);
System.out.println("grid[1][2]: " + grid[1][2]);
System.out.println("Index of 95: " + Arrays.binarySearch(scores, 95));
System.out.println(Arrays.toString(Arrays.copyOf(scores, 5)));
}
}
Expected output:
[58, 72, 95]
Length: 3
Second name: null
grid[1][2]: 6
Index of 95: 2
[58, 72, 95, 0, 0]
- Indexes run from
0tolength - 1. Arrays uselength, with no brackets.
Strings
The methods used most
public class Main {
public static void main(String[] args) {
String s = " Hello, Java ";
String t = s.trim();
System.out.println(t.length());
System.out.println(t.toUpperCase());
System.out.println(t.charAt(0));
System.out.println(t.indexOf("Java"));
System.out.println(t.substring(0, 5));
System.out.println(t.replace("Java", "World"));
System.out.println(t.contains("Java"));
System.out.println("a,b,c".split(",").length);
System.out.println("java".equals("JAVA") + " " + "java".equalsIgnoreCase("JAVA"));
StringBuilder sb = new StringBuilder("ab");
sb.append("cd").reverse();
System.out.println(sb);
}
}
Expected output:
11
HELLO, JAVA
H
7
Hello
Hello, World
true
3
false true
dcba
- Strings are immutable: methods return new strings, so store the result.
- Build text in a loop with
StringBuilder.
DateTime
LocalDate, formatting, arithmetic and periods
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2026, 1, 31);
DateTimeFormatter indian = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(start.plusDays(10));
System.out.println(start.plusMonths(1));
System.out.println(start.format(indian));
System.out.println(LocalDate.parse("15/08/2026", indian));
System.out.println(start.isBefore(LocalDate.of(2026, 2, 1)));
System.out.println(Period.between(LocalDate.of(2008, 3, 14), LocalDate.of(2026, 10, 7)));
}
}
Expected output:
2026-02-10
2026-02-28
31/01/2026
2026-08-15
true
P18Y6M23D
| Class | Holds |
|---|---|
LocalDate | A date |
LocalTime | A time |
LocalDateTime | A date and a time |
ZonedDateTime | A date and time in a time zone |
Duration / Period | A gap in time / in calendar days |
MMis months,mmis minutes.
Classes and Objects
Fields, constructors, this, getters and static
public class Main {
public static void main(String[] args) {
Account a = new Account("Asha", 500);
a.deposit(200);
a.deposit(-50);
System.out.println(a.getOwner() + ": " + a.getBalance());
System.out.println("Accounts created: " + Account.count);
}
}
class Account {
static int count = 0;
private final String owner;
private int balance;
Account(String owner, int balance) {
this.owner = owner;
this.balance = balance;
count++;
}
public String getOwner() { return owner; }
public int getBalance() { return balance; }
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
}
Expected output:
Asha: 700
Accounts created: 1
| Modifier | Visible to |
|---|---|
private | This class only |
| default (none) | This package |
protected | This package and child classes |
public | Everyone |
Inheritance, Polymorphism and Abstraction
extends, super, @Override and abstract
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2), new Square(3) };
for (Shape s : shapes) {
s.describe();
}
Shape s = shapes[1];
if (s instanceof Square sq) {
System.out.println("Side: " + sq.side);
}
}
}
abstract class Shape {
String name;
Shape(String name) {
this.name = name;
}
abstract double area();
void describe() {
System.out.println(name + " area: " + area());
}
}
class Circle extends Shape {
double r;
Circle(double r) { super("Circle"); this.r = r; }
@Override double area() { return 3.0 * r * r; }
}
class Square extends Shape {
double side;
Square(double side) { super("Square"); this.side = side; }
@Override double area() { return side * side; }
}
Expected output:
Circle area: 12.0
Square area: 9.0
Side: 3.0
extendsone class;implementsmany interfaces.- The object's real type decides which overridden method runs.
- Always mark overrides with
@Override.
Interfaces, Enums and Records
The other type kinds
public class Main {
public static void main(String[] args) {
Greeter g = name -> "Hello, " + name;
System.out.println(g.greet("Meena"));
Size s = Size.M;
System.out.println(s + " costs " + s.price());
Point p = new Point(3, 4);
System.out.println(p + " x=" + p.x());
System.out.println(p.equals(new Point(3, 4)));
}
}
interface Greeter {
String greet(String name);
}
enum Size {
S(199), M(249), L(299);
private final int price;
Size(int price) { this.price = price; }
int price() { return price; }
}
record Point(int x, int y) { }
Expected output:
Hello, Meena
M costs 249
Point[x=3, y=4] x=3
true
| Kind | Use for |
|---|---|
interface | An ability many classes share |
abstract class | A half-built parent with shared code |
enum | A fixed list of choices |
record | Small data that never changes |
sealed | A type with a fixed list of children |
Exception Handling
try, catch, finally, throw and a custom exception
public class Main {
public static void main(String[] args) {
try {
int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Not a number");
} finally {
System.out.println("finally always runs");
}
try {
withdraw(100, 500);
} catch (LowBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
}
static void withdraw(int balance, int amount) throws LowBalanceException {
if (amount > balance) {
throw new LowBalanceException("Need " + (amount - balance) + " more");
}
}
}
class LowBalanceException extends Exception {
LowBalanceException(String message) {
super(message);
}
}
Expected output:
Not a number
finally always runs
Error: Need 400 more
| Kind | Extends | Must catch or declare? |
|---|---|---|
| Checked | Exception | Yes |
| Unchecked | RuntimeException | No |
| Error | Error | No, do not catch |
- Catch specific exceptions before general ones.
throwraises;throwsdeclares.
Packages
package com.syncshop.billing; // first line of the file
import java.util.List; // one class
import java.util.*; // a whole package
import static java.lang.Math.PI; // a static member
- Package names are lowercase, starting with your domain reversed:
com.company.project. java.langis imported automatically.
Generics
A generic class, a generic method and a bound
import java.util.List;
public class Main {
public static void main(String[] args) {
Box<String> box = new Box<>("Asha");
System.out.println(box.get());
System.out.println(first(List.of(7, 3, 9)));
System.out.println(total(List.of(1.5, 2.5)));
}
static <T> T first(List<T> items) {
return items.get(0);
}
static double total(List<? extends Number> nums) {
double sum = 0;
for (Number n : nums) sum += n.doubleValue();
return sum;
}
}
class Box<T> {
private final T item;
Box(T item) { this.item = item; }
T get() { return item; }
}
Expected output:
Asha
7
4.0
- Use wrapper types:
List<Integer>, neverList<int>. - PECS: read with
? extends, write with? super.
Collections
List, Set, Map, Stack and Queue
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Pen", "Bag", "Pen"));
list.add("Cap");
System.out.println(list + " size " + list.size());
Set<String> set = new TreeSet<>(list);
System.out.println(set);
Map<String, Integer> prices = new TreeMap<>();
prices.put("Pen", 20);
prices.put("Bag", 499);
System.out.println(prices.get("Bag") + " " + prices.getOrDefault("Hat", 0));
Deque<String> stack = new ArrayDeque<>();
stack.push("a");
stack.push("b");
System.out.println("Stack pops: " + stack.pop());
Queue<String> queue = new ArrayDeque<>();
queue.offer("first");
queue.offer("second");
System.out.println("Queue polls: " + queue.poll());
}
}
Expected output:
[Pen, Bag, Pen, Cap] size 4
[Bag, Cap, Pen]
499 0
Stack pops: b
Queue polls: first
| Need | Use |
|---|---|
| Items in order, duplicates allowed | ArrayList |
| Unique items, fast checks | HashSet (TreeSet for sorted) |
| Look up a value by key | HashMap (TreeMap for sorted keys) |
| Last in, first out | ArrayDeque as a stack |
| First in, first out | ArrayDeque or LinkedList as a queue |
| Smallest first | PriorityQueue |
- Remove while looping with
removeIfor anIterator, neverlist.removeinside for-each.
Lambdas and Streams
Lambdas, method references and a stream pipeline
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<String, Integer> length = String::length;
System.out.println(isEven.test(4) + " " + length.apply("Java"));
List<Integer> marks = List.of(72, 35, 88, 28, 64, 91);
List<Integer> passed = marks.stream()
.filter(m -> m >= 40)
.sorted()
.toList();
System.out.println(passed);
int total = marks.stream().reduce(0, Integer::sum);
long high = marks.stream().filter(m -> m > 80).count();
String joined = List.of("a", "b", "c").stream().collect(Collectors.joining("-"));
System.out.println(total + " " + high + " " + joined);
}
}
Expected output:
true 4
[64, 72, 88, 91]
378 2 a-b-c
| Interface | Takes | Returns |
|---|---|---|
Predicate<T> | One value | boolean |
Function<T, R> | One value | A value |
Consumer<T> | One value | Nothing |
Supplier<T> | Nothing | A value |
- Intermediate:
filter,map,sorted,distinct,limit,skip. Terminal:collect,toList,forEach,reduce,count,findFirst,anyMatch,allMatch. - A stream can only be used once.
File Handling
Path file = Path.of("notes.txt");
Files.writeString(file, "Hello\n"); // replace
Files.writeString(file, "More\n", StandardOpenOption.CREATE,
StandardOpenOption.APPEND); // append
String all = Files.readString(file);
List<String> lines = Files.readAllLines(file);
try (BufferedReader r = new BufferedReader(new FileReader("notes.txt"))) {
String line;
while ((line = r.readLine()) != null) { ... }
}
- Put every file, reader and writer in try-with-resources so it is closed.
- File methods throw
IOException, a checked exception.
Multithreading
Threads, join and synchronized
public class Main {
static int count = 0;
static synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 1000; i++) increment();
};
Thread a = new Thread(job, "worker-a");
Thread b = new Thread(job, "worker-b");
a.start();
b.start();
a.join();
b.join();
System.out.println("Count: " + count);
System.out.println("State of a: " + a.getState());
}
}
Expected output:
Count: 2000
State of a: TERMINATED
start()creates a thread; callingrun()does not.join()waits for a thread to finish.- Guard shared, changing data with
synchronized. Take several locks in the same order to avoid deadlocks.
Optional and Pattern Matching
Optional and switch patterns
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> found = Optional.of("Ravi");
Optional<String> missing = Optional.empty();
System.out.println(found.orElse("nobody") + " " + missing.orElse("nobody"));
found.ifPresent(name -> System.out.println("Hi, " + name));
Object[] values = {250, -5, "hello"};
for (Object v : values) {
String label = switch (v) {
case Integer i when i > 100 -> "big number";
case Integer i -> "number";
case String s -> "text of length " + s.length();
default -> "other";
};
System.out.println(label);
}
}
}
Expected output:
Ravi nobody
Hi, Ravi
big number
number
text of length 5
- Create with
Optional.of,Optional.ofNullableorOptional.empty(). Avoidget()without a check. orElsealways builds its fallback;orElseGetbuilds it only when empty.obj instanceof String schecks and casts in one step.
Check What You Remember
This page is a reminder, not a replacement for the lessons. If a line here does not make sense, go back to that chapter and work through its examples.
The Mistakes That Cost the Most Time
| Symptom | Cause | Fix |
|---|---|---|
';' expected | A statement has no semicolon | Add ; |
cannot find symbol | A typo, a wrong capital letter, or a missing import | Check spelling, case and imports |
incompatible types: possible lossy conversion | A bigger type was stored in a smaller one | Use the right type, or cast |
| An average comes out as a whole number | Both operands are int | Make one a double |
| Text that looks the same does not match | == was used on strings | Use .equals() |
NullPointerException | A method was called on null | Check for null, or use Optional |
ArrayIndexOutOfBoundsException | <= used with length | Loop with i < array.length |
ConcurrentModificationException | A collection changed during a for-each loop | Use removeIf or an Iterator |
unreported exception ... must be caught or declared | A checked exception was ignored | Catch it, or add throws |
| A written file is empty | The writer was never closed | Use try-with-resources |
| A total changes every run with threads | A race condition | Use synchronized |
| The program freezes with threads | A deadlock | Take locks in the same order |