📖 Guide

Java — Complete Reference

Comprehensive Java cheat sheet covering data types, strings, collections, OOP, interfaces, exceptions, file I/O, streams, lambdas, and more.

203 commands across 12 categories

Basics

CommandDescription
public class Main { public static void main(String[] args) { } }
Java program entry point
System.out.println("Hello");
Print line to standard output
System.out.print("no newline");
Print without trailing newline
System.out.printf("Name: %s, Age: %d%n", name, age);
Formatted print (like C printf)
// single line comment
Single-line comment
/* multi-line comment */
Multi-line comment
/** Javadoc comment */
Documentation comment
final int MAX = 100;
Declare a constant (cannot be reassigned)
var name = "Java";
Local variable type inference (Java 10+)
Scanner sc = new Scanner(System.in);
e.g. String line = sc.nextLine(); int n = sc.nextInt();
Read user input from console
import java.util.*;
Import all classes from a package
package com.example.app;
Declare the package for the class

Data Types

CommandDescription
byte b = 127;
8-bit signed integer (-128 to 127)
short s = 32000;
16-bit signed integer
int i = 42;
32-bit signed integer
long l = 100_000L;
64-bit signed integer (suffix L)
float f = 3.14f;
32-bit floating point (suffix f)
double d = 3.14159;
64-bit floating point (default for decimals)
boolean flag = true;
Boolean (true or false)
char c = 'A';
16-bit Unicode character
Integer.parseInt("42")
Parse string to int
Double.parseDouble("3.14")
Parse string to double
String.valueOf(42)
Convert any type to String
(int) 3.7
e.g. int x = (int) 3.7; // 3
Type casting (truncates to 3)
Integer x = 5;
Autoboxing — primitive to wrapper object
int y = x;
Unboxing — wrapper object to primitive
enum Color { RED, GREEN, BLUE }
Define an enum type

Strings

CommandDescription
String s = "Hello";
String literal (immutable)
s.length()
Get string length
s.charAt(0)
Get character at index
s.substring(1, 4)
Extract substring (start inclusive, end exclusive)
s.indexOf("lo")
Find first index of substring (-1 if not found)
s.lastIndexOf("l")
Find last index of character/substring
s.contains("ell")
Check if string contains substring
s.startsWith("He")
Check if string starts with prefix
s.endsWith("lo")
Check if string ends with suffix
s.equals("Hello")
Compare strings for equality (not ==)
s.equalsIgnoreCase("hello")
Case-insensitive comparison
s.compareTo("other")
Lexicographic comparison (returns int)
s.toUpperCase()
Convert to uppercase
s.toLowerCase()
Convert to lowercase
s.trim()
Remove leading/trailing whitespace
s.strip()
Remove whitespace (Unicode-aware, Java 11+)
s.replace("old", "new")
Replace all occurrences of literal
s.replaceAll("regex", "new")
Replace all regex matches
s.split(",")
e.g. String[] parts = "a,b,c".split(",");
Split into String array
String.join(", ", list)
Join strings with delimiter
s.isEmpty()
Check if string is empty (length == 0)
s.isBlank()
Check if string is blank (empty or whitespace, Java 11+)
s.formatted("arg")
e.g. "Hello %s".formatted("World")
Format string (Java 15+)
new StringBuilder()
e.g. sb.append("a").append("b").toString()
Mutable string builder for concatenation
"""\ntext block\n"""
Text block / multi-line string (Java 15+)

Arrays & Collections

CommandDescription
int[] arr = new int[5];
Declare array with fixed size
int[] arr = {1, 2, 3, 4, 5};
Declare and initialize array
arr.length
Get array length (field, not method)
Arrays.sort(arr)
Sort array in place
Arrays.copyOf(arr, newLen)
Copy array with new length
Arrays.fill(arr, value)
Fill array with a value
Arrays.asList(arr)
Convert array to fixed-size List
List<String> list = new ArrayList<>();
Create a dynamic list
List.of("a", "b", "c")
Create immutable list (Java 9+)
list.add(item)
Add element to list
list.get(index)
Get element at index
list.set(index, value)
Replace element at index
list.remove(index)
Remove element at index
list.size()
Get number of elements
list.contains(item)
Check if list contains element
list.indexOf(item)
Find index of element
Collections.sort(list)
Sort a list
Collections.unmodifiableList(list)
Create unmodifiable view of list
Map<String, Integer> map = new HashMap<>();
Create a hash map
Map.of("a", 1, "b", 2)
Create immutable map (Java 9+)
map.put(key, value)
Insert/update key-value pair
map.get(key)
Get value by key (null if absent)
map.getOrDefault(key, defaultVal)
Get value or default
map.containsKey(key)
Check if key exists
map.keySet() / map.values() / map.entrySet()
Get keys, values, or entries
Set<String> set = new HashSet<>();
Create a hash set (unique elements)
Set.of("a", "b", "c")
Create immutable set (Java 9+)
Queue<Integer> q = new LinkedList<>();
Create a queue (FIFO)
Deque<Integer> stack = new ArrayDeque<>();
Create a stack (LIFO) / double-ended queue

Control Flow

CommandDescription
if (cond) { } else if (cond) { } else { }
If-else conditional
switch (val) { case x: break; default: }
Switch statement (classic)
switch (val) { case x -> expr; }
e.g. String s = switch(day) { case MON -> "Monday"; default -> "Other"; };
Switch expression (Java 14+)
for (int i = 0; i < n; i++) { }
Classic for loop
for (Type item : collection) { }
Enhanced for-each loop
while (cond) { }
While loop
do { } while (cond);
Do-while loop
break;
Exit loop or switch
continue;
Skip to next iteration
break label;
Break out of labeled outer loop
condition ? valTrue : valFalse
Ternary operator
if (obj instanceof String s) { }
Pattern matching instanceof (Java 16+)

Methods

CommandDescription
public int add(int a, int b) { return a + b; }
Method with return type and parameters
public void doSomething() { }
Void method (no return value)
public static int helper() { }
Static method (called on class, not instance)
public int add(int a, int... nums)
Varargs — variable number of arguments
method overloading
e.g. int add(int a, int b) / double add(double a, double b)
Same method name, different parameters
@Override
Annotation — method overrides parent method
public final void locked() { }
Final method — cannot be overridden
private
Accessible only within the class
protected
Accessible within package and subclasses
public
Accessible from anywhere
default (no modifier)
Package-private — accessible within the package
return value;
Return a value from a method

Classes & OOP

CommandDescription
class Dog { String name; Dog(String name) { this.name = name; } }
Class with constructor
Dog d = new Dog("Rex");
Create object instance
this
Reference to current object
this(args)
Call another constructor in same class
class Puppy extends Dog { }
Inheritance (extends one class)
super(args)
Call parent class constructor
super.method()
Call parent class method
@Override public String toString() { }
Override toString for custom representation
@Override public boolean equals(Object o) { }
Override equals for value comparison
@Override public int hashCode() { }
Override hashCode (required with equals)
static int count;
Static field — shared across all instances
record Point(int x, int y) { }
Record class — immutable data carrier (Java 16+)
sealed class Shape permits Circle, Square { }
Sealed class — restrict subclasses (Java 17+)
obj.getClass()
Get runtime class of object
obj instanceof Type
Check if object is instance of type

Interfaces & Abstract

CommandDescription
interface Drawable { void draw(); }
Declare an interface
class Circle implements Drawable { public void draw() { } }
Implement an interface
interface A extends B, C { }
Interface extending multiple interfaces
default void method() { }
Default method in interface (Java 8+)
static void helper() { }
Static method in interface
private void internal() { }
Private method in interface (Java 9+)
abstract class Shape { abstract double area(); }
Abstract class with abstract method
class Circle extends Shape { double area() { return Math.PI * r * r; } }
Extend abstract class and implement methods
@FunctionalInterface
Interface with exactly one abstract method (for lambdas)
Comparable<T>
e.g. class Foo implements Comparable<Foo> { public int compareTo(Foo o) { } }
Interface for natural ordering
Comparator.comparing(Foo::getName)
Create comparator from method reference

Exception Handling

CommandDescription
try { } catch (Exception e) { } finally { }
Try-catch-finally block
catch (IOException | SQLException e) { }
Multi-catch — handle multiple exception types
throw new RuntimeException("message");
Throw an unchecked exception
throw new IOException("message");
Throw a checked exception
public void read() throws IOException { }
Declare checked exception in method signature
try (var r = new FileReader("f")) { }
Try-with-resources (auto-closes)
e.getMessage()
Get the error message
e.printStackTrace()
Print the stack trace
e.getCause()
Get the cause of the exception
class MyException extends Exception { }
Custom checked exception
class MyRuntimeException extends RuntimeException { }
Custom unchecked exception
assert condition : "message";
Assert a condition (enable with -ea flag)

File I/O

CommandDescription
Path path = Path.of("file.txt");
Create a Path (Java NIO)
Files.readString(path)
Read entire file as String (Java 11+)
Files.readAllLines(path)
Read all lines into List<String>
Files.writeString(path, content)
Write string to file (Java 11+)
Files.write(path, lines)
Write list of lines to file
Files.exists(path)
Check if file/directory exists
Files.createDirectory(path)
Create a directory
Files.createDirectories(path)
Create directories including parents
Files.delete(path)
Delete a file or empty directory
Files.copy(src, dest)
Copy a file
Files.move(src, dest)
Move/rename a file
Files.list(dir)
List directory contents as Stream<Path>
Files.walk(dir)
Recursively walk directory tree as Stream<Path>
try (var br = new BufferedReader(new FileReader("f"))) { }
Buffered file reading (classic)

Streams & Lambdas

CommandDescription
(a, b) -> a + b
Lambda expression
list.forEach(item -> System.out.println(item))
ForEach with lambda
list.forEach(System.out::println)
Method reference (equivalent to above)
list.stream()
Create a stream from collection
Stream.of(1, 2, 3)
Create stream from values
.filter(x -> x > 5)
Keep elements matching predicate
.map(x -> x * 2)
Transform each element
.flatMap(list -> list.stream())
Flatten nested streams
.sorted()
Sort elements (natural order)
.sorted(Comparator.reverseOrder())
Sort in reverse order
.distinct()
Remove duplicates
.limit(10)
Take first n elements
.skip(5)
Skip first n elements
.peek(x -> log(x))
Perform action on each element without consuming
.collect(Collectors.toList())
Collect stream into a List
.collect(Collectors.toSet())
Collect into a Set
.collect(Collectors.toMap(k, v))
Collect into a Map
.collect(Collectors.joining(", "))
Join elements into a String
.collect(Collectors.groupingBy(fn))
Group elements by classifier
.reduce(0, Integer::sum)
Reduce to single value
.count()
Count elements in stream
.findFirst()
Get first element as Optional
.anyMatch(x -> x > 0)
True if any element matches
.allMatch(x -> x > 0)
True if all elements match
Optional<T> opt = Optional.of(val)
Create Optional with value
opt.orElse(defaultVal)
Get value or default
opt.ifPresent(val -> use(val))
Execute if value present
opt.map(fn).orElse(default)
Transform optional value

Common Utilities

CommandDescription
Math.max(a, b) / Math.min(a, b)
Maximum / minimum of two values
Math.abs(x)
Absolute value
Math.sqrt(x)
Square root
Math.pow(base, exp)
Power / exponentiation
Math.round(x)
Round to nearest integer
Math.floor(x) / Math.ceil(x)
Floor / ceiling
Math.random()
Random double between 0.0 and 1.0
new Random().nextInt(bound)
Random int from 0 to bound-1
LocalDate.now()
Current date
LocalTime.now()
Current time
LocalDateTime.now()
Current date and time
Instant.now()
Current timestamp (UTC)
Duration.between(start, end)
Calculate duration between two times
DateTimeFormatter.ofPattern("yyyy-MM-dd")
Date/time formatting pattern
Thread.sleep(1000)
Pause execution for milliseconds
System.currentTimeMillis()
Current time in milliseconds since epoch
Objects.equals(a, b)
Null-safe equality check
Objects.requireNonNull(obj, "msg")
Throw NPE if null

More Guides

🌿
Git Commands
Complete Git command reference — from basics to advanced workflows. Searchable, with examples.
📝
Vim Commands
Complete Vim/Vi command reference — modes, motions, editing, search, and advanced features.
🐳
Docker Commands
Complete Docker & Docker Compose command reference — containers, images, volumes, networks, and orchestration.
🔤
Regex Reference
Complete regular expression reference — syntax, patterns, quantifiers, groups, lookaheads, and common recipes.
🐧
Linux Commands
Complete Linux/Bash command reference — file management, text processing, networking, system admin, and shell scripting.
☸️
Kubernetes Commands
Complete Kubernetes & kubectl command reference — pods, deployments, services, configmaps, and cluster management.
🐍
Python Reference
Complete Python reference — syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
🗃️
SQL Reference
Complete SQL reference — queries, joins, aggregation, subqueries, indexes, and database management.
🌐
Nginx Reference
Complete Nginx configuration reference — server blocks, locations, proxying, SSL, load balancing, and caching.
🔐
SSH Commands
Complete SSH reference — connections, key management, tunneling, config, SCP/SFTP, and security hardening.
👷
Jenkins Reference
Complete Jenkins reference — pipeline syntax, Jenkinsfile, plugins, CLI, agents, and CI/CD patterns.
📨
HTTP Headers Reference
Complete HTTP headers reference — request headers, response headers, caching, security, CORS, and content negotiation. Searchable, with examples.
🐘
PostgreSQL Reference
Comprehensive PostgreSQL reference — from connection basics to advanced features like JSONB, full-text search, window functions, and performance tuning.
Async Patterns Reference
Multi-language async/concurrency patterns — JavaScript, Python, Go, Rust, Java, and universal concurrency patterns.
📡
Protobuf & gRPC Reference
Comprehensive reference for Protocol Buffers (proto3) and gRPC — message definitions, services, streaming, and common patterns.
📚
JS Array Methods
Complete JavaScript Array methods reference — creating, searching, transforming, sorting, iterating, and common patterns. Searchable, with examples.
🌊
Tailwind CSS Reference
Complete Tailwind CSS reference — layout, spacing, typography, colors, responsive design, states, and common patterns. Searchable, with examples.
GraphQL Reference
Complete GraphQL reference — schema definition, types, queries, mutations, directives, fragments, and common patterns. Searchable, with examples.
💻
VS Code Shortcuts
Complete VS Code keyboard shortcuts — editing, navigation, search, multi-cursor, terminal, debug, and more. Searchable, with Cmd/Ctrl notation.
🔲
CSS Grid Reference
Complete CSS Grid reference — container properties, item placement, grid functions, and common layout patterns. Searchable, with examples.
📦
CSS Flexbox Reference
Complete CSS Flexbox reference — container properties, item properties, and common layout patterns. Searchable, with examples.
⚛️
React Hooks Reference
Complete React Hooks reference — useState, useEffect, useContext, custom hooks, and common patterns. Searchable, with examples.
🔷
TypeScript Reference
Complete TypeScript reference — types, interfaces, generics, utility types, and advanced patterns. Searchable, with examples.
☁️
AWS CLI Reference
Complete AWS CLI reference — EC2, S3, IAM, Lambda, ECS, RDS, CloudFormation, and common operations.
🐹
Go Reference
Complete Go (Golang) reference — syntax, types, functions, concurrency, error handling, and common patterns.
💠
PowerShell Reference
Complete PowerShell reference — cmdlets, pipelines, scripting, file operations, remote management, and Active Directory.
💾
Redis Commands
Complete Redis command reference — strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and server management.
🏗️
Terraform Commands
Complete Terraform reference — init, plan, apply, state management, modules, workspaces, and HCL syntax.
⚙️
Ansible Commands
Complete Ansible reference — playbooks, modules, inventory, roles, vault, and ad-hoc commands.
🟨
JavaScript
Complete JavaScript reference — variables, types, operators, strings, arrays, objects, functions, async, DOM, ES6+, and more.
🎨
CSS
Complete CSS reference — selectors, box model, positioning, typography, animations, media queries, custom properties, and more.
📄
HTML
Complete HTML reference — document structure, text content, forms, media, semantic elements, accessibility, and more.
💻
Bash
Complete Bash reference — variables, strings, arrays, conditionals, loops, functions, file tests, I/O redirection, process management, and more.
🦀
Rust
Comprehensive Rust language cheat sheet covering ownership, traits, pattern matching, concurrency, and more.
📝
Markdown
Complete Markdown syntax reference for headings, formatting, links, tables, code blocks, and extensions.
📋
YAML
YAML syntax reference covering scalars, collections, anchors, multi-line strings, and common patterns.
🌐
Curl
Curl command-line reference for HTTP requests, authentication, file transfers, debugging, and common API patterns.
Cron
Cron scheduling reference covering syntax, field values, crontab management, and common schedule patterns.
🖥️
Tmux
Terminal multiplexer for managing multiple sessions, windows, and panes from a single terminal.
🔧
Awk
Powerful text processing language for pattern scanning, data extraction, and report generation.
✂️
Sed
Stream editor for filtering and transforming text, line by line.
🔍
Find
Search for files and directories in a directory hierarchy with powerful filtering options.
🔎
Grep
Search text using patterns. Filter lines from files, command output, or streams with regular expressions.
🐘
PHP
Complete PHP cheat sheet covering syntax, OOP, arrays, PDO, and modern PHP 8.x features.
⚙️
C
Complete C programming cheat sheet covering syntax, pointers, memory management, and standard library.
🔷
C++
Complete C++ cheat sheet covering STL containers, OOP, templates, smart pointers, and modern C++ features.
🐬
MySQL
Complete MySQL cheat sheet covering queries, joins, indexes, transactions, and administration.
💅
Sass
Complete Sass/SCSS cheat sheet covering variables, mixins, functions, nesting, and modern module system.
🔐
Chmod
Linux file permission commands and patterns for chmod.
🔢
NumPy
Essential NumPy commands for array manipulation and numerical computing in Python.
🐼
Pandas
Pandas cheat sheet for data manipulation, analysis, and transformation in Python.
🎯
Dart
Dart language cheat sheet covering syntax, types, OOP, null safety, and async patterns.
🔺
Laravel
Laravel PHP framework cheat sheet for routing, Eloquent, Blade, Artisan, and more.
🟩
Node.js
Comprehensive Node.js runtime reference covering modules, file system, HTTP, streams, and more.
Next.js
Next.js App Router reference covering routing, data fetching, server components, and deployment.
🍃
MongoDB
MongoDB reference covering CRUD operations, aggregation, indexes, and administration.
🔥
Firebase
Firebase reference covering Authentication, Firestore, Realtime Database, Cloud Functions, and Hosting.
🐳
Docker Compose
Docker Compose reference covering CLI commands, service configuration, networking, volumes, and more.
💲
jQuery
Quick reference for jQuery selectors, DOM manipulation, events, AJAX, and more.
📐
LaTeX
Quick reference for LaTeX document structure, math mode, formatting, and common packages.
🎯
XPath
Quick reference for XPath expressions, axes, predicates, and functions for XML/HTML querying.
Emmet
Quick reference for Emmet abbreviations for lightning-fast HTML and CSS coding.
📦
TOML
Quick reference for TOML configuration file syntax, types, tables, and common patterns.
💎
Prisma
Complete Prisma ORM cheat sheet — schema, queries, migrations, and CLI.
🤖
GitHub Actions
Complete GitHub Actions cheat sheet — workflows, triggers, jobs, and CI/CD patterns.
📦
npm
Complete npm cheat sheet — package management, scripts, publishing, and configuration.
Supabase
Complete Supabase cheat sheet — auth, database, realtime, storage, and edge functions.
🪶
Apache
Complete Apache HTTP Server cheat sheet — virtual hosts, modules, rewrite rules, and SSL.
📡
HTTP Status Codes
Complete reference of all standard HTTP response status codes with descriptions and use cases.
🔤
ASCII Table
Complete ASCII character reference with decimal, hexadecimal, and character values.
🔧
Chrome DevTools
Essential Chrome DevTools shortcuts, commands, and workflows for web developers.
💧
Drizzle ORM
Complete Drizzle ORM reference for schema definition, queries, relations, migrations, and common patterns.
Vercel CLI
Complete Vercel CLI reference for deployment, project management, domains, environment variables, and configuration.
🔄
PM2
Production process manager for Node.js applications with built-in load balancer, monitoring, and zero-downtime reloads.
📺
Screen
GNU Screen terminal multiplexer for persistent sessions, window management, and remote work.
📦
Webpack
Module bundler for JavaScript applications — loaders, plugins, code splitting, optimization, and dev server.
Vite
Next-generation frontend build tool with instant HMR, native ES modules, and optimized production builds via Rollup.

📖 Free, searchable command reference. Bookmark this page for quick access.