Java Cheat Sheet
A comprehensive Java reference guide with syntax, examples, and usage instructions. Find the Java concepts, methods, and commands you need using the search bar or browse by category.
javac
CompilationCompile Java source files into bytecode
Syntax:
javac [options] [source files]
Examples:
javac HelloWorld.java
Compile a single Java filejavac *.java
Compile all Java files in current directoryjavac -cp lib/*.jar MyClass.java
Compile with classpathjavac -d build src/*.java
Compile and place class files in build directoryNotes:
Creates .class files containing Java bytecode
java
ExecutionExecute Java applications
Syntax:
java [options] class [args]
Examples:
java HelloWorld
Run a Java classjava -cp lib/*.jar MyApp
Run with classpathjava -jar myapp.jar
Run a JAR filejava -Xmx2g MyApp
Run with 2GB max heap sizeNotes:
Executes compiled Java bytecode on the JVM
jar
PackagingCreate and manipulate JAR archives
Syntax:
jar [options] [jar-file] [manifest-file] [entry-point] files
Examples:
jar cf myapp.jar *.class
Create JAR file from class filesjar tf myapp.jar
List contents of JAR filejar xf myapp.jar
Extract JAR file contentsjar cfe myapp.jar MainClass *.class
Create executable JAR with main classNotes:
JAR files are ZIP archives containing Java classes and resources
class
Basic SyntaxDeclare a Java class
Syntax:
[modifiers] class ClassName [extends SuperClass] [implements Interface]
Examples:
public class MyClass { }
Public class declarationclass MyClass extends ParentClass { }
Class with inheritancepublic class MyClass implements MyInterface { }
Class implementing interfacepublic final class MyClass { }
Final class (cannot be extended)Notes:
Classes are blueprints for creating objects
method
Basic SyntaxDeclare a Java method
Syntax:
[modifiers] returnType methodName([parameters]) [throws Exception]
Examples:
public void doSomething() { }
Public void methodprivate int calculate(int x, int y) { return x + y; }
Private method with parameters and returnpublic static void main(String[] args) { }
Main method (program entry point)protected String getName() throws Exception { }
Method that throws exceptionNotes:
Methods define behavior and can return values or be void
variables
Basic SyntaxDeclare variables in Java
Syntax:
[modifiers] type variableName [= value]
Examples:
int number = 10;
Integer variable with initializationString name;
String variable declarationfinal double PI = 3.14159;
Final (constant) variableprivate static int count = 0;
Static class variableNotes:
Variables store data and must be declared with a type
primitives
Data TypesJava primitive data types
Syntax:
byte, short, int, long, float, double, boolean, char
Examples:
byte b = 127;
8-bit signed integer (-128 to 127)int i = 2147483647;
32-bit signed integerdouble d = 3.14159;
64-bit floating pointboolean flag = true;
Boolean value (true/false)char c = 'A';
16-bit Unicode characterNotes:
Primitive types are stored directly in memory, not as objects
String
Data TypesString class operations and methods
Syntax:
String variableName = "text"
Examples:
String str = "Hello World";
String literal assignmentstr.length()
Get string lengthstr.substring(0, 5)
Extract substringstr.toUpperCase()
Convert to uppercasestr.equals("Hello World")
Compare strings for equalityNotes:
Strings are immutable objects in Java
arrays
Data TypesArray declaration and manipulation
Syntax:
type[] arrayName = new type[size]
Examples:
int[] numbers = new int[5];
Create integer array of size 5String[] names = {"Alice", "Bob", "Charlie"};
Array initialization with valuesnumbers[0] = 10;
Assign value to array elementint length = numbers.length;
Get array lengthNotes:
Arrays are objects that store multiple values of the same type
if
Control FlowConditional execution
Syntax:
if (condition) { } else if (condition) { } else { }
Examples:
if (x > 0) { System.out.println("Positive"); }
Simple if statementif (x > 0) { } else { }
If-else statementif (x > 0) { } else if (x < 0) { } else { }
If-else if-else chainString result = (x > 0) ? "Positive" : "Non-positive";
Ternary operatorNotes:
Conditional statements control program flow based on boolean expressions
for
Control FlowFor loop iteration
Syntax:
for (initialization; condition; increment) { }
Examples:
for (int i = 0; i < 10; i++) { }
Standard for loopfor (String item : collection) { }
Enhanced for loop (for-each)for (int i = 0, j = 10; i < j; i++, j--) { }
Multiple variables in for loopfor (;;) { break; }
Infinite loop with breakNotes:
For loops are used for controlled iteration
while
Control FlowWhile loop iteration
Syntax:
while (condition) { }
Examples:
while (x < 10) { x++; }
Standard while loopdo { x++; } while (x < 10);
Do-while loop (executes at least once)while (true) { if (condition) break; }
Infinite loop with break conditionNotes:
While loops continue execution as long as the condition is true
switch
Control FlowMulti-way branch statement
Syntax:
switch (expression) { case value: break; default: }
Examples:
switch (day) { case 1: System.out.println("Monday"); break; default: break; }
Basic switch statementswitch (grade) { case 'A': case 'B': System.out.println("Good"); break; }
Multiple casesString result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; default -> "Other"; };
Switch expression (Java 14+)Notes:
Switch statements provide an alternative to long if-else chains
constructor
OOPClass constructor definition
Syntax:
[modifiers] ClassName([parameters]) { }
Examples:
public MyClass() { }
Default constructorpublic MyClass(String name) { this.name = name; }
Parameterized constructorpublic MyClass(String name) { this(name, 0); }
Constructor chaining with this()public MyClass() { super(); }
Call parent constructor with super()Notes:
Constructors initialize objects when they are created
extends
OOPClass inheritance
Syntax:
class ChildClass extends ParentClass
Examples:
class Dog extends Animal { }
Basic inheritance@Override public void makeSound() { }
Method overridingsuper.methodName()
Call parent methodsuper(parameters)
Call parent constructorNotes:
Inheritance allows classes to inherit properties and methods from parent classes
interface
OOPInterface definition and implementation
Syntax:
interface InterfaceName { } | class ClassName implements InterfaceName
Examples:
interface Drawable { void draw(); }
Interface declarationclass Circle implements Drawable { public void draw() { } }
Interface implementationinterface Runnable { default void run() { } }
Interface with default methodclass MyClass implements Interface1, Interface2 { }
Multiple interface implementationNotes:
Interfaces define contracts that implementing classes must follow
abstract
OOPAbstract classes and methods
Syntax:
abstract class ClassName { abstract returnType methodName(); }
Examples:
abstract class Shape { abstract double area(); }
Abstract class with abstract methodabstract class Animal { void sleep() { } abstract void makeSound(); }
Abstract class with concrete and abstract methodsclass Circle extends Shape { double area() { return Math.PI * radius * radius; } }
Concrete class extending abstract classNotes:
Abstract classes cannot be instantiated and may contain abstract methods
try-catch
Exception HandlingException handling with try-catch blocks
Syntax:
try { } catch (ExceptionType e) { } finally { }
Examples:
try { int result = 10/0; } catch (ArithmeticException e) { }
Basic try-catchtry { } catch (IOException | SQLException e) { }
Multi-catch (Java 7+)try { } catch (Exception e) { } finally { }
Try-catch-finallytry (FileReader fr = new FileReader("file.txt")) { }
Try-with-resourcesNotes:
Exception handling allows graceful error recovery
throw/throws
Exception HandlingThrowing exceptions and declaring throws
Syntax:
throw new ExceptionType() | methodName() throws ExceptionType
Examples:
throw new IllegalArgumentException("Invalid input");
Throw an exceptionpublic void readFile() throws IOException { }
Declare checked exceptionpublic void validate(int age) throws IllegalArgumentException { if (age < 0) throw new IllegalArgumentException(); }
Method that throws exceptionNotes:
Use throw to raise exceptions, throws to declare them in method signatures
ArrayList
CollectionsDynamic array implementation
Syntax:
ArrayList<Type> list = new ArrayList<>();
Examples:
ArrayList<String> list = new ArrayList<>();
Create ArrayListlist.add("item");
Add elementlist.get(0);
Get element by indexlist.remove(0);
Remove element by indexlist.size();
Get list sizeNotes:
ArrayList provides dynamic resizing and indexed access
HashMap
CollectionsKey-value pair storage
Syntax:
HashMap<KeyType, ValueType> map = new HashMap<>();
Examples:
HashMap<String, Integer> map = new HashMap<>();
Create HashMapmap.put("key", 123);
Add key-value pairmap.get("key");
Get value by keymap.containsKey("key");
Check if key existsmap.keySet();
Get all keysNotes:
HashMap provides fast key-based lookup using hash tables
HashSet
CollectionsSet implementation with no duplicates
Syntax:
HashSet<Type> set = new HashSet<>();
Examples:
HashSet<String> set = new HashSet<>();
Create HashSetset.add("item");
Add elementset.contains("item");
Check if element existsset.remove("item");
Remove elementset.size();
Get set sizeNotes:
HashSet stores unique elements with fast lookup
System.out
I/OStandard output operations
Syntax:
System.out.print() | System.out.println() | System.out.printf()
Examples:
System.out.println("Hello World");
Print line with newlineSystem.out.print("Hello ");
Print without newlineSystem.out.printf("Number: %d%n", 42);
Formatted outputSystem.out.printf("%.2f%n", 3.14159);
Format decimal placesNotes:
System.out provides methods for console output
Scanner
I/OReading input from various sources
Syntax:
Scanner scanner = new Scanner(System.in);
Examples:
Scanner scanner = new Scanner(System.in);
Create Scanner for console inputString input = scanner.nextLine();
Read entire lineint number = scanner.nextInt();
Read integerdouble value = scanner.nextDouble();
Read doublescanner.close();
Close scannerNotes:
Scanner can read from console, files, and strings
File I/O
I/OFile reading and writing operations
Syntax:
Files.readAllLines() | Files.write()
Examples:
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
Read all lines from fileFiles.write(Paths.get("file.txt"), "content".getBytes());
Write to filetry (BufferedReader br = Files.newBufferedReader(path)) { }
Buffered readingtry (PrintWriter pw = new PrintWriter("file.txt")) { pw.println("text"); }
Write with PrintWriterNotes:
Modern file I/O uses java.nio.file package for better performance
Math
UtilitiesMathematical operations and constants
Syntax:
Math.methodName()
Examples:
Math.max(5, 10)
Maximum of two numbersMath.sqrt(16)
Square rootMath.random()
Random number between 0.0 and 1.0Math.PI
Pi constantMath.round(3.7)
Round to nearest integerNotes:
Math class provides static methods for mathematical operations
StringBuilder
UtilitiesEfficient string manipulation
Syntax:
StringBuilder sb = new StringBuilder();
Examples:
StringBuilder sb = new StringBuilder();
Create StringBuildersb.append("text");
Append textsb.insert(0, "prefix");
Insert at positionsb.delete(0, 5);
Delete charactersString result = sb.toString();
Convert to StringNotes:
StringBuilder is mutable and more efficient for string concatenation
Lambda
Modern JavaLambda expressions for functional programming
Syntax:
(parameters) -> expression | (parameters) -> { statements }
Examples:
list.forEach(item -> System.out.println(item));
Lambda with forEachlist.stream().filter(x -> x > 5).collect(Collectors.toList());
Lambda with streamsComparator<String> comp = (a, b) -> a.compareTo(b);
Lambda for ComparatorRunnable r = () -> System.out.println("Hello");
Lambda for RunnableNotes:
Lambda expressions provide a concise way to represent functional interfaces
Streams
Modern JavaStream API for functional-style operations
Syntax:
collection.stream().operation().collect()
Examples:
list.stream().filter(x -> x > 5).collect(Collectors.toList());
Filter and collectlist.stream().map(String::toUpperCase).forEach(System.out::println);
Map and forEachlist.stream().reduce(0, Integer::sum);
Reduce to sumlist.stream().sorted().distinct().limit(10).collect(Collectors.toList());
Chain multiple operationsNotes:
Streams enable functional-style operations on collections
Optional
Modern JavaContainer for potentially null values
Syntax:
Optional<Type> optional = Optional.of(value);
Examples:
Optional<String> opt = Optional.of("value");
Create Optional with valueOptional<String> empty = Optional.empty();
Create empty Optionalopt.isPresent()
Check if value is presentopt.orElse("default")
Get value or defaultopt.ifPresent(System.out::println)
Execute if presentNotes:
Optional helps avoid NullPointerException and makes null handling explicit
Java Programming Tips
Best Practices
- • Follow Java naming conventions (camelCase for variables and methods, PascalCase for classes)
- • Use meaningful variable and method names that describe their purpose
- • Always close resources (use try-with-resources for automatic cleanup)
- • Prefer composition over inheritance when designing classes
- • Use generics to ensure type safety and avoid ClassCastException
Performance Tips
- • Use StringBuilder for string concatenation in loops
- • Choose appropriate collection types (ArrayList vs LinkedList, HashMap vs TreeMap)
- • Use streams for functional-style operations on collections
- • Avoid creating unnecessary objects in loops
- • Use Optional to handle null values gracefully
Common Java Patterns
Design Patterns
- • Singleton: Ensure only one instance of a class exists
- • Factory: Create objects without specifying exact classes
- • Observer: Define one-to-many dependency between objects
- • Builder: Construct complex objects step by step
Coding Patterns
- • Null Object: Use Optional instead of null checks
- • Immutable Objects: Create objects that cannot be modified
- • Method Chaining: Return 'this' to enable fluent interfaces
- • Dependency Injection: Provide dependencies from external sources
Learning Java
Getting Started
- • Install JDK (Java Development Kit)
- • Set up IDE (IntelliJ IDEA, Eclipse, VS Code)
- • Learn basic syntax and OOP concepts
- • Practice with simple programs
Intermediate Topics
- • Collections Framework
- • Exception Handling
- • File I/O and Streams
- • Multithreading
Advanced Topics
- • Lambda Expressions & Streams
- • Reflection and Annotations
- • JVM Internals
- • Design Patterns
Quick Reference Guide
Data Types Reference
Primitive Data Types
Type | Size | Range | Default |
---|---|---|---|
byte | 1 byte | -128 to 127 | 0 |
short | 2 bytes | -32,768 to 32,767 | 0 |
int | 4 bytes | -2³¹ to 2³¹-1 | 0 |
long | 8 bytes | -2⁶³ to 2⁶³-1 | 0L |
float | 4 bytes | IEEE 754 | 0.0f |
double | 8 bytes | IEEE 754 | 0.0d |
boolean | 1 bit | true/false | false |
char | 2 bytes | 0 to 65,535 | '\\u0000' |
Common Operations
Widening: byte → short → int → long → float → double
Narrowing: Requires explicit casting with (type)
String.valueOf() - Convert to string
Integer.parseInt() - Parse string to int
Double.parseDouble() - Parse string to double
Collections Framework
ArrayList
- • Dynamic array implementation
- • Indexed access (get, set)
- • Allows duplicates
- • Not thread-safe
- • Good for frequent access
HashMap
- • Key-value pair storage
- • Fast lookup O(1) average
- • Allows null key/values
- • Not thread-safe
- • No ordering guarantee
HashSet
- • Unique elements only
- • Fast add/remove/contains
- • Backed by HashMap
- • Not thread-safe
- • No ordering guarantee
Object-Oriented Programming
Core Concepts
Bundle data and methods, control access with modifiers
Child classes inherit from parent using 'extends'
Same interface, different implementations
Hide implementation details, show only essential features
Key Features
Initialize objects, can be overloaded
Redefine parent methods in child classes
Contracts that classes must implement
Cannot be instantiated, may have abstract methods
Modern Java Features (Java 8+)
Lambda Expressions
(parameters) → expression
(parameters) → { statements }
• Functional interfaces
• Stream operations
• Event handling
• Comparators
Stream API
• filter() - Filter elements
• map() - Transform elements
• reduce() - Combine elements
• collect() - Gather results
• Functional programming style
• Parallel processing support
• Lazy evaluation
Access Modifiers & Keywords
Access Modifiers
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✓ | ✗ |
default | ✓ | ✓ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ |