learn2code
Quick Reference

Java Cheatsheet

A comprehensive reference for Java syntax, object-oriented programming, collections, and modern features. From variables to streams and lambdas.

1Variables & Data Types

Java is statically typed. Every variable must have a declared type. Java has 8 primitive types and reference types (objects).

Variables.java
// Primitive types
int age = 25;
double price = 19.99;
float temp = 36.6f;
long population = 8000000000L;
boolean isActive = true;
char grade = 'A';
byte small = 127;
short medium = 32000;

// Reference types (objects)
String name = "Alice";
Integer boxedInt = 42;  // Wrapper class

// Constants
final double PI = 3.14159;
final String APP_NAME = "Learn2Code";

// Type casting
double d = 9.7;
int i = (int) d;      // 9 (explicit cast)
double d2 = i;         // 9.0 (implicit cast)

// var keyword (Java 10+)
var message = "Hello"; // Inferred as String
var nums = List.of(1, 2, 3); // Inferred type
Practice variables

2Strings

Strings in Java are immutable objects. The String class provides many built-in methods for text manipulation.

Strings.java
String str = "Hello World";

// Common methods
str.length()                    // 11
str.toUpperCase()               // "HELLO WORLD"
str.toLowerCase()               // "hello world"
str.trim()                      // Remove whitespace
str.substring(0, 5)             // "Hello"
str.charAt(0)                   // 'H'
str.indexOf("World")            // 6
str.contains("World")           // true
str.startsWith("Hello")         // true
str.replace("World", "Java")    // "Hello Java"
str.split(" ")                  // ["Hello", "World"]

// String comparison (NEVER use ==)
str.equals("Hello World")       // true
str.equalsIgnoreCase("hello world") // true

// String formatting
String.format("Hi %s, age %d", "Alice", 30);

// StringBuilder (mutable, for concatenation)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String result = sb.toString();
Practice strings

3Arrays

Arrays in Java are fixed-size, typed containers. For dynamic sizing, use ArrayList from the Collections framework.

Arrays.java
// Declaration and initialization
int[] nums = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Alice";

// Access and length
int first = nums[0];       // 1
int len = nums.length;     // 5

// Iterate
for (int n : nums) {
    System.out.println(n);
}

// java.util.Arrays utilities
import java.util.Arrays;

Arrays.sort(nums);                    // Sort in place
Arrays.toString(nums);                // "[1, 2, 3, 4, 5]"
Arrays.copyOf(nums, 3);              // [1, 2, 3]
Arrays.fill(nums, 0);                // All zeros
int idx = Arrays.binarySearch(nums, 3); // Find index

// 2D arrays
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};
int val = matrix[1][2]; // 6
Practice arrays

4Conditionals

Control flow with if/else, switch statements, and the ternary operator.

Conditionals.java
// If/else
int score = 85;

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}

// Ternary operator
String result = score >= 60 ? "Pass" : "Fail";

// Switch statement
String day = "Monday";

switch (day) {
    case "Monday":
        System.out.println("Start of week");
        break;
    case "Friday":
        System.out.println("Almost weekend");
        break;
    default:
        System.out.println("Regular day");
}

// Switch expressions (Java 14+)
String type = switch (day) {
    case "Saturday", "Sunday" -> "Weekend";
    default -> "Weekday";
};
Practice conditionals

5Loops

Java provides for, while, do-while, and enhanced for-each loops for iteration.

Loops.java
// For loop
for (int i = 0; i < 5; i++) {
    System.out.println(i); // 0, 1, 2, 3, 4
}

// Enhanced for-each
String[] fruits = {"apple", "banana", "orange"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

// While loop
int count = 0;
while (count < 3) {
    System.out.println(count);
    count++;
}

// Do-while (executes at least once)
do {
    System.out.println("Runs once");
} while (false);

// Loop control
for (int i = 0; i < 10; i++) {
    if (i == 3) continue;  // Skip 3
    if (i == 7) break;     // Stop at 7
    System.out.println(i);
}
Practice loops

6Methods

Methods are functions defined inside a class. Java supports overloading, varargs, and static methods.

Methods.java
// Basic method
public static int add(int a, int b) {
    return a + b;
}

// Method with no return value
public static void greet(String name) {
    System.out.println("Hello, " + name);
}

// Default parameters (via overloading)
public static String greet(String name, String prefix) {
    return prefix + " " + name;
}
public static String greet(String name) {
    return greet(name, "Hello");
}

// Varargs (variable number of arguments)
public static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}
sum(1, 2, 3, 4); // 10

// Static vs instance methods
class Calculator {
    static int add(int a, int b) { return a + b; }
    int multiply(int a, int b) { return a * b; }
}
Practice methods

7Classes & OOP

Java is an object-oriented language. Classes, inheritance, interfaces, and encapsulation are fundamental to every Java program.

OOP.java
// Class definition
public class Person {
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter and Setter
    public String getName() { return name; }
    public void setAge(int age) { this.age = age; }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

// Inheritance
public class Student extends Person {
    private String major;

    public Student(String name, int age, String major) {
        super(name, age);
        this.major = major;
    }
}

// Interface
public interface Drawable {
    void draw();
    default void erase() { /* default impl */ }
}

// Abstract class
public abstract class Shape {
    abstract double area();
}
Practice OOP

8Collections

The Java Collections Framework provides List, Set, Map, and Queue implementations for managing groups of objects.

Collections.java
import java.util.*;

// ArrayList (dynamic array)
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.get(0);           // "Alice"
names.size();           // 2
names.remove("Bob");
names.contains("Alice"); // true

// HashMap (key-value pairs)
Map<String, Integer> scores = new HashMap<>();
scores.put("math", 95);
scores.put("english", 88);
scores.get("math");           // 95
scores.getOrDefault("art", 0); // 0
scores.containsKey("math");   // true
scores.keySet();              // Set of keys
scores.values();              // Collection of values

// HashSet (unique elements)
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("java");  // Duplicate ignored
tags.size();       // 1

// Immutable collections (Java 9+)
List<String> list = List.of("a", "b", "c");
Map<String, Integer> map = Map.of("x", 1, "y", 2);
Practice collections

9Exceptions

Java uses try-catch-finally for error handling. Exceptions are either checked (must handle) or unchecked (runtime).

Exceptions.java
// Try-catch-finally
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
    System.out.println("General error");
} finally {
    System.out.println("Always runs");
}

// Throwing exceptions
public static int divide(int a, int b) {
    if (b == 0) {
        throw new IllegalArgumentException("Cannot divide by zero");
    }
    return a / b;
}

// Custom exception
public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

// Try-with-resources (auto-closeable)
try (BufferedReader reader = new BufferedReader(
        new FileReader("file.txt"))) {
    String line = reader.readLine();
}
Practice exceptions

10Streams & Lambdas

Java 8+ introduced lambdas and the Stream API for functional-style operations on collections.

Streams.java
import java.util.List;
import java.util.stream.Collectors;

List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8);

// Lambda syntax
Runnable task = () -> System.out.println("Hello");
Comparator<String> cmp = (a, b) -> a.compareTo(b);

// Stream operations
List<Integer> evens = nums.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
// [2, 4, 6, 8]

List<Integer> doubled = nums.stream()
    .map(n -> n * 2)
    .collect(Collectors.toList());
// [2, 4, 6, 8, 10, 12, 14, 16]

int sum = nums.stream()
    .reduce(0, Integer::sum); // 36

// Chaining operations
nums.stream()
    .filter(n -> n > 3)
    .map(n -> n * n)
    .sorted()
    .forEach(System.out::println);

// Optional (avoid null)
Optional<String> name = Optional.ofNullable(getName());
String result = name.orElse("Unknown");
Practice streams

Ready to practice Java?

Master Java syntax through interactive fill-in-the-blank exercises. Build enterprise-grade muscle memory today.

Start Practicing Java