






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







How to use: read the theory once, then type every program yourself without looking. Interviewers ask you to write
code live, so practice on paper or in a plain editor.
1. Java Basics, JVM and Memory
Features of Java
JDK vs JRE vs JVM
Data Types and Wrapper Classes
Memory Areas in JVM
Garbage Collection
Runtime polymorphism example
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } }
public class Test { public static void main(String[] args) { Animal a = new Dog(); // upcasting a.sound(); // prints Bark (decided at runtime) } }
4. Exception Handling - Exception = event that disrupts normal flow. Hierarchy: Throwable -> Error (OutOfMemoryError, StackOverflowError) and Exception. - Checked (checked by compiler, must handle or declare): IOException, SQLException, ClassNotFoundException. - Unchecked (RuntimeException subclasses): NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException. - throw = actually throw an exception object; throws = declares in method signature; try-with-resources auto-closes AutoCloseable resources. - finally runs even if there is a return in try; it does not run only if the JVM exits (System.exit) or crashes. - Order of multiple catch blocks: specific first, general (Exception) last, otherwise compile error.
try-catch-finally and custom exception
class InvalidAgeException extends Exception { InvalidAgeException(String msg) { super(msg); } }
public class AgeCheck { static void check(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18+"); System.out.println("Eligible"); } public static void main(String[] args) { try { check(15); } catch (InvalidAgeException e) { System.out.println("Caught: " + e.getMessage()); } finally { System.out.println("Finally always runs"); } } }
5. Collections Framework
Hierarchy: Iterable -> Collection -> List , Set , Queue. Map is separate (does not extend Collection).
How HashMap Works Internally (Very Important)
Comparable vs Comparator
Other Must-Know Points
Thread Life Cycle
NEW -> RUNNABLE -> (RUNNING) -> BLOCKED / WAITING / TIMED_WAITING -> TERMINATED
Synchronization and Keywords
5. Prime number check
static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; // only up to sqrt(n) return true; }
6. Swap two numbers without a third variable
int a = 10, b = 20; a = a + b; // 30 b = a - b; // 10 a = a - b; // 20
7. Check if two strings are anagrams
static boolean isAnagram(String a, String b) { if (a.length() != b.length()) return false; char[] x = a.toLowerCase().toCharArray(), y = b.toLowerCase().toCharArray(); Arrays.sort(x); Arrays.sort(y); return Arrays.equals(x, y); }
8. Count vowels and consonants
String s = "Hello World"; int v = 0, c = 0; for (char ch : s.toLowerCase().toCharArray()) { if (ch >= 'a' && ch <= 'z') { if ("aeiou".indexOf(ch) != -1) v++; else c++; } } System.out.println("Vowels=" + v + " Consonants=" + c);
9. Character frequency using HashMap
String s = "programming"; Map map = new HashMap<>(); for (char ch : s.toCharArray()) map.put(ch, map.getOrDefault(ch, 0) + 1); System.out.println(map); // {p=1, r=2, g=2, a=1, m=2, i=1, n=1, o=1}
10. First non-repeating character
String s = "swiss"; Map m = new LinkedHashMap<>(); // keeps insertion order for (char ch : s.toCharArray()) m.merge(ch, 1, Integer::sum); for (Map.Entry e : m.entrySet()) if (e.getValue() == 1) { System.out.println(e.getKey()); break; } // w
11. Remove duplicates from an array
int[] arr = {1, 2, 2, 3, 4, 4, 5}; Set set = new LinkedHashSet<>(); for (int n : arr) set.add(n); System.out.println(set); // [1, 2, 3, 4, 5]
12. Second largest element in an array
int[] a = {12, 35, 1, 10, 34, 1}; int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int n : a) { if (n > first) { second = first; first = n; } else if (n > second && n != first) second = n; } System.out.println(second); // 34
13. Find the missing number from 1 to n
int[] a = {1, 2, 4, 5, 6}; int n = 6; int expected = n * (n + 1) / 2, actual = 0; for (int x : a) actual += x; System.out.println(expected - actual); // 3
14. Binary search (array must be sorted)
static int binarySearch(int[] a, int key) { int lo = 0, hi = a.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == key) return mid; else if (a[mid] < key) lo = mid + 1; else hi = mid - 1; } return -1; // O(log n) }
15. Bubble sort
static void bubbleSort(int[] a) { for (int i = 0; i < a.length - 1; i++) for (int j = 0; j < a.length - i - 1; j++) if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; } } // O(n^2)
16. Armstrong number (153 = 1^3 + 5^3 + 3^3)
int n = 153, sum = 0, t = n; while (t > 0) { int d = t % 10; sum += d * d * d; t /= 10; } System.out.println(sum == n? "Armstrong" : "Not Armstrong");
17. Reverse a linked list
class Node { int data; Node next; Node(int d) { data = d; } }
static Node reverse(Node head) { Node prev = null, curr = head; while (curr != null) { Node nxt = curr.next; curr.next = prev; prev = curr; curr = nxt; } return prev; // new head }
18. Singleton class (thread-safe, double-checked locking)
class Singleton { private static volatile Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; } }
19. Thread using Runnable and lambda
Runnable task = () -> System.out.println("Running: " + Thread.currentThread().getName()); Thread t1 = new Thread(task, "T1"); Thread t2 = new Thread(task, "T2"); t1.start(); t2.start();
20. Synchronized counter (avoid race condition)
class Counter { private int count = 0; public synchronized void increment() { count++; } public int get() { return count; } }
21. Deadlock example (know why it happens)
Object lockA = new Object(), lockB = new Object(); new Thread(() -> { synchronized (lockA) { sleep(100); synchronized (lockB) { } } }).start(); new Thread(() -> { synchronized (lockB) { sleep(100); synchronized (lockA) { } } }).start(); // Thread 1 holds A and waits for B; Thread 2 holds B and waits for A -> deadlock // Fix: both threads should take locks in the same order (A then B)
Q3. finally with return
static int test() { try { return 1; } finally { System.out.println("finally"); } // prints finally, then returns 1 }
Q4. Character arithmetic
System.out.println('a' + 1); // 98 (char promoted to int) System.out.println((char)('a' + 1)); // b System.out.println("a" + 1 + 2); // a System.out.println(1 + 2 + "a"); // 3a
Q5. Floating point
System.out.println(0.1 + 0.2); // 0. System.out.println(10 / 3); // 3 (integer division) System.out.println(10 / 3.0); // 3. System.out.println(5 / 0.0); // Infinity (5 / 0 gives ArithmeticException)
Q6. Increment operators
int i = 5; int r = i++ + ++i; // 5 + 7 = 12 ; i becomes 7 System.out.println(r);
Q7. Order of execution
class A { static { System.out.println("static block"); } { System.out.println("instance block"); } A() { System.out.println("constructor"); } public static void main(String[] args) { new A(); new A(); } } // Output: static block, instance block, constructor, instance block, constructor
10. Rapid-Fire Q&A and Last-Minute Tips
Q. Can we override the main method?
No. main is static. You can overload it, but the JVM calls only main(String[] args).
Q. Can we declare a class as both abstract and final?
No. Abstract needs to be inherited, final prevents inheritance.
Q. Can a constructor be private?
Yes. Used in Singleton and factory patterns.
Q. What is the difference between == and equals()?
== compares references (for primitives, values). equals() compares content if overridden.
Q. Difference between ArrayList and LinkedList?
ArrayList = dynamic array, fast random access. LinkedList = doubly linked list, fast insertion/deletion in the middle.
Q. HashMap vs Hashtable?
HashMap: not synchronized, allows one null key. Hashtable: synchronized, no nulls, legacy.
Q. HashSet vs TreeSet?
HashSet: unordered, O(1). TreeSet: sorted, O(log n), no null.
Q. What is the difference between throw and throws?
throw actually throws an exception object; throws declares possible exceptions in the method signature.
Q. What happens if we do not override hashCode() with equals()?
Equal objects may land in different buckets, so HashMap/HashSet can hold logical duplicates or fail to find keys.
Q. What is a marker interface?
An interface with no methods used as a tag, for example Serializable and Cloneable.
Q. What is serialization?
Converting an object into a byte stream to store or send it. Fields marked transient are skipped; static fields are not serialized.
Q. Shallow copy vs deep copy?
Shallow copy copies references of inner objects; deep copy creates new copies of inner objects too.
Q. What is the use of the super keyword?
To access the parent's methods, variables and constructor.
Q. Can we have multiple public classes in one file?
No. Only one public class, and the file name must match it.
Q. What is the difference between path and classpath?
PATH is used by the OS to find executables like javac. CLASSPATH is used by JVM to find .class files and jars.
Q. What is the diamond problem?
Ambiguity when a class inherits the same method from two parents. Java avoids it by not allowing multiple class inheritance; for default methods the class must override to resolve it.
Q. What is the difference between process and thread?
Process has its own memory space and is heavy; threads share the process memory and are lightweight.
Q. What are the SOLID principles?
Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion.
Last-Minute Interview Tips