Skip to content

Sanjaykannavedhachalam/JAVA-Programmes-STS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🧠 Java Coding Test Cheat Sheet

Practical reference of Java basics, conversions, math, strings, arrays, collections, I/O and common patterns
for algorithm / competitive programming / coding interviews.


📚 1. Common Imports

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 automatically

🔢 2. Primitive Types & Wrappers

int 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;

🔁 3. Type Conversion (Casting & Parsing)

3.1 Number ↔ String

// 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");

3.2 char ↔ int

// char → int (ASCII / Unicode code)
int code = 'A';           // 65

// int → char
char ch = (char) 65;      // 'A'

3.3 String ↔ char[]

// String → char[]
char[] chars = "hello".toCharArray();

// char[] → String
String s = new String(chars);

3.4 Decimal ↔ Binary

// Decimal → Binary String
String binStr = Integer.toBinaryString(10);  // "1010"

// Binary String → Decimal
int num = Integer.parseInt("1010", 2);      // 10

🧮 4. Math & Random (java.lang.Math)

4.1 Math

int 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.0

Common constants:

double pi = Math.PI;
double e  = Math.E;

4.2 Random

// 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();

🧵 5. Strings & StringBuilder

5.1 Basic String Operations

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";

5.2 Comparison & Search

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");    // 3

5.3 Replace, Split, Join, Case

s.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 spaces

5.4 StringBuilder (for Fast Mutations)

StringBuilder 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);

🧱 6. Arrays

6.1 Declaration & Initialization

int[] arr = {1, 2, 3};
int[] a = new int[5];        // default 0
int n = arr.length;

6.2 Common Operations (java.util.Arrays)

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);

6.3 Multidimensional Arrays

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];
    }
}

🧺 7. Collections Framework Overview

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 problems
  • PriorityQueue – min/max heap

Note: Always use wrapper types with collections: List<Integer> (not List<int>).


📋 8. List & ArrayList

8.1 Declaration & Creation

List<Integer> list = new ArrayList<>();
ArrayList<String> arrList = new ArrayList<>();
List<Integer> fixed = Arrays.asList(1, 2, 3);   // fixed-size list view

8.2 Adding, Getting, Updating, Removing

list.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 all

8.3 Search & Utility

boolean exists = list.contains(25);
int firstIdx = list.indexOf(25);
int lastIdx = list.lastIndexOf(25);

8.4 Convert Between List & Array

// List → Array
Integer[] arr = list.toArray(new Integer[0]);

// Array → List (backed by the array, fixed size)
List<Integer> fromArray = Arrays.asList(arr);

8.5 Sorting Lists

// 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));

🧾 9. Set

9.1 HashSet (Unordered, Unique)

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.

9.2 TreeSet (Sorted Unique)

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);  // ≥ 10

🗺️ 10. Map (HashMap, TreeMap)

10.1 HashMap (Unordered Key–Value)

Map<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();

10.2 Iterating Maps

// 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();
}

10.3 TreeMap (Sorted by Key)

Map<Integer, String> treeMap = new TreeMap<>();

treeMap.put(3, "c");
treeMap.put(1, "a");
treeMap.put(2, "b");   // keys stored in sorted order

📬 11. Queue, Deque, Stack, PriorityQueue

11.1 Queue (FIFO) – LinkedList

Queue<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();

11.2 Deque (Double-Ended Queue)

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 back

11.3 Stack

Stack<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 Deque as stack with push, pop, peek.

11.4 PriorityQueue (Heap)

// 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());

🧭 12. Control Flow (if, loops)

// 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);

📥 13. Input / Output Patterns

13.1 Simple: Scanner (Easy but Slower)

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();

13.2 Fast I/O: BufferedReader + StringTokenizer

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();

13.3 Fast Output: PrintWriter

import java.io.*;

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

out.println("Hello");
out.print(123);
out.flush();    // or out.close();

🧰 14. Common Algorithmic Helpers

14.1 Frequency Count (Map / Array)

// 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);
}

14.2 Prefix Sum Array

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];

14.3 Sorting With Custom Comparator

// 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];
});

🧾 15. Full Template for Coding Problems

15.1 Basic Template (Scanner)

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();
    }
}

15.2 Fast I/O Template

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();
    }
}

✅ Tips for Coding Tests

  • Prefer 0-based indexing consistently.
  • Use StringBuilder when 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! 🚀


About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages