Java Reference
0. Basics
0.1 Hello World
public class Main {
public static void main(String[] args) {
// System.out.println() prints to STDOUT with a newline
System.out.println("Hello, World!");
}
}Hello, World!
0.2 Building & Running
Java is a compiled language that runs on the JVM. Use
javac to compile and java to
run.
# Compile the Java source file into bytecode (.class)
javac Main.java
# Run the compiled class (must contain a main method)
java MainHello, World!
0.3 Comments
// Single-line comment for brief annotations
/* Multi-line
comment block for extensive documentation */
/**
* Javadoc comment used for generating
* API documentation in HTML format.
*/(No output)
0.4 Imports
import java.util.List; // Import a specific class
import java.util.*; // Import all classes in a package
import static java.lang.Math.PI; // Import a static member (constant)(No output)
0.5 Exit Codes
public class Main {
public static void main(String[] args) {
// System.exit(status) terminates the JVM with an exit code
// 0 for success, non-zero (e.g., 1) for failure
System.exit(1);
}
}(Process exits with status 1)
0.6 Error Handling
Java uses try-catch-finally for structured
exception handling.
public class Main {
public static void main(String[] args) {
try {
// Explicitly throw a checked or unchecked exception
throw new RuntimeException("failed");
} catch (RuntimeException e) {
// Catch specific exception and print its message
System.err.println("Error: " + e.getMessage());
} finally {
// Always executes, used for resource cleanup
System.out.println("Cleanup");
}
}
}Error: failed
Cleanup
1. Environment, Variables & Time
1.1 Variable Declaration
Modern Java (11+) supports local variable type inference
with var.
int x = 5; // Mutable integer with explicit type
final double PI = 3.14; // Immutable constant using 'final'
var name = "Java"; // Type inference (inferred as String)(No output)
1.2 Integer Types & Limits
| Size | Signed Type | Range / Constant |
|---|---|---|
| 8-bit | byte |
Byte.MIN_VALUE to
Byte.MAX_VALUE |
| 16-bit | short |
Short.MIN_VALUE
to Short.MAX_VALUE |
| 32-bit | int |
Integer.MIN_VALUE
to Integer.MAX_VALUE |
| 64-bit | long |
Long.MIN_VALUE to
Long.MAX_VALUE |
Limits: Integer.MAX_VALUE
is 2,147,483,647.
1.3 Casting
Implicit for widening; explicit required for narrowing (potential data loss).
double d = 3.99;
// Explicit narrowing cast from double to int (truncation)
int i = (int) d; // Result: 3(No output)
1.4 Truthiness
In Java, only boolean values
(true, false) are valid in
conditional expressions.
boolean ok = true;
if (ok) {
// 0 or null are NOT truthy/falsy in Java
System.out.println("Condition met");
}Condition met
1.5 Environment Variables
// Retrieve an environment variable from the system
String path = System.getenv("PATH");
// Access system properties (JVM-specific configurations)
String version = System.getProperty("java.version");(No output)
1.6 Time Measurement & Formatting
Using the java.time package (since Java
8).
import java.time.*;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// High-resolution monotonic clock for performance measurement
long start = System.nanoTime();
long end = System.nanoTime();
long elapsedNs = end - start;
// Current date and time formatting
LocalDateTime now = LocalDateTime.now();
var fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(now.format(fmt));
}
}2024-05-16 12:00:00 (example)
2. Operators & Regex
2.1 Arithmetic & Logic
int a = 10 / 3; // Integer division (3)
double b = 10.0 / 3.0; // Floating point division (3.333...)
int rem = 10 % 3; // Modulo operator (1)
boolean c = true && false; // Logical AND (false)(No output)
2.2 Regex & Pattern Matching
Using java.util.regex.
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String text = "Price: $100";
// Compile regex pattern with capture group
Pattern p = Pattern.compile("\\$(\\d+)");
Matcher m = p.matcher(text);
if (m.find()) {
// Group 1 contains the first captured digits
System.out.println(m.group(1));
}
}
}100
3. Argument Parsing
3.1 Argument Parsing
Standard Java does not have a built-in CLI flag parser. Manual iteration is common for simple scripts.
public class Main {
public static void main(String[] args) {
// 'args' array contains CLI parameters
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-v")) { /* Handle verbose flag */ }
else if (args[i].equals("-o") && i + 1 < args.length) {
String out = args[++i]; // Handle valued flag
}
}
}
}(No output)
4. Functions & Memory
4.1 Declaration & Returns
public class Main {
// Basic function with parameters and return type
public static int add(int a, int b) {
return a + b;
}
// Java does not support multi-returns; use a custom object or array
public static String[] getStatus() {
return new String[] {"200", "OK"};
}
}(No output)
4.2 References & Pointers
Java uses “pass-by-value,” but for objects, the value is the reference (memory address).
import java.util.ArrayList;
public class Main {
public static void modify(ArrayList<Integer> list) {
// Modifies the original list object in memory
list.add(42);
}
public static void main(String[] args) {
var list = new ArrayList<Integer>();
modify(list); // list now contains 42
}
}(No output)
5. Control Flow
5.1 Basic Loops
public class Main {
public static void main(String[] args) {
// Standard for loop
for (int i = 0; i < 3; i++) { System.out.print(i); }
int x = 0;
// While loop
while (x < 3) { x++; }
// Do-while loop (guarantees at least one execution)
do { x--; } while (x > 0);
}
}012
5.2 Breaking & Continue
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i < 2) continue; // Skip to next iteration
if (i == 5) break; // Exit the loop
System.out.print(i);
}
}
}234
5.3 Iterating Collections
Using the enhanced for-loop (for-each).
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
var list = List.of("a", "b");
for (String s : list) { System.out.print(s); }
var map = Map.of("k", "v");
// Iterating over map entries
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}ab
k:v
6. Strings & Files
6.1 String Manipulation
String s = " Hello ";
s = s.strip(); // "Hello" (removes whitespace)
String sub = s.substring(0, 2); // "He"
String joined = String.join("-", "a", "b"); // "a-b"
boolean match = s.equalsIgnoreCase("hello"); // true(No output)
6.2 Path Joining
Using the java.nio.file.Path API.
import java.nio.file.Path;
// System-agnostic path joining
Path p = Path.of("/", "usr", "bin");
String pathStr = p.toString(); // "/usr/bin" on Linux/macOS(No output)
6.3 Streaming I/O (Chunks)
import java.io.*;
public class Main {
public static void readChunks() throws IOException {
try (var in = new FileInputStream("data.bin")) {
byte[] buf = new byte[4096]; // 4KB buffer
int n;
// read() returns number of bytes read, or -1 at EOF
while ((n = in.read(buf)) != -1) {
// Process 'n' bytes from 'buf'
}
}
}
}(No output)
6.4 Read to Memory
Modern Java (11+) provides convenient one-liners for small files.
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Path p = Path.of("file.txt");
// Read entire file as a single String
String content = Files.readString(p);
}
}(No output)
7. Binary & Bitwise
7.1 Allocation & Packing
Using ByteBuffer for structured binary data
handling.
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) {
// Allocate a 12-byte buffer
ByteBuffer buf = ByteBuffer.allocate(12);
// Pack an int (4 bytes) and a double (8 bytes)
buf.putInt(42);
buf.putDouble(3.14);
byte[] raw = buf.array();
}
}(No output)
7.2 Bitwise Operations
int res = 0b1010 & 0b1100; // Bitwise AND
res = 0b1010 | 0b1100; // Bitwise OR
res = 0b1010 ^ 0b1100; // Bitwise XOR
res = ~0b1010; // Bitwise NOT (complement)
res = 0b0001 << 2; // Shift Left (0b0100)
res = 0b1000 >>> 2; // Unsigned Shift Right (0b0010)(No output)
7.3 Hex Conversion
// Convert integer to hex string
String s = Integer.toHexString(255); // "ff"
// Parse hex string to integer
int val = Integer.parseInt("ff", 16); // 255(No output)
8. Collections & JSON
8.1 Lists, Maps & Sets
Using immutable factory methods (Java 9+).
import java.util.*;
// Immutable List
List<Integer> list = List.of(1, 2, 3);
// Immutable Set
Set<String> set = Set.of("a", "b");
// Immutable Map
Map<String, Integer> map = Map.of("k", 1);
// Mutable implementations
var mutableList = new ArrayList<>(list);
mutableList.add(4);(No output)
8.2 JSON Parsing
Java has no standard JSON parser; Gson or Jackson are standard.
/* Assuming Gson library is in classpath */
import com.google.gson.Gson;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
// Parse JSON string to Map
String json = "{\"id\": 42}";
Map<?, ?> data = gson.fromJson(json, Map.class);
// Serialize object to JSON string
String output = gson.toJson(data);
}
}(No output)
9. Systems & Networking
9.1 TCP Server & Client
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
// TCP Client: connect to server
try (var s = new Socket("localhost", 8080)) {
OutputStream out = s.getOutputStream();
out.write("hello".getBytes());
}
// TCP Server: listen for connections
// try (var srv = new ServerSocket(8080)) {
// Socket client = srv.accept();
// }
}
}(No output)
9.2 UDP Server & Client
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
DatagramSocket s = new DatagramSocket();
byte[] buf = "ping".getBytes();
InetAddress addr = InetAddress.getByName("localhost");
// Send a UDP datagram packet
DatagramPacket pkt = new DatagramPacket(buf, buf.length, addr, 8080);
s.send(pkt);
s.close();
}
}(No output)
9.3 Concurrency
Using Thread and
ExecutorService.
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
// Low-level Thread
Thread t = new Thread(() -> System.out.println("Thread running"));
t.start();
t.join();
// High-level ExecutorService (ThreadPool)
ExecutorService exec = Executors.newFixedThreadPool(2);
exec.submit(() -> "Task 1");
exec.shutdown();
}
}Thread running
9.4 SQLite
Using the JDBC standard API.
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException {
// Connect to an in-memory SQLite database
String url = "jdbc:sqlite::memory:";
try (Connection conn = DriverManager.getConnection(url)) {
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE t(id INT)");
stmt.execute("INSERT INTO t VALUES(42)");
ResultSet rs = stmt.executeQuery("SELECT id FROM t");
if (rs.next()) {
System.out.println(rs.getInt("id"));
}
}
}
}42