import java.util.Scanner;Scanner sc = new Scanner(System.in);// Single integerint n = sc.nextInt();// Single stringString str = sc.next(); // single wordString line = sc.nextLine(); // entire line// Float/Doublefloat f = sc.nextFloat();double d = sc.nextDouble();// Reading array from single line (space-separated)String[] tokens = sc.nextLine().split(" ");int[] arr = new int[tokens.length];for(int i = 0; i < tokens.length; i++) { arr[i] = Integer.parseInt(tokens[i]);}// Reading array from single line (comma-separated)String[] tokens = sc.nextLine().split(",");
Output
// Basic printSystem.out.println(x); // with newlineSystem.out.print(x); // without newline// Formatted outputSystem.out.printf("%.2f", value); // 2 decimal placesSystem.out.printf("$%.2f%n", value); // with $ signSystem.out.printf("%s: %d%n", name, marks); // string and int// String formattingString.format("%.2f", value);
2. ARRAYS
Declaration and Initialization
// Fixed size arrayint[] arr = new int[5];// Array with valuesint[] arr = {1, 2, 3, 4, 5};// From inputint n = sc.nextInt();int[] arr = new int[n];for(int i = 0; i < n; i++) { arr[i] = sc.nextInt();}
Common Operations
// Lengthint len = arr.length;// Access elementsint first = arr[0];int last = arr[arr.length - 1];// Slicing (use Arrays.copyOfRange)int[] subArray = Arrays.copyOfRange(arr, start, end); // end is exclusive// Finding max/minint max = Arrays.stream(arr).max().getAsInt();int min = Arrays.stream(arr).min().min().getAsInt();// Or manually:int max = arr[0];for(int i = 1; i < arr.length; i++) { max = Math.max(max, arr[i]);}// Sumint sum = Arrays.stream(arr).sum();
3. ARRAYLIST (Dynamic Arrays)
import java.util.ArrayList;// DeclarationArrayList<Integer> list = new ArrayList<>();ArrayList<String> strList = new ArrayList<>();// Add elementslist.add(5); // appendlist.add(0, 10); // insert at index// Accessint val = list.get(i); // arr[i] in Pythonlist.set(i, newVal); // arr[i] = newVal// Sizeint size = list.size();// Removelist.remove(i); // by indexlist.remove(Integer.valueOf(5)); // by value// Check containsboolean exists = list.contains(5);// Convert to arrayInteger[] arr = list.toArray(new Integer[0]);// SublistList<Integer> sub = list.subList(start, end); // end exclusive
4. SORTING
import java.util.Arrays;import java.util.Collections;// Primitive arraysint[] arr = {3, 1, 4, 1, 5};Arrays.sort(arr); // ascending// For descending with primitives, convert to Integer[]Integer[] arr2 = {3, 1, 4, 1, 5};Arrays.sort(arr2, Collections.reverseOrder());// ArrayListArrayList<Integer> list = new ArrayList<>();Collections.sort(list); // ascendingCollections.sort(list, Collections.reverseOrder()); // descending// String arraysString[] strs = {"apple", "banana", "cherry"};Arrays.sort(strs);// Custom sorting with ComparatorArrays.sort(arr2, (a, b) -> b - a); // descending
5. HASHMAP (Frequency Counting, Key-Value Pairs)
import java.util.HashMap;import java.util.Map;// DeclarationHashMap<String, Integer> map = new HashMap<>();HashMap<Integer, Integer> freq = new HashMap<>();// Add/Updatemap.put(key, value);freq.put(num, freq.getOrDefault(num, 0) + 1); // frequency counting// Getint val = map.get(key);int val = map.getOrDefault(key, 0); // with default// Check if key existsboolean exists = map.containsKey(key);// Check if value existsboolean exists = map.containsValue(val);// Removemap.remove(key);// Sizeint size = map.size();// Iteratefor(Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue();}// Get all keysSet<String> keys = map.keySet();// Get all valuesCollection<Integer> values = map.values();// Find max value in mapint maxVal = Collections.max(map.values());// Find key with max valueString maxKey = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
6. HASHSET (Unique Elements)
import java.util.HashSet;import java.util.Set;// DeclarationHashSet<Integer> set = new HashSet<>();// Addset.add(5);// Removeset.remove(5);// Check containsboolean exists = set.contains(5);// Sizeint size = set.size();// Iteratefor(int num : set) { System.out.println(num);}// Convert array to set (remove duplicates)Integer[] arr = {1, 2, 2, 3, 4, 4, 5};Set<Integer> set = new HashSet<>(Arrays.asList(arr));// Convert set back to arrayInteger[] uniqueArr = set.toArray(new Integer[0]);
7. STRING OPERATIONS
// DeclarationString str = "Hello World";// Lengthint len = str.length();// Character at indexchar ch = str.charAt(i);// SubstringString sub = str.substring(start, end); // end exclusiveString sub = str.substring(start); // till end// SplitString[] parts = str.split(" "); // split by spaceString[] parts = str.split(","); // split by comma// JoinString joined = String.join(" ", parts);// ReplaceString newStr = str.replace("old", "new");// Character checksCharacter.isLowerCase(ch);Character.isUpperCase(ch);Character.isDigit(ch);// Case conversionchar lower = Character.toLowerCase(ch);char upper = Character.toUpperCase(ch);String lowerStr = str.toLowerCase();String upperStr = str.toUpperCase();// String to char arraychar[] chars = str.toCharArray();// Char array to stringString str = new String(chars);// String to integerint num = Integer.parseInt(str);// Integer to stringString str = String.valueOf(num);String str = Integer.toString(num);// String comparisonstr1.equals(str2); // equalitystr1.compareTo(str2); // lexicographic
8. STRINGBUILDER (For String Concatenation)
StringBuilder sb = new StringBuilder();// Appendsb.append("Hello");sb.append(" ");sb.append("World");sb.append(123);// Convert to stringString result = sb.toString();// Insertsb.insert(index, "text");// Deletesb.delete(start, end);// Reversesb.reverse();// Lengthint len = sb.length();
import java.lang.Math;// BasicMath.max(a, b);Math.min(a, b);Math.abs(x);Math.pow(base, exp); // returns doubleMath.sqrt(x);// RoundingMath.round(x); // nearest integerMath.ceil(x); // round upMath.floor(x); // round down// Integer divisionint quotient = a / b; // floor divisionint remainder = a % b; // modulo// Power (integer result)int result = (int) Math.pow(base, exp);// Cubeint cube = num * num * num;// Combinations (nCr)// Need to implement factorial or use BigInteger
11. LOOPS
For Loop
// Standard forfor(int i = 0; i < n; i++) { // code}// Range (inclusive end)for(int i = start; i <= end; i++) { // code}// Reversefor(int i = n-1; i >= 0; i--) { // code}// Enhanced for (foreach)for(int num : arr) { // code}
// Method declarationpublic static int functionName(int[] arr) { // code return result;}// Void methodpublic static void printArray(int[] arr) { // code}// Method with multiple parameterspublic static int max(int a, int b) { return (a > b) ? a : b;}// Main methodpublic static void main(String[] args) { // code}
14. TWO POINTERS TECHNIQUE
// Left and right pointersint left = 0;int right = arr.length - 1;while(left < right) { if(condition) { // do something left++; } else { right--; }}// Sliding windowint left = 0;for(int right = 0; right < arr.length; right++) { // process right while(condition) { // shrink from left left++; }}
15. DEQUE (Double-Ended Queue)
import java.util.Deque;import java.util.ArrayDeque;Deque<Integer> deque = new ArrayDeque<>();// Adddeque.addLast(x); // append (add to end)deque.addFirst(x); // add to front// Removedeque.removeLast(); // pop from enddeque.removeFirst(); // pop from front// Accessint last = deque.peekLast(); // get lastint first = deque.peekFirst(); // get first// Sizeint size = deque.size();// Check emptyboolean empty = deque.isEmpty();
16. PAIR CLASS (For Tuples)
// Using AbstractMap.SimpleEntryimport java.util.AbstractMap;import java.util.AbstractMap.SimpleEntry;SimpleEntry<Integer, String> pair = new SimpleEntry<>(90, "Alice");int key = pair.getKey();String value = pair.getValue();// Or create custom Pair classclass Pair { int first; String second; Pair(int first, String second) { this.first = first; this.second = second; }}// UsagePair p = new Pair(90, "Alice");
17. CUSTOM COMPARATORS
import java.util.Comparator;// Sort array of pairs by first element (descending)Arrays.sort(pairs, (a, b) -> b.first - a.first);// Sort by first element, then by secondArrays.sort(pairs, (a, b) -> { if(a.first != b.first) return b.first - a.first; return a.second.compareTo(b.second);});// Using Comparator.comparingArrays.sort(pairs, Comparator.comparing(p -> p.first));Arrays.sort(pairs, Comparator.comparing((Pair p) -> p.first).reversed());
18. COMMON ALGORITHMS
Kadane’s Algorithm (Max Subarray Sum)
int maxSum = arr[0];int currSum = 0;for(int i = 0; i < arr.length; i++) { currSum += arr[i]; maxSum = Math.max(maxSum, currSum); if(currSum < 0) { currSum = 0; }}
Prime Check
public static boolean isPrime(int n) { if(n <= 1) return false; if(n <= 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i += 6) { if(n % i == 0 || n % (i + 2) == 0) return false; } return true;}
Count Factors
public static int countFactors(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) count++; } return count;}
19. SPECIAL TECHNIQUES
Prefix Sum
int[] prefixSum = new int[arr.length + 1];for(int i = 0; i < arr.length; i++) { prefixSum[i + 1] = prefixSum[i] + arr[i];}// Sum from i to j: prefixSum[j+1] - prefixSum[i]
Frequency Map Pattern
HashMap<Integer, Integer> map = new HashMap<>();for(int num : arr) { map.put(num, map.getOrDefault(num, 0) + 1);}
Sliding Window Maximum
Deque<Integer> dq = new ArrayDeque<>();for(int i = 0; i < arr.length; i++) { while(!dq.isEmpty() && arr[dq.peekLast()] <= arr[i]) { dq.removeLast(); } dq.addLast(i); if(dq.peekFirst() == i - k) { dq.removeFirst(); } if(i >= k - 1) { result.add(arr[dq.peekFirst()]); }}