// Range checkingif (index >= 0 && index < array.length) { // safe to access}// Null checkingif (obj != null && obj.property != null) { // safe to use}// Multiple conditionsif (a > 0 && b > 0 && a + b < 100) { // all conditions must be true}
Tips
Use && and || for short-circuit evaluation
Consider using Objects.equals() for null-safe comparisons
Use switch for multiple discrete values
Control Flow Statements
Loops
// For loop - when you know iteration countfor (int i = 0; i < n; i++) { // code}// Enhanced for loop - for collections/arraysfor (int element : array) { // code}// While loop - condition-based iterationwhile (condition) { // code}// Do-while - execute at least oncedo { // code} while (condition);
Control Statements
// Break - exit loopfor (int i = 0; i < n; i++) { if (condition) break;}// Continue - skip current iterationfor (int i = 0; i < n; i++) { if (skipCondition) continue; // process}// Return - exit methodif (baseCase) return result;
Common Patterns
// Two pointersint left = 0, right = array.length - 1;while (left < right) { // process if (condition) left++; else right--;}// Sliding windowint left = 0;for (int right = 0; right < array.length; right++) { // expand window while (windowInvalid) { // shrink window left++; }}
import java.util.Date;import java.util.Calendar;import java.text.SimpleDateFormat;// Current dateDate now = new Date();// FormattingSimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");String formatted = sdf.format(now);// Using CalendarCalendar cal = Calendar.getInstance();cal.set(2024, Calendar.MARCH, 15); // Month is 0-basedDate date = cal.getTime();
Common Date/Time Problems
// Check if year is leap yearboolean isLeapYear(int year) { return Year.of(year).isLeap();}// Get number of days in monthint daysInMonth(int year, int month) { return YearMonth.of(year, month).lengthOfMonth();}// Find day of week for a dateDayOfWeek findDayOfWeek(int year, int month, int day) { return LocalDate.of(year, month, day).getDayOfWeek();}
Searching
Linear Search
// Basic linear searchint linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; // not found}
Binary Search
// Iterative binary searchint binarySearch(int[] arr, int target) { int left = 0, right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; // Prevents overflow if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; // not found}// Recursive binary searchint binarySearchRecursive(int[] arr, int target, int left, int right) { if (left > right) return -1; int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) return binarySearchRecursive(arr, target, mid + 1, right); else return binarySearchRecursive(arr, target, left, mid - 1);}
Binary Search Variations
// Find first occurrenceint findFirst(int[] arr, int target) { int left = 0, right = arr.length - 1; int result = -1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { result = mid; right = mid - 1; // Continue searching in left half } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return result;}// Find last occurrenceint findLast(int[] arr, int target) { int left = 0, right = arr.length - 1; int result = -1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { result = mid; left = mid + 1; // Continue searching in right half } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return result;}// Search in rotated sorted arrayint searchRotated(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; // Left half is sorted if (nums[left] <= nums[mid]) { if (target >= nums[left] && target < nums[mid]) { right = mid - 1; } else { left = mid + 1; } } // Right half is sorted else { if (target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1;}
Using Built-in Methods
import java.util.Arrays;import java.util.Collections;// Arrays.binarySearch (array must be sorted)int[] arr = {1, 3, 5, 7, 9};int index = Arrays.binarySearch(arr, 5); // returns 2// Collections.binarySearchList<Integer> list = Arrays.asList(1, 3, 5, 7, 9);int index2 = Collections.binarySearch(list, 5); // returns 2
Sorting
Built-in Sorting
import java.util.Arrays;import java.util.Collections;// Array sortingint[] arr = {3, 1, 4, 1, 5};Arrays.sort(arr); // [1, 1, 3, 4, 5]// Partial sortingArrays.sort(arr, 1, 4); // Sort elements from index 1 to 3// Collection sortingList<Integer> list = Arrays.asList(3, 1, 4, 1, 5);Collections.sort(list); // [1, 1, 3, 4, 5]
Custom Sorting with Comparators
// Sort by custom criteriaString[] words = {"apple", "pie", "banana"};// Sort by lengthArrays.sort(words, (a, b) -> a.length() - b.length());// orArrays.sort(words, Comparator.comparing(String::length));// Sort in reverse orderArrays.sort(arr, Collections.reverseOrder());// Multiple criteria sortingPerson[] people = {...};Arrays.sort(people, Comparator .comparing(Person::getAge) .thenComparing(Person::getName));// Custom object sortingclass Student { String name; int grade; // Constructor, getters, setters...}Student[] students = {...};// Sort by grade (descending), then by name (ascending)Arrays.sort(students, (s1, s2) -> { if (s1.grade != s2.grade) { return s2.grade - s1.grade; // descending } return s1.name.compareTo(s2.name); // ascending});
Manual Sorting Algorithms
// Bubble Sort - O(n²)void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // swap int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }}// Selection Sort - O(n²)void selectionSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { int minIdx = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIdx]) { minIdx = j; } } // swap int temp = arr[minIdx]; arr[minIdx] = arr[i]; arr[i] = temp; }}// Insertion Sort - O(n²)void insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; }}// Merge Sort - O(n log n)void mergeSort(int[] arr, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); }}void merge(int[] arr, int left, int mid, int right) { int[] temp = new int[right - left + 1]; int i = left, j = mid + 1, k = 0; while (i <= mid && j <= right) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } } while (i <= mid) temp[k++] = arr[i++]; while (j <= right) temp[k++] = arr[j++]; System.arraycopy(temp, 0, arr, left, temp.length);}// Quick Sort - Average O(n log n)void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }}int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; swap(arr, i, j); } } swap(arr, i + 1, high); return i + 1;}void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;}
Object-Oriented Programming
Classes and Objects
public class Student { // Instance variables (private for encapsulation) private String name; private int age; private double gpa; // Static variables (class-level) private static int totalStudents = 0; // Constructors public Student() { this("Unknown", 0, 0.0); } public Student(String name, int age, double gpa) { this.name = name; this.age = age; this.gpa = gpa; totalStudents++; } // Getter methods public String getName() { return name; } public int getAge() { return age; } public double getGpa() { return gpa; } // Setter methods public void setName(String name) { this.name = name; } public void setAge(int age) { if (age >= 0) this.age = age; } public void setGpa(double gpa) { if (gpa >= 0.0 && gpa <= 4.0) this.gpa = gpa; } // Instance methods public boolean isHonorStudent() { return gpa >= 3.5; } // Static methods public static int getTotalStudents() { return totalStudents; } // Override toString for string representation @Override public String toString() { return String.format("Student{name='%s', age=%d, gpa=%.2f}", name, age, gpa); } // Override equals for object comparison @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Student student = (Student) obj; return age == student.age && Double.compare(student.gpa, gpa) == 0 && Objects.equals(name, student.name); } // Override hashCode when equals is overridden @Override public int hashCode() { return Objects.hash(name, age, gpa); }}
Inheritance
// Base classpublic class Person { protected String name; protected int age; public Person(String name, int age) { this.name = name; this.age = age; } public void displayInfo() { System.out.println("Name: " + name + ", Age: " + age); }}// Derived classpublic class Employee extends Person { private double salary; private String department; public Employee(String name, int age, double salary, String department) { super(name, age); // Call parent constructor this.salary = salary; this.department = department; } @Override public void displayInfo() { super.displayInfo(); // Call parent method System.out.println("Salary: " + salary + ", Department: " + department); } // Additional methods specific to Employee public double getAnnualSalary() { return salary * 12; }}
Polymorphism and Interfaces
// Interfaceinterface Drawable { void draw(); // implicitly public abstract // Default method (Java 8+) default void print() { System.out.println("Printing..."); } // Static method (Java 8+) static void info() { System.out.println("This is Drawable interface"); }}// Abstract classabstract class Shape implements Drawable { protected String color; public Shape(String color) { this.color = color; } // Abstract method public abstract double getArea(); // Concrete method public void setColor(String color) { this.color = color; }}// Concrete implementationsclass Circle extends Shape { private double radius; public Circle(String color, double radius) { super(color); this.radius = radius; } @Override public double getArea() { return Math.PI * radius * radius; } @Override public void draw() { System.out.println("Drawing a " + color + " circle"); }}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 getArea() { return width * height; } @Override public void draw() { System.out.println("Drawing a " + color + " rectangle"); }}
import java.util.*;// ArrayList - Dynamic array, good for random accessList<Integer> arrayList = new ArrayList<>();arrayList.add(1);arrayList.add(2);arrayList.add(0, 0); // Insert at indexarrayList.get(0); // Access by indexarrayList.set(0, 10); // Update at indexarrayList.remove(0); // Remove by indexarrayList.remove(Integer.valueOf(2)); // Remove by value// LinkedList - Good for frequent insertions/deletionsList<Integer> linkedList = new LinkedList<>();linkedList.addFirst(1);linkedList.addLast(3);linkedList.add(1, 2);// Vector - Synchronized version of ArrayListList<Integer> vector = new Vector<>();// Common List operationsCollections.sort(arrayList);Collections.reverse(arrayList);Collections.shuffle(arrayList);int max = Collections.max(arrayList);int min = Collections.min(arrayList);
Set Interface
// HashSet - No duplicates, no orderingSet<String> hashSet = new HashSet<>();hashSet.add("apple");hashSet.add("banana");hashSet.add("apple"); // Won't be added again// LinkedHashSet - Maintains insertion orderSet<String> linkedHashSet = new LinkedHashSet<>();// TreeSet - Sorted orderSet<String> treeSet = new TreeSet<>();treeSet.add("zebra");treeSet.add("apple");// Contains: [apple, zebra]// Set operationsSet<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));// UnionSet<Integer> union = new HashSet<>(set1);union.addAll(set2); // {1, 2, 3, 4, 5, 6}// IntersectionSet<Integer> intersection = new HashSet<>(set1);intersection.retainAll(set2); // {3, 4}// DifferenceSet<Integer> difference = new HashSet<>(set1);difference.removeAll(set2); // {1, 2}
Map Interface
// HashMap - Key-value pairs, no orderingMap<String, Integer> hashMap = new HashMap<>();hashMap.put("apple", 5);hashMap.put("banana", 3);hashMap.put("orange", 7);// Access operationsint apples = hashMap.get("apple"); // 5int pears = hashMap.getOrDefault("pears", 0); // 0 (default value)hashMap.putIfAbsent("grape", 10); // Only adds if key doesn't exist// LinkedHashMap - Maintains insertion orderMap<String, Integer> linkedHashMap = new LinkedHashMap<>();// TreeMap - Sorted by keysMap<String, Integer> treeMap = new TreeMap<>();// Common Map operationshashMap.containsKey("apple"); // truehashMap.containsValue(5); // truehashMap.keySet(); // Set of all keyshashMap.values(); // Collection of all valueshashMap.entrySet(); // Set of key-value pairs// Iterating over mapfor (Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue());}// Using forEach (Java 8+)hashMap.forEach((key, value) -> System.out.println(key + ": " + value));
Queue Interface
// LinkedList as QueueQueue<Integer> queue = new LinkedList<>();queue.offer(1); // Add to rearqueue.offer(2);queue.offer(3);int front = queue.poll(); // Remove from front, returns 1int peek = queue.peek(); // Look at front without removing, returns 2// PriorityQueue - Min heap by defaultPriorityQueue<Integer> minHeap = new PriorityQueue<>();minHeap.offer(5);minHeap.offer(2);minHeap.offer(8);int min = minHeap.poll(); // Returns 2// Max heapPriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());maxHeap.offer(5);maxHeap.offer(2);maxHeap.offer(8);int max = maxHeap.poll(); // Returns 8// Custom comparator for PriorityQueuePriorityQueue<String> pq = new PriorityQueue<>((a, b) -> a.length() - b.length());
Stack
// Using Stack class (legacy, prefer Deque)Stack<Integer> stack = new Stack<>();stack.push(1);stack.push(2);stack.push(3);int top = stack.pop(); // Returns 3int peek = stack.peek(); // Returns 2 (top element)// Using Deque as Stack (recommended)Deque<Integer> stack2 = new ArrayDeque<>();stack2.push(1);stack2.push(2);int top2 = stack2.pop();
Deque (Double-ended Queue)
Deque<Integer> deque = new ArrayDeque<>();// Add elementsdeque.addFirst(1); // Add to frontdeque.addLast(2); // Add to reardeque.offerFirst(0); // Alternative to addFirstdeque.offerLast(3); // Alternative to addLast// Remove elementsint first = deque.removeFirst(); // Remove from frontint last = deque.removeLast(); // Remove from rearint polledFirst = deque.pollFirst(); // Returns null if emptyint polledLast = deque.pollLast(); // Returns null if empty// Peek elementsint peekFirst = deque.peekFirst();int peekLast = deque.peekLast();
Common Collection Utility Methods
import java.util.Collections;List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5));// Sorting and searchingCollections.sort(list);Collections.reverse(list);Collections.shuffle(list);int index = Collections.binarySearch(list, 4);// Min/Maxint min = Collections.min(list);int max = Collections.max(list);// Frequencyint freq = Collections.frequency(list, 1); // Count occurrences// Fill and copyCollections.fill(list, 0); // Fill with 0List<Integer> copy = new ArrayList<>(Collections.nCopies(5, 10)); // [10,10,10,10,10]// SynchronizationList<Integer> syncList = Collections.synchronizedList(new ArrayList<>());Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());// Unmodifiable collectionsList<Integer> readOnlyList = Collections.unmodifiableList(list);
Common Collection Problem Patterns
// Group AnagramsMap<String, List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> groups = new HashMap<>(); for (String str : strs) { char[] chars = str.toCharArray(); Arrays.sort(chars); String key = new String(chars); groups.computeIfAbsent(key, k -> new ArrayList<>()).add(str); } return groups;}// Top K Frequent ElementsList<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> count = new HashMap<>(); for (int num : nums) { count.put(num, count.getOrDefault(num, 0) + 1); } PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>( (a, b) -> b.getValue() - a.getValue() ); pq.addAll(count.entrySet()); List<Integer> result = new ArrayList<>(); for (int i = 0; i < k; i++) { result.add(pq.poll().getKey()); } return result;}// Valid Parenthesesboolean isValid(String s) { Stack<Character> stack = new Stack<>(); Map<Character, Character> mapping = new HashMap<>(); mapping.put(')', '('); mapping.put('}', '{'); mapping.put(']', '['); for (char c : s.toCharArray()) { if (mapping.containsKey(c)) { if (stack.isEmpty() || stack.pop() != mapping.get(c)) { return false; } } else { stack.push(c); } } return stack.isEmpty();}
Functional Programming
Lambda Expressions
// Basic lambda syntax: (parameters) -> expression/statement blockRunnable r = () -> System.out.println("Hello World");// Single parameter (parentheses optional)Function<String, Integer> length = s -> s.length();Function<String, Integer> length2 = (s) -> s.length();// Multiple parametersBinaryOperator<Integer> add = (a, b) -> a + b;// Block bodyPredicate<String> startsWithA = s -> { return s.startsWith("A");};// Method referencesList<String> words = Arrays.asList("apple", "banana", "cherry");words.forEach(System.out::println); // Method referencewords.sort(String::compareToIgnoreCase); // Method reference
Functional Interfaces
import java.util.function.*;// Predicate<T> - takes T, returns booleanPredicate<String> isEmpty = String::isEmpty;Predicate<Integer> isEven = n -> n % 2 == 0;// Function<T, R> - takes T, returns RFunction<String, Integer> strLength = String::length;Function<Integer, String> intToStr = Object::toString;// Consumer<T> - takes T, returns nothingConsumer<String> print = System.out::println;// Supplier<T> - takes nothing, returns TSupplier<String> hello = () -> "Hello World";// BinaryOperator<T> - takes two T, returns TBinaryOperator<Integer> multiply = (a, b) -> a * b;// UnaryOperator<T> - takes T, returns TUnaryOperator<String> toUpper = String::toUpperCase;// BiPredicate<T, U> - takes T and U, returns booleanBiPredicate<String, String> equals = String::equals;// Custom functional interface@FunctionalInterfaceinterface MathOperation { int operate(int a, int b);}MathOperation addition = (a, b) -> a + b;MathOperation subtraction = (a, b) -> a - b;
// Automatic resource managementtry (FileInputStream file = new FileInputStream("data.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(file))) { String line = reader.readLine(); // process line} catch (IOException e) { System.out.println("File error: " + e.getMessage());}// Resources are automatically closed// Multiple resourcestry (Scanner scanner = new Scanner(System.in); PrintWriter writer = new PrintWriter("output.txt")) { String input = scanner.nextLine(); writer.println(input);} catch (IOException e) { e.printStackTrace();}
Custom Exceptions
// Custom checked exceptionclass InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } public InvalidAgeException(String message, Throwable cause) { super(message, cause); }}// Custom unchecked exceptionclass InsufficientFundsException extends RuntimeException { private double deficit; public InsufficientFundsException(double deficit) { super("Insufficient funds. Deficit: " + deficit); this.deficit = deficit; } public double getDeficit() { return deficit; }}// Using custom exceptionspublic class BankAccount { private double balance; public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount - balance); } balance -= amount; } public void setAge(int age) throws InvalidAgeException { if (age < 0 || age > 150) { throw new InvalidAgeException("Age must be between 0 and 150: " + age); } // set age }}
Exception Hierarchy and Common Exceptions
// Checked exceptions (must be handled)try { Thread.sleep(1000); // InterruptedException Class.forName("NonExistentClass"); // ClassNotFoundException new FileInputStream("missing.txt"); // FileNotFoundException} catch (InterruptedException | ClassNotFoundException | FileNotFoundException e) { e.printStackTrace();}// Unchecked exceptions (RuntimeException subclasses)// NullPointerExceptionString str = null;// int len = str.length(); // NPE// ArrayIndexOutOfBoundsExceptionint[] arr = {1, 2, 3};// int value = arr[5]; // AIOOBE// NumberFormatException// int num = Integer.parseInt("abc"); // NFE// IllegalArgumentException// Thread.sleep(-1000); // IAE
Best Practices and Patterns
// Don't catch and ignoretry { riskyOperation();} catch (Exception e) { // BAD: Swallowing exception}// Better: Log and handle appropriatelytry { riskyOperation();} catch (SpecificException e) { logger.error("Operation failed", e); return defaultValue();}// Rethrowing with contextpublic void processFile(String filename) throws ProcessingException { try { // file processing } catch (IOException e) { throw new ProcessingException("Failed to process file: " + filename, e); }}// Validation patternpublic void setScore(int score) { if (score < 0 || score > 100) { throw new IllegalArgumentException("Score must be between 0 and 100: " + score); } this.score = score;}// Optional pattern for methods that might failpublic Optional<String> readFirstLine(String filename) { try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) { return Optional.ofNullable(reader.readLine()); } catch (IOException e) { logger.warn("Could not read file: " + filename, e); return Optional.empty(); }}// Exception handling in streamsList<String> validNumbers = Arrays.asList("1", "2", "abc", "4", "xyz") .stream() .map(this::parseIntSafely) .filter(Optional::isPresent) .map(Optional::get) .map(String::valueOf) .collect(Collectors.toList());private Optional<Integer> parseIntSafely(String str) { try { return Optional.of(Integer.parseInt(str)); } catch (NumberFormatException e) { return Optional.empty(); }}
Quick Reference & Tips
Array and Collection Quick Operations
// Reverse array in-placevoid reverseArray(int[] arr) { int left = 0, right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; }}// Reverse listCollections.reverse(list);// Convert array to listList<Integer> list = Arrays.asList(1, 2, 3, 4, 5);// Note: This creates a fixed-size list// Convert list to arrayInteger[] array = list.toArray(new Integer[0]);// Convert between primitive and wrapper arraysint[] primitives = {1, 2, 3, 4, 5};Integer[] wrappers = Arrays.stream(primitives).boxed().toArray(Integer[]::new);int[] backToPrimitives = Arrays.stream(wrappers).mapToInt(Integer::intValue).toArray();
Sorting Shortcuts
// Sort array in descending orderInteger[] arr = {3, 1, 4, 1, 5};Arrays.sort(arr, Collections.reverseOrder());// Sort by multiple criteriaPerson[] people = {...};Arrays.sort(people, Comparator.comparing(Person::getAge) .thenComparing(Person::getName));// Custom sort for primitives (convert to Integer first)int[] primitives = {3, 1, 4, 1, 5};Integer[] wrappers = Arrays.stream(primitives).boxed().toArray(Integer[]::new);Arrays.sort(wrappers, Collections.reverseOrder());// Sort part of arrayArrays.sort(arr, 1, 4); // Sort elements from index 1 to 3
Mathematical Utilities
// Math class essentialsMath.abs(-5); // 5Math.max(3, 7); // 7Math.min(3, 7); // 3Math.pow(2, 3); // 8.0Math.sqrt(16); // 4.0Math.ceil(3.2); // 4.0Math.floor(3.8); // 3.0Math.round(3.6); // 4// Random numbersRandom rand = new Random();int randomInt = rand.nextInt(10); // 0-9double randomDouble = rand.nextDouble(); // 0.0-1.0
String Processing Shortcuts
// Check if string is numericboolean isNumeric(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; }}// Count character occurrenceslong count = str.chars().filter(ch -> ch == 'a').count();// Remove all non-alphanumeric charactersString cleaned = str.replaceAll("[^a-zA-Z0-9]", "");// Check if two strings are anagramsboolean areAnagrams(String s1, String s2) { char[] arr1 = s1.toLowerCase().toCharArray(); char[] arr2 = s2.toLowerCase().toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); return Arrays.equals(arr1, arr2);}
Common Coding Patterns
// Sliding window maximumint[] maxSlidingWindow(int[] nums, int k) { Deque<Integer> deque = new ArrayDeque<>(); List<Integer> result = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { // Remove elements outside window while (!deque.isEmpty() && deque.peekFirst() < i - k + 1) { deque.pollFirst(); } // Remove smaller elements while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { deque.pollLast(); } deque.offerLast(i); if (i >= k - 1) { result.add(nums[deque.peekFirst()]); } } return result.stream().mapToInt(i -> i).toArray();}// Find intersection of two arraysint[] intersect(int[] nums1, int[] nums2) { Map<Integer, Integer> count = new HashMap<>(); for (int num : nums1) { count.put(num, count.getOrDefault(num, 0) + 1); } List<Integer> result = new ArrayList<>(); for (int num : nums2) { if (count.getOrDefault(num, 0) > 0) { result.add(num); count.put(num, count.get(num) - 1); } } return result.stream().mapToInt(i -> i).toArray();}// Check if array is sortedboolean isSorted(int[] arr) { for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[i-1]) { return false; } } return true;}
Input/Output Shortcuts
// Fast input readingScanner sc = new Scanner(System.in);int n = sc.nextInt();String line = sc.nextLine();String[] parts = line.split(" ");// StringBuilder for outputStringBuilder sb = new StringBuilder();for (int i = 0; i < n; i++) { sb.append(i).append(" ");}System.out.println(sb.toString());