Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Printable · 2 pages · free

Core Java cheat sheet

A printable Core Java cheat sheet for revision: syntax, data types, strings, arrays, OOP, exceptions, collections, streams, files and JDBC, with short examples.

Read the full notes

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

TypeSizeExample
byte / short1 / 2 bytesbyte b = 10;
int4 bytesint n = 25;
long8 byteslong p = 9_000_000_000L;
float4 bytesfloat f = 3.5f;
double8 bytesdouble d = 3.5;
char2 byteschar 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 / int drops decimals: 7 / 2 is 3)
  • 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

CodeResult 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 }
AccessClassPackageSubclassAll
privateyesnonono
noneyesyesnono
protectedyesyesyesno
publicyesyesyesyes

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

NeedUse
ordered listList<String> l = new ArrayList<>();
no duplicatesSet<String> s = new HashSet<>(); (TreeSet sorted)
key to valueMap<String,Integer> m = new HashMap<>(); (TreeMap sorted)
queue / stackDeque<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.