Java Cheat Sheet
Complete reference guide for Java with interactive examples and live playground links
Click on any section to jump directly to it
Basic Syntax
Hello World
The classic first program: outputting text to the console.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Variables and Data Types
Variable declaration and basic data types in Java
// Primitive types
int age = 30;
double height = 5.9;
boolean isActive = true;
char grade = 'A';
// Reference types
String name = "Java";
Integer count = 42;
Double price = 19.99;
Boolean isValid = true;
// Type conversion
int num = 42;
double decimal = (double) num; // Explicit casting
int backToInt = (int) decimal; // Explicit casting
String Operations
Common string operations and formatting techniques
String text = "Hello World";
// String methods
System.out.println(text.toUpperCase()); // HELLO WORLD
System.out.println(text.toLowerCase()); // hello world
System.out.println(text.replace("World", "Java")); // Hello Java
System.out.println(text.split(" ")); // [Hello, World]
System.out.println(text.length()); // 11
// String formatting
String name = "Alice";
int age = 25;
System.out.printf("My name is %s and I'm %d years old%n", name, age);
System.out.println(String.format("My name is %s and I'm %d years old", name, age));
Arrays and Collections
Working with arrays and collections
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] fruits = new String[3];
fruits[0] = "apple";
fruits[1] = "banana";
fruits[2] = "cherry";
// ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.remove("banana");
list.set(0, "orange");
// HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
map.remove("banana");
int value = map.get("apple");
Input/Output
Basic input and output operations
// Console output
System.out.println("Hello World");
System.out.printf("Name: %s, Age: %d%n", name, age);
System.out.print("No new line");
// Console input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.close();
Comments
Different ways to add comments and documentation
// Single line comment
/*
* Multi-line comment
* This is a block comment
*/
/**
* Javadoc comment
* Used for documentation
* @param name the name parameter
* @return the greeting string
*/
public String greet(String name) {
return "Hello, " + name;
}
Control Flow
Conditional Statements
Conditional logic and decision making
// If-else
int age = 18;
if (age >= 18) {
System.out.println("Adult");
} else if (age >= 13) {
System.out.println("Teenager");
} else {
System.out.println("Child");
}
// Ternary operator
String status = (age >= 18) ? "Adult" : "Minor";
// Switch statement
switch (age) {
case 18:
System.out.println("Just became adult");
break;
case 13:
System.out.println("Just became teenager");
break;
default:
System.out.println("Other age");
}
Loops
Different types of loops and iterations
// For loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Enhanced for loop
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// While loop
int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}
// Do-while loop
int num = 0;
do {
System.out.println(num);
num++;
} while (num < 5);
Exception Handling
Error handling with try-catch blocks and custom exceptions
try {
// Risky code
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("This always executes");
}
// Custom exception
class ValidationException extends Exception {
public ValidationException(String message) {
super(message);
}
}
// Throwing exceptions
public void validate(int age) throws ValidationException {
if (age < 0) {
throw new ValidationException("Age cannot be negative");
}
}
Object-Oriented Programming
Classes and Objects
Class definition, constructors, and methods
public class Person {
// Fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Methods
public void introduce() {
System.out.printf("Hi, I'm %s and I'm %d years old%n", name, age);
}
}
// Usage
Person person = new Person("Alice", 25);
person.introduce();
Inheritance and Interfaces
Inheritance, abstract classes, and interfaces
// Abstract class
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
}
// Interface
interface Movable {
void move();
void stop();
}
// Class implementing interface and extending abstract class
class Dog extends Animal implements Movable {
public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Woof!");
}
@Override
public void move() {
System.out.println("Dog is running");
}
@Override
public void stop() {
System.out.println("Dog stopped");
}
}
Collections Framework
Lists and Sets
Working with Lists and Sets
// ArrayList
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.remove("banana");
String first = list.get(0);
// LinkedList
List<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
// HashSet
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("cherry");
set.add("apple"); // Duplicate, won't be added
// TreeSet
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(3);
treeSet.add(1);
treeSet.add(2);
// Will be stored in order: 1, 2, 3
Maps
Map implementations and operations
// HashMap
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
// Accessing values
int value = map.get("apple");
boolean exists = map.containsKey("banana");
map.remove("cherry");
// TreeMap
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("cherry", 3);
treeMap.put("apple", 1);
treeMap.put("banana", 2);
// Keys will be stored in order: apple, banana, cherry
// Iterating
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.printf("%s: %d%n", entry.getKey(), entry.getValue());
}
Streams and Lambdas
Stream Operations
Working with Java Streams API
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter and map
List<Integer> evenSquares = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
// Reduce
int sum = numbers.stream()
.reduce(0, Integer::sum);
// Grouping
Map<String, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(p -> p.getAge() >= 18 ? "Adult" : "Minor"));
// Parallel stream
int sum = numbers.parallelStream()
.mapToInt(Integer::intValue)
.sum();
Lambda Expressions
Lambda expressions and functional programming
// Functional interfaces
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
// Lambda expressions
Calculator add = (a, b) -> a + b;
Calculator subtract = (a, b) -> a - b;
Calculator multiply = (a, b) -> a * b;
// Method references
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);
// Comparator
List<Person> people = new ArrayList<>();
people.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));
// or
people.sort(Comparator.comparing(Person::getName));
Java - Interactive Developer Reference
Hover over code blocks to copy or run in live playground