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.

30 concepts found
Filter by category:

javac

Compilation

Compile Java source files into bytecode

Syntax:

javac [options] [source files]

Examples:

javac HelloWorld.java Compile a single Java file
javac *.java Compile all Java files in current directory
javac -cp lib/*.jar MyClass.java Compile with classpath
javac -d build src/*.java Compile and place class files in build directory

Notes:

Creates .class files containing Java bytecode

java

Execution

Execute Java applications

Syntax:

java [options] class [args]

Examples:

java HelloWorld Run a Java class
java -cp lib/*.jar MyApp Run with classpath
java -jar myapp.jar Run a JAR file
java -Xmx2g MyApp Run with 2GB max heap size

Notes:

Executes compiled Java bytecode on the JVM

jar

Packaging

Create 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 files
jar tf myapp.jar List contents of JAR file
jar xf myapp.jar Extract JAR file contents
jar cfe myapp.jar MainClass *.class Create executable JAR with main class

Notes:

JAR files are ZIP archives containing Java classes and resources

class

Basic Syntax

Declare a Java class

Syntax:

[modifiers] class ClassName [extends SuperClass] [implements Interface]

Examples:

public class MyClass { } Public class declaration
class MyClass extends ParentClass { } Class with inheritance
public class MyClass implements MyInterface { } Class implementing interface
public final class MyClass { } Final class (cannot be extended)

Notes:

Classes are blueprints for creating objects

method

Basic Syntax

Declare a Java method

Syntax:

[modifiers] returnType methodName([parameters]) [throws Exception]

Examples:

public void doSomething() { } Public void method
private int calculate(int x, int y) { return x + y; } Private method with parameters and return
public static void main(String[] args) { } Main method (program entry point)
protected String getName() throws Exception { } Method that throws exception

Notes:

Methods define behavior and can return values or be void

variables

Basic Syntax

Declare variables in Java

Syntax:

[modifiers] type variableName [= value]

Examples:

int number = 10; Integer variable with initialization
String name; String variable declaration
final double PI = 3.14159; Final (constant) variable
private static int count = 0; Static class variable

Notes:

Variables store data and must be declared with a type

primitives

Data Types

Java 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 integer
double d = 3.14159; 64-bit floating point
boolean flag = true; Boolean value (true/false)
char c = 'A'; 16-bit Unicode character

Notes:

Primitive types are stored directly in memory, not as objects

String

Data Types

String class operations and methods

Syntax:

String variableName = "text"

Examples:

String str = "Hello World"; String literal assignment
str.length() Get string length
str.substring(0, 5) Extract substring
str.toUpperCase() Convert to uppercase
str.equals("Hello World") Compare strings for equality

Notes:

Strings are immutable objects in Java

arrays

Data Types

Array declaration and manipulation

Syntax:

type[] arrayName = new type[size]

Examples:

int[] numbers = new int[5]; Create integer array of size 5
String[] names = {"Alice", "Bob", "Charlie"}; Array initialization with values
numbers[0] = 10; Assign value to array element
int length = numbers.length; Get array length

Notes:

Arrays are objects that store multiple values of the same type

if

Control Flow

Conditional execution

Syntax:

if (condition) { } else if (condition) { } else { }

Examples:

if (x > 0) { System.out.println("Positive"); } Simple if statement
if (x > 0) { } else { } If-else statement
if (x > 0) { } else if (x < 0) { } else { } If-else if-else chain
String result = (x > 0) ? "Positive" : "Non-positive"; Ternary operator

Notes:

Conditional statements control program flow based on boolean expressions

for

Control Flow

For loop iteration

Syntax:

for (initialization; condition; increment) { }

Examples:

for (int i = 0; i < 10; i++) { } Standard for loop
for (String item : collection) { } Enhanced for loop (for-each)
for (int i = 0, j = 10; i < j; i++, j--) { } Multiple variables in for loop
for (;;) { break; } Infinite loop with break

Notes:

For loops are used for controlled iteration

while

Control Flow

While loop iteration

Syntax:

while (condition) { }

Examples:

while (x < 10) { x++; } Standard while loop
do { x++; } while (x < 10); Do-while loop (executes at least once)
while (true) { if (condition) break; } Infinite loop with break condition

Notes:

While loops continue execution as long as the condition is true

switch

Control Flow

Multi-way branch statement

Syntax:

switch (expression) { case value: break; default: }

Examples:

switch (day) { case 1: System.out.println("Monday"); break; default: break; } Basic switch statement
switch (grade) { case 'A': case 'B': System.out.println("Good"); break; } Multiple cases
String 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

OOP

Class constructor definition

Syntax:

[modifiers] ClassName([parameters]) { }

Examples:

public MyClass() { } Default constructor
public MyClass(String name) { this.name = name; } Parameterized constructor
public 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

OOP

Class inheritance

Syntax:

class ChildClass extends ParentClass

Examples:

class Dog extends Animal { } Basic inheritance
@Override public void makeSound() { } Method overriding
super.methodName() Call parent method
super(parameters) Call parent constructor

Notes:

Inheritance allows classes to inherit properties and methods from parent classes

interface

OOP

Interface definition and implementation

Syntax:

interface InterfaceName { } | class ClassName implements InterfaceName

Examples:

interface Drawable { void draw(); } Interface declaration
class Circle implements Drawable { public void draw() { } } Interface implementation
interface Runnable { default void run() { } } Interface with default method
class MyClass implements Interface1, Interface2 { } Multiple interface implementation

Notes:

Interfaces define contracts that implementing classes must follow

abstract

OOP

Abstract classes and methods

Syntax:

abstract class ClassName { abstract returnType methodName(); }

Examples:

abstract class Shape { abstract double area(); } Abstract class with abstract method
abstract class Animal { void sleep() { } abstract void makeSound(); } Abstract class with concrete and abstract methods
class Circle extends Shape { double area() { return Math.PI * radius * radius; } } Concrete class extending abstract class

Notes:

Abstract classes cannot be instantiated and may contain abstract methods

try-catch

Exception Handling

Exception handling with try-catch blocks

Syntax:

try { } catch (ExceptionType e) { } finally { }

Examples:

try { int result = 10/0; } catch (ArithmeticException e) { } Basic try-catch
try { } catch (IOException | SQLException e) { } Multi-catch (Java 7+)
try { } catch (Exception e) { } finally { } Try-catch-finally
try (FileReader fr = new FileReader("file.txt")) { } Try-with-resources

Notes:

Exception handling allows graceful error recovery

throw/throws

Exception Handling

Throwing exceptions and declaring throws

Syntax:

throw new ExceptionType() | methodName() throws ExceptionType

Examples:

throw new IllegalArgumentException("Invalid input"); Throw an exception
public void readFile() throws IOException { } Declare checked exception
public void validate(int age) throws IllegalArgumentException { if (age < 0) throw new IllegalArgumentException(); } Method that throws exception

Notes:

Use throw to raise exceptions, throws to declare them in method signatures

ArrayList

Collections

Dynamic array implementation

Syntax:

ArrayList<Type> list = new ArrayList<>();

Examples:

ArrayList<String> list = new ArrayList<>(); Create ArrayList
list.add("item"); Add element
list.get(0); Get element by index
list.remove(0); Remove element by index
list.size(); Get list size

Notes:

ArrayList provides dynamic resizing and indexed access

HashMap

Collections

Key-value pair storage

Syntax:

HashMap<KeyType, ValueType> map = new HashMap<>();

Examples:

HashMap<String, Integer> map = new HashMap<>(); Create HashMap
map.put("key", 123); Add key-value pair
map.get("key"); Get value by key
map.containsKey("key"); Check if key exists
map.keySet(); Get all keys

Notes:

HashMap provides fast key-based lookup using hash tables

HashSet

Collections

Set implementation with no duplicates

Syntax:

HashSet<Type> set = new HashSet<>();

Examples:

HashSet<String> set = new HashSet<>(); Create HashSet
set.add("item"); Add element
set.contains("item"); Check if element exists
set.remove("item"); Remove element
set.size(); Get set size

Notes:

HashSet stores unique elements with fast lookup

System.out

I/O

Standard output operations

Syntax:

System.out.print() | System.out.println() | System.out.printf()

Examples:

System.out.println("Hello World"); Print line with newline
System.out.print("Hello "); Print without newline
System.out.printf("Number: %d%n", 42); Formatted output
System.out.printf("%.2f%n", 3.14159); Format decimal places

Notes:

System.out provides methods for console output

Scanner

I/O

Reading input from various sources

Syntax:

Scanner scanner = new Scanner(System.in);

Examples:

Scanner scanner = new Scanner(System.in); Create Scanner for console input
String input = scanner.nextLine(); Read entire line
int number = scanner.nextInt(); Read integer
double value = scanner.nextDouble(); Read double
scanner.close(); Close scanner

Notes:

Scanner can read from console, files, and strings

File I/O

I/O

File reading and writing operations

Syntax:

Files.readAllLines() | Files.write()

Examples:

List<String> lines = Files.readAllLines(Paths.get("file.txt")); Read all lines from file
Files.write(Paths.get("file.txt"), "content".getBytes()); Write to file
try (BufferedReader br = Files.newBufferedReader(path)) { } Buffered reading
try (PrintWriter pw = new PrintWriter("file.txt")) { pw.println("text"); } Write with PrintWriter

Notes:

Modern file I/O uses java.nio.file package for better performance

Math

Utilities

Mathematical operations and constants

Syntax:

Math.methodName()

Examples:

Math.max(5, 10) Maximum of two numbers
Math.sqrt(16) Square root
Math.random() Random number between 0.0 and 1.0
Math.PI Pi constant
Math.round(3.7) Round to nearest integer

Notes:

Math class provides static methods for mathematical operations

StringBuilder

Utilities

Efficient string manipulation

Syntax:

StringBuilder sb = new StringBuilder();

Examples:

StringBuilder sb = new StringBuilder(); Create StringBuilder
sb.append("text"); Append text
sb.insert(0, "prefix"); Insert at position
sb.delete(0, 5); Delete characters
String result = sb.toString(); Convert to String

Notes:

StringBuilder is mutable and more efficient for string concatenation

Lambda

Modern Java

Lambda expressions for functional programming

Syntax:

(parameters) -> expression | (parameters) -> { statements }

Examples:

list.forEach(item -> System.out.println(item)); Lambda with forEach
list.stream().filter(x -> x > 5).collect(Collectors.toList()); Lambda with streams
Comparator<String> comp = (a, b) -> a.compareTo(b); Lambda for Comparator
Runnable r = () -> System.out.println("Hello"); Lambda for Runnable

Notes:

Lambda expressions provide a concise way to represent functional interfaces

Streams

Modern Java

Stream API for functional-style operations

Syntax:

collection.stream().operation().collect()

Examples:

list.stream().filter(x -> x > 5).collect(Collectors.toList()); Filter and collect
list.stream().map(String::toUpperCase).forEach(System.out::println); Map and forEach
list.stream().reduce(0, Integer::sum); Reduce to sum
list.stream().sorted().distinct().limit(10).collect(Collectors.toList()); Chain multiple operations

Notes:

Streams enable functional-style operations on collections

Optional

Modern Java

Container for potentially null values

Syntax:

Optional<Type> optional = Optional.of(value);

Examples:

Optional<String> opt = Optional.of("value"); Create Optional with value
Optional<String> empty = Optional.empty(); Create empty Optional
opt.isPresent() Check if value is present
opt.orElse("default") Get value or default
opt.ifPresent(System.out::println) Execute if present

Notes:

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

TypeSizeRangeDefault
byte1 byte-128 to 1270
short2 bytes-32,768 to 32,7670
int4 bytes-2³¹ to 2³¹-10
long8 bytes-2⁶³ to 2⁶³-10L
float4 bytesIEEE 7540.0f
double8 bytesIEEE 7540.0d
boolean1 bittrue/falsefalse
char2 bytes0 to 65,535'\\u0000'

Common Operations

Type Casting:

Widening: byte → short → int → long → float → double

Narrowing: Requires explicit casting with (type)

String Conversions:

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

Encapsulation:

Bundle data and methods, control access with modifiers

Inheritance:

Child classes inherit from parent using 'extends'

Polymorphism:

Same interface, different implementations

Abstraction:

Hide implementation details, show only essential features

Key Features

Constructors:

Initialize objects, can be overloaded

Method Overriding:

Redefine parent methods in child classes

Interfaces:

Contracts that classes must implement

Abstract Classes:

Cannot be instantiated, may have abstract methods

Modern Java Features (Java 8+)

Lambda Expressions

Syntax:

(parameters) → expression

(parameters) → { statements }

Use Cases:

• Functional interfaces

• Stream operations

• Event handling

• Comparators

Stream API

Operations:

• filter() - Filter elements

• map() - Transform elements

• reduce() - Combine elements

• collect() - Gather results

Benefits:

• Functional programming style

• Parallel processing support

• Lazy evaluation

Access Modifiers & Keywords

Access Modifiers

ModifierClassPackageSubclassWorld
public
protected
default
private

Important Keywords

abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while