1. INPUT/OUTPUT

Reading Input

import java.util.Scanner;
 
Scanner sc = new Scanner(System.in);
 
// Single integer
int n = sc.nextInt();
 
// Single string
String str = sc.next();      // single word
String line = sc.nextLine(); // entire line
 
// Float/Double
float 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 print
System.out.println(x);        // with newline
System.out.print(x);          // without newline
 
// Formatted output
System.out.printf("%.2f", value);           // 2 decimal places
System.out.printf("$%.2f%n", value);        // with $ sign
System.out.printf("%s: %d%n", name, marks); // string and int
 
// String formatting
String.format("%.2f", value);

2. ARRAYS

Declaration and Initialization

// Fixed size array
int[] arr = new int[5];
 
// Array with values
int[] arr = {1, 2, 3, 4, 5};
 
// From input
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
    arr[i] = sc.nextInt();
}

Common Operations

// Length
int len = arr.length;
 
// Access elements
int 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/min
int 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]);
}
 
// Sum
int sum = Arrays.stream(arr).sum();

3. ARRAYLIST (Dynamic Arrays)

import java.util.ArrayList;
 
// Declaration
ArrayList<Integer> list = new ArrayList<>();
ArrayList<String> strList = new ArrayList<>();
 
// Add elements
list.add(5);                    // append
list.add(0, 10);                // insert at index
 
// Access
int val = list.get(i);          // arr[i] in Python
list.set(i, newVal);            // arr[i] = newVal
 
// Size
int size = list.size();
 
// Remove
list.remove(i);                 // by index
list.remove(Integer.valueOf(5)); // by value
 
// Check contains
boolean exists = list.contains(5);
 
// Convert to array
Integer[] arr = list.toArray(new Integer[0]);
 
// Sublist
List<Integer> sub = list.subList(start, end); // end exclusive

4. SORTING

import java.util.Arrays;
import java.util.Collections;
 
// Primitive arrays
int[] 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());
 
// ArrayList
ArrayList<Integer> list = new ArrayList<>();
Collections.sort(list);         // ascending
Collections.sort(list, Collections.reverseOrder()); // descending
 
// String arrays
String[] strs = {"apple", "banana", "cherry"};
Arrays.sort(strs);
 
// Custom sorting with Comparator
Arrays.sort(arr2, (a, b) -> b - a); // descending

5. HASHMAP (Frequency Counting, Key-Value Pairs)

import java.util.HashMap;
import java.util.Map;
 
// Declaration
HashMap<String, Integer> map = new HashMap<>();
HashMap<Integer, Integer> freq = new HashMap<>();
 
// Add/Update
map.put(key, value);
freq.put(num, freq.getOrDefault(num, 0) + 1); // frequency counting
 
// Get
int val = map.get(key);
int val = map.getOrDefault(key, 0); // with default
 
// Check if key exists
boolean exists = map.containsKey(key);
 
// Check if value exists
boolean exists = map.containsValue(val);
 
// Remove
map.remove(key);
 
// Size
int size = map.size();
 
// Iterate
for(Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
}
 
// Get all keys
Set<String> keys = map.keySet();
 
// Get all values
Collection<Integer> values = map.values();
 
// Find max value in map
int maxVal = Collections.max(map.values());
 
// Find key with max value
String maxKey = Collections.max(map.entrySet(), 
    Map.Entry.comparingByValue()).getKey();

6. HASHSET (Unique Elements)

import java.util.HashSet;
import java.util.Set;
 
// Declaration
HashSet<Integer> set = new HashSet<>();
 
// Add
set.add(5);
 
// Remove
set.remove(5);
 
// Check contains
boolean exists = set.contains(5);
 
// Size
int size = set.size();
 
// Iterate
for(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 array
Integer[] uniqueArr = set.toArray(new Integer[0]);

7. STRING OPERATIONS

// Declaration
String str = "Hello World";
 
// Length
int len = str.length();
 
// Character at index
char ch = str.charAt(i);
 
// Substring
String sub = str.substring(start, end); // end exclusive
String sub = str.substring(start);      // till end
 
// Split
String[] parts = str.split(" ");        // split by space
String[] parts = str.split(",");        // split by comma
 
// Join
String joined = String.join(" ", parts);
 
// Replace
String newStr = str.replace("old", "new");
 
// Character checks
Character.isLowerCase(ch);
Character.isUpperCase(ch);
Character.isDigit(ch);
 
// Case conversion
char lower = Character.toLowerCase(ch);
char upper = Character.toUpperCase(ch);
String lowerStr = str.toLowerCase();
String upperStr = str.toUpperCase();
 
// String to char array
char[] chars = str.toCharArray();
 
// Char array to string
String str = new String(chars);
 
// String to integer
int num = Integer.parseInt(str);
 
// Integer to string
String str = String.valueOf(num);
String str = Integer.toString(num);
 
// String comparison
str1.equals(str2);              // equality
str1.compareTo(str2);           // lexicographic

8. STRINGBUILDER (For String Concatenation)

StringBuilder sb = new StringBuilder();
 
// Append
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.append(123);
 
// Convert to string
String result = sb.toString();
 
// Insert
sb.insert(index, "text");
 
// Delete
sb.delete(start, end);
 
// Reverse
sb.reverse();
 
// Length
int len = sb.length();

9. CHARACTER/ASCII OPERATIONS

// Char to ASCII
int ascii = (int) ch;
 
// ASCII to char
char ch = (char) ascii;
 
// Character arithmetic (Caesar cipher style)
char newChar = (char)((ch - 'a' + shift) % 26 + 'a'); // lowercase
char newChar = (char)((ch - 'A' + shift) % 26 + 'A'); // uppercase
 
// Digit arithmetic
int newDigit = (Character.getNumericValue(ch) + shift) % 10;

10. MATHEMATICAL OPERATIONS

import java.lang.Math;
 
// Basic
Math.max(a, b);
Math.min(a, b);
Math.abs(x);
Math.pow(base, exp);        // returns double
Math.sqrt(x);
 
// Rounding
Math.round(x);              // nearest integer
Math.ceil(x);               // round up
Math.floor(x);              // round down
 
// Integer division
int quotient = a / b;       // floor division
int remainder = a % b;      // modulo
 
// Power (integer result)
int result = (int) Math.pow(base, exp);
 
// Cube
int cube = num * num * num;
 
// Combinations (nCr)
// Need to implement factorial or use BigInteger

11. LOOPS

For Loop

// Standard for
for(int i = 0; i < n; i++) {
    // code
}
 
// Range (inclusive end)
for(int i = start; i <= end; i++) {
    // code
}
 
// Reverse
for(int i = n-1; i >= 0; i--) {
    // code
}
 
// Enhanced for (foreach)
for(int num : arr) {
    // code
}

While Loop

while(condition) {
    // code
}

Do-While

do {
    // code
} while(condition);

12. CONDITIONAL STATEMENTS

// If-else
if(condition) {
    // code
} else if(condition) {
    // code
} else {
    // code
}
 
// Ternary operator
int result = (condition) ? valueIfTrue : valueIfFalse;
String result = (num % 9 == 0) ? "Divisible" : "Not divisible";
 
// Switch (Java 14+)
switch(value) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
}

13. FUNCTIONS/METHODS

// Method declaration
public static int functionName(int[] arr) {
    // code
    return result;
}
 
// Void method
public static void printArray(int[] arr) {
    // code
}
 
// Method with multiple parameters
public static int max(int a, int b) {
    return (a > b) ? a : b;
}
 
// Main method
public static void main(String[] args) {
    // code
}

14. TWO POINTERS TECHNIQUE

// Left and right pointers
int left = 0;
int right = arr.length - 1;
 
while(left < right) {
    if(condition) {
        // do something
        left++;
    } else {
        right--;
    }
}
 
// Sliding window
int 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<>();
 
// Add
deque.addLast(x);       // append (add to end)
deque.addFirst(x);      // add to front
 
// Remove
deque.removeLast();     // pop from end
deque.removeFirst();    // pop from front
 
// Access
int last = deque.peekLast();    // get last
int first = deque.peekFirst();  // get first
 
// Size
int size = deque.size();
 
// Check empty
boolean empty = deque.isEmpty();

16. PAIR CLASS (For Tuples)

// Using AbstractMap.SimpleEntry
import 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 class
class Pair {
    int first;
    String second;
    
    Pair(int first, String second) {
        this.first = first;
        this.second = second;
    }
}
 
// Usage
Pair 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 second
Arrays.sort(pairs, (a, b) -> {
    if(a.first != b.first) return b.first - a.first;
    return a.second.compareTo(b.second);
});
 
// Using Comparator.comparing
Arrays.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()]);
    }
}

20. COMMON IMPORTS

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.Collections;
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.Comparator;

21. COMPLETE TEMPLATE

import java.util.*;
 
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // Your code here
        
        sc.close();
    }
    
    // Helper methods here
}

KEY DIFFERENCES FROM PYTHON

  1. Array indexing: Same as Python (0-based)
  2. No negative indexing: Use arr[arr.length - 1] for last element
  3. No slicing operator: Use Arrays.copyOfRange() or subList()
  4. Explicit type declarations: Must declare types for all variables
  5. Fixed size arrays: Use ArrayList for dynamic sizing
  6. String immutability: Use StringBuilder for concatenation in loops
  7. No in operator: Use contains() method for collections
  8. No list comprehension: Use loops or streams
  9. Integer division: Automatically floors (no need for //)
  10. Modulo works with negatives: May need adjustment for negative numbers

QUICK CONVERSION GUIDE

PythonJava
len(arr)arr.length
len(list)list.size()
arr.append(x)list.add(x)
arr[i]list.get(i)
arr[-1]arr[arr.length-1]
x in arrArrays.asList(arr).contains(x)
sorted(arr)Arrays.sort(arr)
arr[::-1]Collections.reverse(list)
max(arr)Collections.max(list)
sum(arr)Loop or stream
str.split()str.split(" ")
" ".join(arr)String.join(" ", arr)
Counter(arr)HashMap with frequency counting
set(arr)new HashSet<>(Arrays.asList(arr))
dict[key]map.get(key)
f"{x}"String.format("%d", x)

TIPS FOR THE ASSESSMENT

  1. Always initialize Scanner: Scanner sc = new Scanner(System.in);
  2. Use ArrayList when size is unknown
  3. Remember to import required classes
  4. Close Scanner at end: sc.close();
  5. Use getOrDefault() for frequency counting
  6. StringBuilder for string concatenation in loops
  7. Arrays.sort() for ascending, Collections.reverseOrder() for descending
  8. Use enhanced for loop when index not needed
  9. Remember semicolons at end of statements
  10. Method names start with lowercase (camelCase)