☕ Java Programming Language

Quick Reference & Cheat Sheet - Built-in Classes, Syntax & Standard Library

Basic Syntax

Class Structure

// Package declaration package com.example.myapp; // Import statements import java.util.*; import java.io.*; // Class declaration public class MyClass { // Fields private String name; public static final int CONSTANT = 100; // Constructor public MyClass(String name) { this.name = name; } // Methods public String getName() { return name; } public void setName(String name) { this.name = name; } // Main method public static void main(String[] args) { MyClass obj = new MyClass("Java"); System.out.println(obj.getName()); } }

Data Types

// Primitive types byte b = 127; // 8-bit short s = 32767; // 16-bit int i = 2147483647; // 32-bit long l = 9223372036854775807L; // 64-bit float f = 3.14f; // 32-bit double d = 3.14159; // 64-bit char c = 'A'; // 16-bit Unicode boolean bool = true; // true/false // Reference types String str = "Hello World"; Integer intObj = 42; int[] array = {1, 2, 3, 4, 5}; List list = new ArrayList<>(); // Type casting int num = (int) 3.14; // Explicit casting double dbl = 42; // Implicit casting

Variables & Constants

// Variable declaration int number; String message = "Hello"; // Constants final int MAX_SIZE = 100; public static final String APP_NAME = "MyApp"; // Access modifiers public int publicVar; // Accessible everywhere private int privateVar; // Only within class protected int protectedVar; // Within package and subclasses int packageVar; // Within package (default) // Static variables static int staticVar = 0; // Belongs to class, not instance

Control Structures

Conditionals

// If statement if (condition) { // code } else if (anotherCondition) { // code } else { // code } // Ternary operator String result = condition ? "true" : "false"; // Switch statement switch (variable) { case 1: // code break; case 2: case 3: // code for 2 or 3 break; default: // default code } // Switch expression (Java 14+) String dayType = switch (day) { case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday"; case SATURDAY, SUNDAY -> "Weekend"; };

Loops

// For loop for (int i = 0; i < 10; i++) { System.out.println(i); } // Enhanced for loop (for-each) int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); } // While loop while (condition) { // code } // Do-while loop do { // code } while (condition); // Break and continue break; // exit loop continue; // skip to next iteration

Methods

Method Declaration

// Basic method public int add(int a, int b) { return a + b; } // Method with no return value public void printMessage(String message) { System.out.println(message); } // Static method public static double calculateArea(double radius) { return Math.PI * radius * radius; } // Method overloading public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } // Varargs method public int sum(int... numbers) { int total = 0; for (int num : numbers) { total += num; } return total; }

String Methods

String Operations

length()
charAt(index)
substring(start, end)
indexOf(str)
lastIndexOf(str)
contains(str)
startsWith(prefix)
endsWith(suffix)
toLowerCase()
toUpperCase()
trim()
replace(oldChar, newChar)
replaceAll(regex, replacement)
split(regex)
equals(str)
equalsIgnoreCase(str)
compareTo(str)
isEmpty()
isBlank()
concat(str)
valueOf(obj)

StringBuilder

// StringBuilder for efficient string manipulation StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(" "); sb.append("World"); sb.insert(5, ","); sb.delete(5, 6); sb.reverse(); String result = sb.toString(); // StringBuffer (thread-safe version) StringBuffer buffer = new StringBuffer("Initial"); buffer.append(" text"); String finalString = buffer.toString();

Collections Framework

List Interface

add(element)
add(index, element)
remove(index)
remove(object)
get(index)
set(index, element)
size()
isEmpty()
contains(object)
indexOf(object)
clear()
toArray()
// ArrayList - resizable array List arrayList = new ArrayList<>(); arrayList.add("Java"); arrayList.add("Python"); // LinkedList - doubly-linked list List linkedList = new LinkedList<>(); linkedList.addFirst("First"); linkedList.addLast("Last"); // Vector - synchronized ArrayList List vector = new Vector<>();

Set Interface

add(element)
remove(object)
contains(object)
size()
isEmpty()
clear()
iterator()
// HashSet - hash table implementation Set hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Python"); // LinkedHashSet - maintains insertion order Set linkedHashSet = new LinkedHashSet<>(); // TreeSet - sorted set Set treeSet = new TreeSet<>();

Map Interface

put(key, value)
get(key)
remove(key)
containsKey(key)
containsValue(value)
keySet()
values()
entrySet()
size()
isEmpty()
clear()
// HashMap - hash table implementation Map hashMap = new HashMap<>(); hashMap.put("Java", 25); hashMap.put("Python", 30); // LinkedHashMap - maintains insertion order Map linkedHashMap = new LinkedHashMap<>(); // TreeMap - sorted map Map treeMap = new TreeMap<>(); // Hashtable - synchronized HashMap Map hashtable = new Hashtable<>();

Object-Oriented Programming

Classes & Inheritance

// Base class public class Animal { protected String name; public Animal(String name) { this.name = name; } public void eat() { System.out.println(name + " is eating"); } // Abstract method (if class is abstract) public abstract void makeSound(); } // Derived class public class Dog extends Animal { private String breed; public Dog(String name, String breed) { super(name); // Call parent constructor this.breed = breed; } @Override public void makeSound() { System.out.println(name + " barks"); } public void wagTail() { System.out.println(name + " wags tail"); } }

Interfaces

// Interface definition public interface Drawable { // Abstract method (implicitly public abstract) void draw(); // Default method (Java 8+) default void print() { System.out.println("Printing..."); } // Static method (Java 8+) static void info() { System.out.println("Drawable interface"); } // Constants (implicitly public static final) int MAX_SIZE = 100; } // Interface implementation public class Circle implements Drawable { private double radius; public Circle(double radius) { this.radius = radius; } @Override public void draw() { System.out.println("Drawing circle with radius " + radius); } }

Abstract Classes

// Abstract class public abstract class Shape { protected String color; public Shape(String color) { this.color = color; } // Concrete method public void setColor(String color) { this.color = color; } // Abstract method public abstract double calculateArea(); public abstract void draw(); } // Concrete implementation public class Rectangle extends Shape { private double width, height; public Rectangle(String color, double width, double height) { super(color); this.width = width; this.height = height; } @Override public double calculateArea() { return width * height; } @Override public void draw() { System.out.println("Drawing " + color + " rectangle"); } }

Exception Handling

Try-Catch-Finally

// Basic exception handling try { // Code that might throw an exception int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Division by zero: " + e.getMessage()); } catch (Exception e) { System.out.println("General exception: " + e.getMessage()); } finally { System.out.println("This always executes"); } // Try-with-resources (Java 7+) try (FileReader file = new FileReader("file.txt"); BufferedReader reader = new BufferedReader(file)) { String line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } // Multiple catch (Java 7+) try { // risky code } catch (IOException | SQLException e) { e.printStackTrace(); }

Custom Exceptions

// Custom checked exception public class CustomException extends Exception { public CustomException(String message) { super(message); } public CustomException(String message, Throwable cause) { super(message, cause); } } // Custom unchecked exception public class CustomRuntimeException extends RuntimeException { public CustomRuntimeException(String message) { super(message); } } // Throwing exceptions public void validateAge(int age) throws CustomException { if (age < 0) { throw new CustomException("Age cannot be negative"); } }

Common Exceptions

NullPointerException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NumberFormatException
IOException
FileNotFoundException
SQLException
InterruptedException
ClassNotFoundException

File I/O

File Operations

// Reading from file try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } // Writing to file try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { writer.write("Hello, World!"); writer.newLine(); writer.write("Java File I/O"); } catch (IOException e) { e.printStackTrace(); } // Using Files class (Java 7+) try { List lines = Files.readAllLines(Paths.get("file.txt")); Files.write(Paths.get("output.txt"), lines); } catch (IOException e) { e.printStackTrace(); }

Generics

Generic Classes & Methods

// Generic class public class Box { private T content; public void set(T content) { this.content = content; } public T get() { return content; } } // Generic method public static void swap(T[] array, int i, int j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; } // Bounded type parameters public class NumberBox { private T number; public double getDoubleValue() { return number.doubleValue(); } } // Wildcards List numbers = new ArrayList(); List integers = new ArrayList(); List unknowns = new ArrayList();

Lambda Expressions & Streams

Lambda Expressions (Java 8+)

// Lambda syntax (parameters) -> expression (parameters) -> { statements; } // Examples Runnable r = () -> System.out.println("Hello"); Comparator comp = (s1, s2) -> s1.compareTo(s2); Function length = s -> s.length(); // Method references List names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(System.out::println); names.sort(String::compareToIgnoreCase);

Stream API (Java 8+)

List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Filter and collect List evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); // Map and reduce int sum = numbers.stream() .map(n -> n * n) .reduce(0, Integer::sum); // Find operations Optional first = numbers.stream() .filter(n -> n > 5) .findFirst(); // Grouping Map> partitioned = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0));
Wesley Classen
Wesley's AI Assistant Usually replies in ~15 min Ask me anything — if I can't answer, Wesley gets pinged and replies personally.
Hello! I'm Wesley's AI assistant. How can I help you today?