Java quick reference
Syntax, rules and tables from the whole course on one searchable page.
No section matches.
Program skeleton
import java.util.Scanner;
public class Main { // file: Main.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println("n = " + n);
}
}Compile javac Main.java · run java Main. JDK ⊃ JRE ⊃ JVM.
Primitive types
| Type | Bits | Range | Literal |
|---|---|---|---|
| byte | 8 | −128 … 127 | (byte) 10 |
| short | 16 | −32768 … 32767 | (short) 10 |
| int | 32 | −2³¹ … 2³¹−1 | 42, 0x2A, 0b101010, 1_000 |
| long | 64 | −2⁶³ … 2⁶³−1 | 42L |
| float | 32 | ~7 digits | 3.14f |
| double | 64 | ~15 digits | 3.14, 1e-3 |
| char | 16 | 0 … 65535 (Unicode) | 'A', '\n', '\u0041' |
| boolean | — | true / false | true |
Widening (automatic): byte → short → int → long → float → double; char → int. Narrowing needs a cast: (int) 3.9 → 3.
Operator precedence (high → low)
| Level | Operators |
|---|---|
| postfix | x++ x-- |
| unary | ++x --x +x -x ! ~ (type) |
| multiplicative | * / % |
| additive | + - |
| shift | << >> >>> |
| relational | < > <= >= instanceof |
| equality | == != |
| bitwise | & then ^ then | |
| logical | && then || |
| ternary | ? : |
| assignment | = += -= *= /= %= … |
Control flow
if (a > b) { ... } else if (a == b) { ... } else { ... }
switch (day) { case 1: ...; break; default: ... }
String t = switch (day) { case 6, 7 -> "Weekend"; default -> "Weekday"; };
for (int i = 0; i < n; i++) { ... }
for (int x : arr) { ... }
while (cond) { ... }
do { ... } while (cond);
outer: for (...) { for (...) { if (done) break outer; if (skip) continue outer; } }Arrays
int[] a = new int[5]; int[] b = {3, 1, 2};
int[][] m = new int[3][4]; int[][] j = { {1}, {2, 3} };
a.length m[0].length
Arrays.sort(b); Arrays.toString(b); Arrays.copyOf(b, 5);
Arrays.fill(a, 7); Arrays.equals(a, b); Arrays.binarySearch(b, 2);Classes, objects and constructors
public class Student {
private String name; // field
private static int count = 0; // class-wide
public Student() { this("Unknown"); } // constructor chaining
public Student(String name) { this.name = name; count++; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public String toString() { return "Student " + name; }
}
Student s = new Student("Ann");- No constructor written → Java adds a default no-arg one.
- Fields default to 0 / 0.0 / false / null; local variables have no default.
Access modifiers
| Class | Package | Subclass (other pkg) | World | |
|---|---|---|---|---|
| private | ✓ | |||
| (default) | ✓ | ✓ | ||
| protected | ✓ | ✓ | ✓ | |
| public | ✓ | ✓ | ✓ | ✓ |
static and final
| Keyword | On a variable | On a method | On a class |
|---|---|---|---|
| static | one copy per class | called on the class; no this | only nested classes |
| final | assign once (constant) | cannot be overridden | cannot be extended |
Overloading vs overriding
| Overloading | Overriding | |
|---|---|---|
| Signature | different parameters | same parameters |
| Return type | any | same or subtype |
| Resolved | compile time | run time (dynamic dispatch) |
| Where | same class | subclass |
Inheritance and polymorphism
class Dog extends Animal {
Dog(String n) { super(n); } // first statement
@Override String sound() { return "Woof"; }
String both() { return super.sound() + sound(); }
}
Animal a = new Dog("Rex"); // upcast (automatic)
a.sound(); // Dog's version runs
if (a instanceof Dog d) d.fetch(); // pattern + downcastConstructors run top-down (Object → Animal → Dog). A class extends one class and implements many interfaces.
Abstract classes and interfaces
| abstract class | interface | |
|---|---|---|
| Instantiate? | No | No |
| Fields | any | public static final only |
| Constructors | yes | no |
| Methods | abstract + concrete | abstract, default, static, private |
| Inheritance | extends (one) | implements (many) |
interface Payable { double getPayment(); default String currency() { return "BDT"; } }
abstract class Shape { abstract double area(); }Packages
package bd.edu.green.cse.model; // first line of the file import java.util.ArrayList; // one class import java.util.*; // whole package (not sub-packages) import static java.lang.Math.PI; // static import
java.lang is imported automatically. Folder path = package name.
Exceptions
try {
risky();
} catch (FileNotFoundException e) { // specific first
...
} catch (IOException | NumberFormatException e) {
System.out.println(e.getMessage());
} finally {
cleanUp(); // always runs
}
void read() throws IOException { throw new IOException("disk"); }
class MyException extends Exception { MyException(String m) { super(m); } }
try (Scanner sc = new Scanner(new File("a.txt"))) { ... } // auto-closeChecked: Exception but not RuntimeException (IOException, SQLException, InterruptedException). Unchecked: RuntimeException (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, ClassCastException).
Threads
Thread t = new Thread(() -> work(), "worker");
t.start(); t.join(); Thread.sleep(500);
class MyThread extends Thread { public void run() { ... } }
synchronized void inc() { count++; }
synchronized (lock) { ... }
while (!ready) wait(); // inside synchronized
notifyAll();States: NEW → RUNNABLE ⇄ BLOCKED / WAITING / TIMED_WAITING → TERMINATED.
String methods
| Call | Result |
|---|---|
| "Hello".length() | 5 |
| "Hello".charAt(1) | 'e' |
| "Hello".indexOf("l") | 2 |
| "Hello".substring(1, 3) | "el" |
| " hi ".trim() | "hi" |
| "a,b".split(",") | {"a", "b"} |
| "Java".toUpperCase() | "JAVA" |
| "ab".equals("AB") | false |
| "ab".equalsIgnoreCase("AB") | true |
| "apple".compareTo("apricot") | -2 |
| "x".repeat(3) | "xxx" |
| String.valueOf(12) | "12" |
| Integer.parseInt("12") | 12 |
StringBuilder sb = new StringBuilder();
sb.append("a").append(1).insert(0, "[").reverse().toString();
BigInteger big = new BigInteger("123456789012345678901234567890").multiply(BigInteger.TEN);JavaFX
public class App extends Application {
public void start(Stage stage) {
Button b = new Button("OK");
b.setOnAction(e -> System.out.println("clicked"));
VBox root = new VBox(10, new Label("Hi"), b);
stage.setScene(new Scene(root, 300, 200));
stage.show();
}
public static void main(String[] a) { launch(a); }
}Layouts: HBox, VBox, FlowPane, GridPane (add(node, col, row)), BorderPane (setTop/Center/…), StackPane. Drawing: Canvas → getGraphicsContext2D() → fillRect, fillOval, strokeLine, fillText. Animation: AnimationTimer.handle(now).
JDBC
try (Connection con = DriverManager.getConnection(url, user, pass);
PreparedStatement ps = con.prepareStatement("SELECT name FROM students WHERE cgpa >= ?")) {
ps.setDouble(1, 3.5);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) System.out.println(rs.getString("name"));
}
} // executeUpdate() for INSERT / UPDATE / DELETE