Core Java cheat sheet · BrainBit Infotech Teaching · brainbit-teaching.com/courses/core-java/notes/cheatsheet/
Basics
Program skeleton
import java.util.Scanner;
public class Main { // file must be Main.java
public static void main(String[] args) {
System.out.println("Hi"); // print + new line
System.out.printf("%d %.2f %s%n", 5, 3.14159, "x");
}
}
javac Main.java then java Main. Or java Main.java for one file.
Data types
| Type | Size | Example |
|---|---|---|
byte / short | 1 / 2 bytes | byte b = 10; |
int | 4 bytes | int n = 25; |
long | 8 bytes | long p = 9_000_000_000L; |
float | 4 bytes | float f = 3.5f; |
double | 8 bytes | double d = 3.5; |
char | 2 bytes | char c = 'A'; |
boolean | - | boolean ok = true; |
String s = "text"; is a class. final int MAX = 60; is a constant. var x = 10; infers int.
Casting and conversion
double d = 7; // widening: automatic
int i = (int) 9.99; // narrowing: 9
int n = Integer.parseInt("42");
double v = Double.parseDouble("3.5");
String s = String.valueOf(42);
Operators
- Arithmetic:
+ - * / %(int / intdrops decimals:7 / 2is3) - Compare:
== != > < >= <= - Logical:
&&(and),||(or),!(not) - Assign:
= += -= *= /= %=, and++ -- - Ternary:
cond ? a : b
Input
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
double b = sc.nextDouble();
sc.nextLine(); // eat the leftover newline
String line = sc.nextLine();
Control flow
if (m >= 90) g = 'A'; else if (m >= 75) g = 'B'; else g = 'C';
String t = switch (day) {
case "SAT", "SUN" -> "Weekend";
default -> "Weekday";
};
for (int i = 0; i < n; i++) { }
for (String x : list) { }
while (cond) { }
do { } while (cond);
break; continue; outer: for (...) { break outer; }
Methods
static int add(int a, int b) { return a + b; } // overloading:
static double add(double a, double b) { return a + b; } // same name, new params
static int sum(int... nums) { ... } // varargs
Java passes copies of values. Recursion needs a base case.
Strings
| Code | Result for s = "Java Notes" |
|---|---|
s.length() | 10 |
s.charAt(0) | 'J' |
s.indexOf("No") | 5 |
s.substring(5) | "Notes" |
s.substring(0, 4) | "Java" |
s.toUpperCase() | "JAVA NOTES" |
s.split(" ") | ["Java", "Notes"] |
s.replace("a", "@") | "J@v@ Notes" |
s.contains("Not") | true |
s.equals(t) | compare text (never ==) |
Strings are immutable. Build in loops with StringBuilder: sb.append(x), sb.reverse(), sb.toString().
Arrays
int[] a = new int[5]; // zeros
int[] b = {3, 1, 2};
b.length; // 3 (no brackets)
Arrays.sort(b); // [1, 2, 3]
Arrays.toString(b); // "[1, 2, 3]"
int[][] g = new int[3][4]; // g[row][col]
OOP
public class Account {
private double balance; // encapsulation
private static int count; // shared by all objects
public Account(double opening) { // constructor
this.balance = opening;
count++;
}
public double getBalance() { return balance; }
@Override
public String toString() { return "Account " + balance; }
}
class Savings extends Account { // inheritance
Savings(double o) { super(o); } // parent constructor first
}
abstract class Shape { abstract double area(); }
interface Payable { double amountDue(); } // class X implements A, B
record Point(int x, int y) { } // immutable data class
enum Status { NEW, PAID, SHIPPED }
| Access | Class | Package | Subclass | All |
|---|---|---|---|---|
private | yes | no | no | no |
| none | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
Polymorphism: Account a = new Savings(100); calls Savings' overrides at run time. Check with if (a instanceof Savings s).
Exceptions
try {
risky();
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
} finally {
cleanUp(); // always runs
}
try (BufferedReader br = Files.newBufferedReader(Path.of("f.txt"))) { } // auto-close
throw new IllegalArgumentException("bad"); // raise
void read() throws IOException { } // declare (checked)
class MyEx extends Exception { MyEx(String m) { super(m); } }
Checked (must handle): IOException, SQLException. Unchecked (RuntimeException): NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.
Collections
| Need | Use |
|---|---|
| ordered list | List<String> l = new ArrayList<>(); |
| no duplicates | Set<String> s = new HashSet<>(); (TreeSet sorted) |
| key to value | Map<String,Integer> m = new HashMap<>(); (TreeMap sorted) |
| queue / stack | Deque<Integer> q = new ArrayDeque<>(); |
l.add("a"); l.get(0); l.remove(0); l.size(); l.contains("a");
m.put("pen", 10); m.get("pen"); m.getOrDefault("ink", 0);
m.merge(word, 1, Integer::sum); // counting
for (Map.Entry<String,Integer> e : m.entrySet()) { e.getKey(); e.getValue(); }
Collections.sort(l);
l.sort(Comparator.comparing(Student::name).reversed());
Lambdas and streams
Predicate<Integer> pass = m -> m >= 40;
list.forEach(System.out::println);
List<Integer> top = marks.stream()
.filter(m -> m >= 40)
.map(m -> m + 5)
.sorted()
.toList();
int total = marks.stream().mapToInt(Integer::intValue).sum();
Map<String, List<Student>> byCity =
students.stream().collect(Collectors.groupingBy(Student::city));
Files and dates
Files.writeString(Path.of("a.txt"), "hi\n");
List<String> lines = Files.readAllLines(Path.of("a.txt"));
LocalDate d = LocalDate.of(2026, 12, 15).plusDays(7);
Period age = Period.between(dob, LocalDate.now());
d.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
Threads
Thread t = new Thread(() -> System.out.println("run"));
t.start(); t.join();
synchronized void inc() { count++; }
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(task); pool.shutdown();
JDBC
try (Connection con = DriverManager.getConnection("jdbc:sqlite:school.db");
PreparedStatement ps = con.prepareStatement("SELECT name FROM student WHERE marks > ?")) {
ps.setInt(1, 60);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) System.out.println(rs.getString("name"));
}
}
executeQuery for SELECT, executeUpdate for INSERT, UPDATE and DELETE. Always use ? placeholders.