Docsity

Java Interview Preparation Notes: Important Topics + 28 Must-Practice Coding Questions, Cheat Sheet of Java Programming

Toggle sidebar
bg1
JAVA
Interview Preparation Notes
Important Topics + Must-Practice Code Questions
Student-written revision notes for MCA / BCA / Fresher interviews
Part Topic
1 Java Basics, JVM and Memory
2 Strings
3 OOP Concepts
4 Exception Handling
5 Collections Framework
6 Multithreading
7 Java 8 Features
8 Coding Questions (28 programs)
9 Tricky Output-Based Questions
10 Rapid-Fire Q&A and Last-Minute Tips
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.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Java Interview Preparation Notes: Important Topics + 28 Must-Practice Coding Questions and more Cheat Sheet Java Programming in PDF only on Docsity!

JAVA

Interview Preparation Notes

Important Topics + Must-Practice Code Questions

Student-written revision notes for MCA / BCA / Fresher interviews

Part Topic

1 Java Basics, JVM and Memory

2 Strings

3 OOP Concepts

4 Exception Handling

5 Collections Framework

6 Multithreading

7 Java 8 Features

8 Coding Questions (28 programs)

9 Tricky Output-Based Questions

10 Rapid-Fire Q&A and Last-Minute Tips

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

  • Platform independent : source compiles to bytecode (.class), which any JVM can run (write once, run anywhere).
  • Object-oriented (except 8 primitive types), robust (exception handling, garbage collection), secure (no pointers, bytecode verifier), multithreaded , portable.
  • Java is not 100% object-oriented because of primitives (int, char, etc.) and static members.

JDK vs JRE vs JVM

Term Meaning

JVM Java Virtual Machine. Runs bytecode. Does class loading, bytecode verification, JIT compilation and garbage

collection. Platform dependent.

JRE JVM + core libraries (rt classes). Needed to only run Java programs.

JDK JRE + development tools (javac, jar, javadoc, debugger). Needed to write and compile programs.

Data Types and Wrapper Classes

Type Size Default Notes

byte 1 byte 0 -128 to 127

short 2 bytes 0 -32768 to 32767

int 4 bytes 0 about +/- 2.1 billion

long 8 bytes 0L use L suffix

float 4 bytes 0.0f use f suffix

double 8 bytes 0.0d default decimal type

char 2 bytes '\u0000' Unicode, 0 to 65535

boolean JVM dependent false true / false

  • Autoboxing : int to Integer automatically. Unboxing : Integer to int. Wrapper classes are immutable.
  • Integer cache : Integer values from -128 to 127 are cached, so == works only in that range. Always use equals() for objects.

Memory Areas in JVM

  • Heap : all objects live here. Shared by all threads. Garbage collector works here. Divided into Young (Eden + Survivor S0/S1) and Old generation.
  • Stack : one per thread. Stores method frames, local variables and references. Gets cleared when a method ends. Overflow gives StackOverflowError.
  • Metaspace (Java 8+, replaced PermGen): class metadata, static variables' metadata, method info.
  • PC register and native method stack : current instruction address per thread, and native code support.

Garbage Collection

  • Automatic removal of objects that have no references. You can only request it with System.gc(); JVM may ignore it.
  • Common collectors: Serial, Parallel, CMS (removed), G1 (default from Java 9), ZGC. Minor GC cleans Young generation; Major/Full GC cleans Old generation.
  • An object becomes eligible for GC when reference is set to null, reassigned, or goes out of scope (island of isolation).

Remember: static variables belong to the class (one copy), instance variables belong to each object, local variables live on

the stack and must be initialised before use.

  • final : variable = constant, method = cannot be overridden, class = cannot be inherited (String is final).
  • finally : block that runs after try/catch. finalize() : called by GC before destroying an object (deprecated).
  • Constructor : same name as class, no return type, called on new. Default constructor is given only if you write none. Constructors are not inherited and cannot be abstract/static/final.
  • Access modifiers: private (class) < default (package) < protected (package + subclasses) < public (everywhere).
  • Java does not support multiple inheritance with classes (diamond problem) but supports it through interfaces.

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

Class Ordered? Duplicates Null Internal / Notes

ArrayList Insertion order Yes Yes Dynamic array; fast get O(1), slow middle

insert/delete O(n)

LinkedList Insertion order Yes Yes Doubly linked list; fast insert/delete, slow get O(n)

Vector Insertion order Yes Yes Synchronized (legacy)

HashSet No order No One null Backed by HashMap

LinkedHashSet Insertion order No One null HashSet + linked list

TreeSet Sorted No No Red-Black tree, O(log n)

Class Ordered? Duplicates Null Internal / Notes

HashMap No order Keys unique 1 null key Array of buckets, O(1) average

LinkedHashMa

p

Insertion order Keys unique 1 null key HashMap + linked list

TreeMap Sorted by key Keys unique No null key Red-Black tree

Hashtable No order Keys unique No nulls Synchronized (legacy)

How HashMap Works Internally (Very Important)

  • Stores data as Node(hash, key, value, next) in an array of buckets (default size 16, load factor 0.75).
  • put(k,v) : compute hashCode of key, spread hash, index = hash & (n-1). If bucket empty, store. If not empty, compare keys with equals() : same key = replace value, else add to the chain.
  • Collision handling: linked list; from Java 8 a bucket converts to a Red-Black tree when it has 8+ nodes (and table size at least 64). Worst case improves from O(n) to O(log n).
  • Resize : when size > capacity x 0.75, the table doubles and entries are rehashed.
  • hashCode/equals contract : if two objects are equal, they must have the same hashCode. Always override both together for custom keys.
  • HashMap is not thread-safe. Use ConcurrentHashMap (locks per bucket/CAS, no null keys or values) or Collections.synchronizedMap().

Comparable vs Comparator

Comparable Comparator

Package java.lang; method compareTo(T o) Package java.util; method compare(T a, T b)

Natural (default) ordering, inside the class Custom ordering, separate class or lambda

Only one sort order per class Many sort orders possible

Other Must-Know Points

  • Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is modified while iterating. Fail-safe (CopyOnWriteArrayList, ConcurrentHashMap) do not.
  • Iterator moves forward only and can remove(); ListIterator moves both ways (lists only).
  • Arrays.asList() returns a fixed-size list (cannot add/remove). List.of() is immutable.
  • ArrayList grows by 50% (new capacity = old + old/2). Default capacity is 10 (created lazily on first add).
  • Queue : PriorityQueue (min-heap by default), ArrayDeque. Stack is legacy; prefer Deque. 6. Multithreading
  • Process = heavy, own memory. Thread = lightweight unit inside a process, shares heap memory.
  • Ways to create a thread: (1) extend Thread , (2) implement Runnable (preferred, allows extending another class), (3) implement Callable (returns a value, throws exceptions) with ExecutorService.
  • start() creates a new thread and calls run(); calling run() directly just executes it in the current thread like a normal method. Calling start() twice gives IllegalThreadStateException.

Thread Life Cycle

NEW -> RUNNABLE -> (RUNNING) -> BLOCKED / WAITING / TIMED_WAITING -> TERMINATED

Synchronization and Keywords

  • synchronized (method or block): only one thread at a time holds the object lock; prevents race conditions. Static synchronized locks the class object.
  • volatile : guarantees visibility of a variable's latest value across threads (no caching), but does NOT give atomicity (count++ is still unsafe). Use AtomicInteger for that.
  • wait() (releases lock), notify() , notifyAll() must be called inside synchronized code; they belong to Object class. sleep() belongs to Thread and does not release the lock.

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

Remember: Static block runs once when the class loads. Instance block and constructor run for every object; instance block

runs before the constructor body.

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

  • Start with a brute-force idea, then improve it. Always mention time and space complexity.
  • Handle edge cases aloud: null input, empty string/array, single element, negative numbers, overflow.
  • Use meaningful variable names, and dry-run your code with a small example before saying you are done.
  • Prepare 2 to 3 lines about your own project and where you used Java concepts like collections, exceptions and OOP.
  • If you do not know an answer, say what you do know about the topic and how you would find out. Do not guess wildly.