Java Quick Reference
Everything you need day‑to‑day – syntax, OOP, collections, and modern features.
Data Types
Primitive Types
byte– 8‑bit integershort– 16‑bit integerint– 32‑bit integerlong– 64‑bit integer (L suffix)float– 32‑bit floating point (f suffix)double– 64‑bit floating pointchar– 16‑bit Unicodeboolean– true / false
Reference Types
StringArraysClassesInterfacesEnumsCollections– List, Set, MapOptional<T>– may contain valuevar– local variable type inference (Java 10+)
Type Conversion
// Implicit (widening) int num = 10; double d = num; // int → double // Explicit (narrowing) – may lose data double d = 3.14; int num = (int) d; // 3 // String to primitive int i = Integer.parseInt("123"); double d = Double.parseDouble("3.14"); boolean b = Boolean.parseBoolean("true"); // Primitive to String String str = Integer.toString(123); String str2 = String.valueOf(3.14);
Variables
// Declaration and initialisation int age = 25; String name = "Alice"; double pi = 3.14159; boolean isActive = true; final double TAX_RATE = 0.08; // constant (cannot be reassigned) // Java 10+ var – local variable type inference var list = new ArrayList<String>(); // inferred as ArrayList<String> var number = 42; // inferred as int
Control Flow
if / else if / else
if (x > 0) { System.out.println("positive"); } else if (x == 0) { System.out.println("zero"); } else { System.out.println("negative"); }
switch (modern)
// Traditional switch switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other"); } // Switch expression (Java 14+) String result = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; default -> "Other"; };
Loops
// for for (int i = 0; i < 10; i++) { System.out.println(i); } // Enhanced for (for‑each) int[] numbers = {1, 2, 3, 4, 5}; for (int n : numbers) { System.out.println(n); } // while int i = 0; while (i < 10) { System.out.println(i++); } // do‑while int i = 0; do { System.out.println(i++); } while (i < 10); // break / continue for (int i = 0; i < 20; i++) { if (i % 2 == 0) continue; // skip even if (i > 15) break; // exit loop System.out.println(i); }
Methods
Declaration
public static int add(int a, int b) { return a + b; } // Void method public static void greet(String name) { System.out.println("Hello, " + name); } // Method overloading public static int max(int a, int b) { return (a > b) ? a : b; } public static double max(double a, double b) { return (a > b) ? a : b; } // Varargs public static int sum(int... numbers) { int total = 0; for (int n : numbers) total += n; return total; } // Recursion public static long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }
Classes & Objects
public class Person { // Fields (instance variables) private String name; private int age; // Constructor public Person(String name, int age) { this.name = name; this.age = age; } // Default constructor public Person() { this("", 0); } // Methods public void introduce() { System.out.println("I am " + name + ", " + age + " years old"); } // Getters & Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Inheritance
public class Animal { private String name; public Animal(String name) { this.name = name; } public void speak() { System.out.println(name + " makes a sound"); } } public class Dog extends Animal { private String breed; public Dog(String name, String breed) { super(name); this.breed = breed; } // Method overriding @Override public void speak() { System.out.println("Woof!"); } public String getBreed() { return breed; } }
Interfaces
// Interface definition public interface Drawable { void draw(); // Default method (Java 8+) default void print() { System.out.println("Drawing..."); } // Static method (Java 8+) static void info() { System.out.println("Drawable interface"); } } // Implementing interface public class Circle implements Drawable { private double radius; public Circle(double radius) { this.radius = radius; } @Override public void draw() { System.out.println("Drawing a circle"); } }
Exception Handling
try { int result = 10 / 0; } catch (ArithmeticException e) { System.err.println("Math error: " + e.getMessage()); } catch (Exception e) { System.err.println("Generic error: " + e.getMessage()); } finally { System.out.println("Always executes"); } // Throwing exceptions public void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } this.age = age; } // Custom exception public class MyException extends Exception { public MyException(String message) { super(message); } } // Try‑with‑resources (Java 7+) try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { String line = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
Collections Framework
List
ArrayList<T>– dynamic arrayLinkedList<T>– doubly‑linked listVector<T>– synchronised arrayStack<T>– LIFO
Set
HashSet<T>– unique, unorderedLinkedHashSet<T>– unique, insertion orderTreeSet<T>– unique, sorted
Map
HashMap<K,V>– key‑value, unorderedLinkedHashMap<K,V>– key‑value, insertion orderTreeMap<K,V>– key‑value, sortedConcurrentHashMap<K,V>– thread‑safe
Queue
PriorityQueue<T>– priority orderArrayDeque<T>– double‑ended queueLinkedList<T>– as queue
Common Collection Operations
// ArrayList ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add(1, "Mango"); String fruit = list.get(0); list.remove(1); list.size(); list.isEmpty(); // HashMap HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 95); map.put("Bob", 87); int score = map.get("Alice"); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } // HashSet HashSet<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.contains(1); // true
File I/O
// Reading text file (try‑with‑resources) try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } // Writing to text file try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { writer.write("Hello, World!"); writer.newLine(); writer.write("Second line"); } catch (IOException e) { e.printStackTrace(); } // Reading with Scanner try (Scanner scanner = new Scanner(new File("data.txt"))) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } // Files class (Java 7+) List<String> lines = Files.readAllLines(Paths.get("file.txt")); Files.write(Paths.get("output.txt"), content.getBytes());
Lambdas & Streams (Java 8+)
Lambda Expressions
// Syntax: (parameters) -> expression List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Lambda with single parameter names.forEach(name -> System.out.println(name)); // Lambda with multiple parameters Comparator<String> comp = (a, b) -> a.compareTo(b); // Functional Interfaces // Predicate<T>, Function<T,R>, Consumer<T>, Supplier<T> Predicate<Integer> isEven = x -> x % 2 == 0;
Streams
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Filter, map, collect List<Integer> squares = numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .collect(Collectors.toList()); // [4, 16, 36, 64] // Reduce int sum = numbers.stream() .reduce(0, Integer::sum); // Find first match Optional<Integer> first = numbers.stream() .filter(n -> n > 5) .findFirst(); // Optional[6] // Grouping Map<String, List<Person>> byCity = people.stream() .collect(Collectors.groupingBy(Person::getCity)); // FlatMap List<List<Integer>> listOfLists = ... List<Integer> flat = listOfLists.stream() .flatMap(List::stream) .collect(Collectors.toList());
Optional (Java 8+)
Optional<String> optional = Optional.of("Hello"); // Check if present if (optional.isPresent()) { String value = optional.get(); } // orElse / orElseGet String value = optional.orElse("Default"); String value2 = optional.orElseGet(() -> "Computed Default"); // orElseThrow String value3 = optional.orElseThrow(() -> new RuntimeException("No value")); // map / flatMap Optional<Integer> length = optional.map(String::length); // ifPresent optional.ifPresent(value -> System.out.println(value));
Common Built‑ins
String
s.length()s.toUpperCase()s.toLowerCase()s.trim()s.split(regex)s.contains(sub)s.startsWith(prefix)s.endsWith(suffix)s.replace(old, new)s.substring(start, end)s.indexOf(char)s.isEmpty()s.equals(other)String.join(delim, array)
Math
Math.abs(x)Math.ceil(x)Math.floor(x)Math.round(x)Math.max(a, b)Math.min(a, b)Math.random()Math.pow(x, y)Math.sqrt(x)Math.PIMath.E
Array Utilities (java.util.Arrays)
int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr); // sort
int index = Arrays.binarySearch(arr, 4); // binary search
String str = Arrays.toString(arr);// [1, 1, 3, 4, 5]
int[] copy = Arrays.copyOf(arr, 3); // copy first 3
boolean equal = Arrays.equals(arr1, arr2);
Enums
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } // Enum with fields and methods public enum Status { SUCCESS(200, "OK"), NOT_FOUND(404, "Not Found"), ERROR(500, "Server Error"); private int code; private String message; Status(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } Day today = Day.MONDAY; for (Day d : Day.values()) { ... }
Generics
public class Box<T> { private T content; public void set(T content) { this.content = content; } public T get() { return content; } } // Wildcards public void process(List<? extends Number> list) { ... } // unbounded public void add(List<? super Integer> list) { ... } // lower bounded
Best Practices
- Follow naming conventions:
PascalCasefor classes,camelCasefor methods/variables,UPPER_SNAKEfor constants. - Use
privatefields with getters/setters (encapsulation). - Prefer
ArrayListoverVectorunless synchronisation is needed. - Use
try‑with‑resourcesfor AutoCloseable resources (files, streams, etc.). - Use
Optionalinstead of returningnull. - Use
StringBuilderfor string concatenation in loops (orStringBufferfor thread‑safety). - Prefer
interfaceover abstract class when possible. - Use
@Overrideannotation when overriding methods. - Use
equals()andhashCode()together when overriding. - Use
List.of()andSet.of()for immutable collections (Java 9+). - Use
varfor local variables when the type is obvious (Java 10+). - Handle exceptions at the appropriate level – don't swallow them silently.
📌 Quick Reference
Check Java version:
Compile:
Run:
JAR creation:
Javadoc:
java -versionCompile:
javac Program.javaRun:
java ProgramJAR creation:
jar cvf app.jar *.classJavadoc:
javadoc -d docs *.java