Practical reference of Java basics, conversions, math, strings, arrays, collections, I/O and common patterns
for algorithm / competitive programming / coding interviews.
import java.util.*; // List, ArrayList, Map, HashMap, Set, HashSet, Queue, Stack, Collections, Arrays, etc.
import java.io.*; // BufferedReader, InputStreamReader, PrintWriter, etc.
// java.lang.* (String, Math, Integer, etc.) is imported automaticallyint i = 10;
long l = 10_000_000_000L;
double d = 3.14;
float f = 3.14f;
char c = 'A';
boolean b = true;Wrapper classes (useful for generics & utilities):
Integer I;
Long L;
Double D;
Character C;
Boolean B;// int → String
String s1 = Integer.toString(123);
String s2 = String.valueOf(123);
// long → String
String s3 = Long.toString(123L);
// String → int / long / double
int n = Integer.parseInt("123");
long lng = Long.parseLong("123456789");
double d = Double.parseDouble("3.14");// char → int (ASCII / Unicode code)
int code = 'A'; // 65
// int → char
char ch = (char) 65; // 'A'// String → char[]
char[] chars = "hello".toCharArray();
// char[] → String
String s = new String(chars);// Decimal → Binary String
String binStr = Integer.toBinaryString(10); // "1010"
// Binary String → Decimal
int num = Integer.parseInt("1010", 2); // 10int mx = Math.max(a, b);
int mn = Math.min(a, b);
int abs = Math.abs(x);
double sq = Math.sqrt(16); // 4.0
double pw = Math.pow(2, 10); // 1024.0
long rounded = Math.round(3.6); // 4
double fl = Math.floor(3.9); // 3.0
double ce = Math.ceil(3.1); // 4.0Common constants:
double pi = Math.PI;
double e = Math.E;// Using Math.random()
int r = (int) (Math.random() * 100); // 0–99
// Using java.util.Random
import java.util.Random;
Random rand = new Random();
int a = rand.nextInt(100); // 0–99
double x = rand.nextDouble(); // 0.0–1.0
boolean flag = rand.nextBoolean();String s = "hello";
// length & access
int len = s.length();
char ch = s.charAt(1); // 'e'
// substring (start inclusive, end exclusive)
String sub = s.substring(1, 4); // "ell"
// concatenation
String res = s + " world";s.equals("hello"); // true
s.equalsIgnoreCase("HeLLo"); // true
s.contains("he");
s.startsWith("he");
s.endsWith("lo");
int first = s.indexOf("l"); // 2
int last = s.lastIndexOf("l"); // 3s.replace('l', 'x'); // "hexxo"
s.replace("ll", "yy"); // "heyyo"
String[] parts = "a,b,c".split(",");
String joined = String.join("-", "a", "b", "c"); // "a-b-c"
s.toUpperCase(); // "HELLO"
s.toLowerCase(); // "hello"
s.trim(); // remove leading/trailing spacesStringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append(' ');
sb.append("world");
String str = sb.toString();
// reverse
String rev = new StringBuilder("abc").reverse().toString();
// insert & delete
sb.insert(1, "XYZ");
sb.delete(2, 4);int[] arr = {1, 2, 3};
int[] a = new int[5]; // default 0
int n = arr.length;import java.util.Arrays;
Arrays.sort(arr); // O(n log n)
Arrays.fill(arr, 5); // [5, 5, 5, 5, 5]
int[] copy = Arrays.copyOf(arr, newLength);
int[] slice = Arrays.copyOfRange(arr, from, to); // [from, to)
// binary search (array must be sorted)
int idx = Arrays.binarySearch(arr, key);int[][] mat = new int[3][4];
mat[0][0] = 1;
int rows = mat.length;
int cols = mat[0].length;
// Traversal
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int val = mat[i][j];
}
}Main interfaces (all in java.util):
List– ordered, allows duplicates (ArrayList,LinkedList)Set– unique elements (HashSet,TreeSet,LinkedHashSet)Map– key–value pairs (HashMap,TreeMap,LinkedHashMap)Queue/Deque– BFS, sliding window, etc.Stack/Deque– stack operations, DFS, parentheses problemsPriorityQueue– min/max heap
Note: Always use wrapper types with collections:
List<Integer>(notList<int>).
List<Integer> list = new ArrayList<>();
ArrayList<String> arrList = new ArrayList<>();
List<Integer> fixed = Arrays.asList(1, 2, 3); // fixed-size list viewlist.add(10); // add at end
list.add(0, 5); // add at index
int x = list.get(0); // get element
list.set(0, 99); // update element at index
list.remove(0); // remove by index
list.remove(Integer.valueOf(10)); // remove by value
int size = list.size();
boolean empty = list.isEmpty();
list.clear(); // remove allboolean exists = list.contains(25);
int firstIdx = list.indexOf(25);
int lastIdx = list.lastIndexOf(25);// List → Array
Integer[] arr = list.toArray(new Integer[0]);
// Array → List (backed by the array, fixed size)
List<Integer> fromArray = Arrays.asList(arr);// Natural order
Collections.sort(list);
// Reverse order
Collections.sort(list, Collections.reverseOrder());
// Custom comparator (e.g. sort by absolute value)
Collections.sort(list, (a, b) -> Math.abs(a) - Math.abs(b));Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(2); // ignored, no duplicates
boolean has = set.contains(1);
set.remove(1);
int size = set.size();
set.isEmpty();Common use cases: find duplicates, membership check in O(1) average.
Set<Integer> sortedSet = new TreeSet<>();
sortedSet.add(10);
sortedSet.add(5);
sortedSet.add(7); // elements kept in sorted order
// TreeSet specific operations
TreeSet<Integer> ts = new TreeSet<>();
ts.add(10); ts.add(5); ts.add(20);
Integer lower = ts.lower(10); // < 10
Integer floor = ts.floor(10); // ≤ 10
Integer higher = ts.higher(10); // > 10
Integer ceil = ts.ceiling(10); // ≥ 10Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("A", 5); // overwrite value for key "A"
int val = map.get("A"); // 5
Integer maybe = map.getOrDefault("C", 0); // 0 if key not present
boolean hasKey = map.containsKey("B");
boolean hasValue = map.containsValue(2);
map.remove("B");
int size = map.size();
map.isEmpty();// Keys
for (String key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
// Values
for (Integer value : map.values()) {
System.out.println(value);
}
// Entries (most common)
for (Map.Entry<String, Integer> e : map.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();
}Map<Integer, String> treeMap = new TreeMap<>();
treeMap.put(3, "c");
treeMap.put(1, "a");
treeMap.put(2, "b"); // keys stored in sorted orderQueue<Integer> q = new LinkedList<>();
q.add(1); // or q.offer(1);
q.add(2);
int front = q.peek(); // view front (null if empty)
int removed = q.poll(); // remove front (null if empty)
boolean empty = q.isEmpty();
int size = q.size();Useful for sliding window, monotonic queue, or as stack.
Deque<Integer> dq = new ArrayDeque<>();
dq.addLast(1); // add to back
dq.addFirst(0); // add to front
int front = dq.peekFirst();
int back = dq.peekLast();
dq.pollFirst(); // remove front
dq.pollLast(); // remove backStack<Integer> st = new Stack<>();
st.push(10);
st.push(20);
int top = st.peek(); // view top
int popped = st.pop(); // remove top
boolean empty = st.isEmpty();Alternative (recommended in modern code): use
Dequeas stack withpush,pop,peek.
// Min-heap (default)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.offer(5);
minHeap.offer(1);
minHeap.offer(10);
int smallest = minHeap.peek(); // 1
int removed = minHeap.poll(); // 1
// Max-heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());// if / else
if (a > b) {
// ...
} else if (a == b) {
// ...
} else {
// ...
}
// for loop
for (int i = 0; i < n; i++) {
// ...
}
// enhanced for (for-each)
for (int x : arr) {
// ...
}
// while loop
while (condition) {
// ...
}
// do-while
do {
// ...
} while (condition);import java.util.*;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long l = sc.nextLong();
double d = sc.nextDouble();
String s = sc.next(); // token (no spaces)
String line = sc.nextLine(); // whole line
sc.close();import java.io.*;
import java.util.*;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
// read token
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
// typical pattern inside main:
String line = br.readLine();import java.io.*;
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
out.println("Hello");
out.print(123);
out.flush(); // or out.close();// chars 'a' to 'z'
int[] freq = new int[26];
for (char ch : s.toCharArray()) {
freq[ch - 'a']++;
}
// generic frequency with HashMap
Map<Integer, Integer> count = new HashMap<>();
for (int x : arr) {
count.put(x, count.getOrDefault(x, 0) + 1);
}int[] prefix = new int[n + 1]; // prefix[0] = 0
for (int i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + arr[i];
}
// sum of [l, r] inclusive
int sum = prefix[r + 1] - prefix[l];// Sort List<Integer> ascending / descending
Collections.sort(list, (a, b) -> a - b); // ascending
Collections.sort(list, (a, b) -> b - a); // descending
// Sort array of int[] by first element, then second
Arrays.sort(arrOfPairs, (p1, p2) -> {
if (p1[0] != p2[0]) return p1[0] - p2[0];
return p1[1] - p2[1];
});import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
for (int x : arr) {
System.out.print(x + " ");
}
sc.close();
}
}import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
for (int x : arr) {
out.print(x + " ");
}
out.println();
out.flush();
}
}- Prefer 0-based indexing consistently.
- Use
StringBuilderwhen building strings in loops. - Use HashMap / HashSet for O(1) average lookups.
- Use PriorityQueue for problems involving "k smallest/largest" or "always pick min/max".
- Memorize at least one I/O template and a sort + custom comparator pattern.
Happy coding! 🚀