200+ Java Interview Questions and Answers for All Levels

Facing a stack of technical coding interviews and not sure what to study next? Coding interviews test both your code and your thinking, from core Java and object-oriented design to concurrency and system design. This collection of Java interview questions and answers covers core Java, OOP, collections, JVM internals, multithreading, Java 8 features, streams, design patterns, data structures, common coding challenges, and behavioral questions so you can practice real interview prompts. Use it to confidently crack Java interviews at any level by mastering 200+ carefully curated questions and answers that cover everything from basics to advanced concepts.

Interview Coder's AI Interview Assistant helps you reach that goal by offering personalized practice, mock interviews, clear explanations, and targeted feedback to sharpen your problem-solving and system design skills.

Top 80 Java Interview Questions and Answers

Blog image

1. What is Java? A Concise Definition of the Platform

Java is a high-level, class-based, object-oriented programming language designed for portability, write once, run anywhere. Compiled Java bytecode runs on any platform with a compatible JVM, making Java a general-purpose choice for server, desktop, and mobile applications.

2. JDK, JRE, and JVM: How They Fit Together

JVM (Java Virtual Machine) runs Java bytecode and converts it to machine instructions at runtime. JRE (Java Runtime Environment) packages the JVM plus the core libraries and runtime files needed to run Java programs. JDK (Java Development Kit) includes the JRE plus developer tools (compiler, debugger, etc.) used to build Java applications.

3. Variables in Java: What They Are and Why Types Matter

Variables are named containers for data. Java is statically typed, so you declare a variable with a type (int, String, double, etc.) before using it. Types determine storage, valid operations, and compile-time checks.

4. Typecasting in Java: Converting Between Types

Typecasting converts a value from one type to another. Widening casting (implicit) converts smaller to larger types, e.g., int to long. Narrowing casting (explicit) converts larger to smaller types and requires a cast, e.g., (int) 3.14.

5. Declaring Arrays: Fixed-Size Collections

An array holds a fixed number of values of one type.

Example declarations:int[] myIntArray = new int[10];String[] myStringArray = new String[50];

6. The Main Method: Java's Entry Point

The main method is the program entry point and must be public, static, return void, and accept a String array:public static void main(String[] args) { // program starts here}

7. Literals: Fixed Values in Code

Literals are fixed values written directly in code, such as 100, -90, 3.14F, 'A', and "Hello". They represent constants of primitive or String types.

8. Constructors: How Objects Get Initialized

A constructor is a special method called when creating an object. It has no return type and shares the class name. Constructors initialize instance state.

9. Method Overloading: Same Name, Different Parameters

Method overloading allows multiple methods in the same class with the same name but different parameter lists. It resolves at compile time and supports clearer APIs.

10. Packages: Organizing Classes and Interfaces

A package is a namespace grouping related classes and interfaces. Use packages to avoid name collisions and to structure code like folders.

11. What is OOP: The Object-Centered Approach

Object-oriented programming models software as objects with fields and methods. It emphasizes modeling real-world entities, encapsulating state, and defining behaviour on that state.

12. OOP Principles: Four Pillars That Guide Design

  • Encapsulation: Bundle state and behavior; hide internal details.
  • Abstraction: Expose a simple interface while hiding complexity.
  • Inheritance: Derive new classes from existing ones to reuse code.
  • Polymorphism: Let objects present different behaviors under a common type.

13. Inheritance: Reusing and Extending Behavior

Inheritance lets a class inherit fields and methods from a parent class, enabling code reuse and subtype relationships.

14. Interfaces: Contracts for Behavior

An interface defines method signatures (and since Java 8 default and static methods). Classes implement interfaces to promise certain behavior without specifying implementation.

15. Abstract Classes vs Interfaces: When to Choose Which

Abstract class: can have both abstract and concrete methods and state; used when classes share common implementation. Interface: defines a contract; used for multiple inheritance of type and to decouple behavior.

16. Polymorphism: One Reference, Many Behaviors

Polymorphism lets a parent type reference point to child objects; method calls dispatch to the actual runtime implementation. It supports flexible and extensible code.

17. Method Overriding: Customize Inherited Behavior

Overriding provides a subclass-specific implementation of a superclass method with the same signature. Use @Override to signal intent and enable runtime polymorphism.

18. The Super Keyword: Access Parent Class Members

Use super to call a superclass constructor or to refer to superclass methods/fields when overridden or hidden.

19. Getters and Setters: Controlled Access to Fields

Getters and setters are methods that read and modify private fields. They enforce encapsulation:public int getNum() { return num; }public void setNum(int num) { this.num = num; }

20. Static: Class-Level Members

Static marks members that belong to the class rather than instances. Static fields and methods are shared across all instances.

21. Exception Handling: Managing Runtime Errors

Exception handling uses try, catch, and finally to manage runtime errors and keep program flow predictable when exceptions occur.

22. Try-Catch Blocks: Catch Exceptions Where They Occur

Place risky code in try and handle exceptions in catch blocks. You may chain multiple catch blocks or use finally for cleanup.

23. Finally Block: Cleanup that Always Runs

Finally contains code that executes after try/catch whether an exception occurred or not, commonly used to release resources.

24. What is an Exception: An Error Signal at Runtime

An exception is a runtime problem signaled by an object that can interrupt normal flow; catch or declare it to handle the condition.

25. Checked Exceptions: Enforced at Compile Time

Checked exceptions must be declared or handled by the calling code (e.g., IOException, SQLException). The compiler enforces handling or declaration.

26. Unchecked Exceptions: Runtime Problems Not Required to Be Declared

Unchecked exceptions extend RuntimeException and are not checked by the compiler. They usually indicate programming errors like NullPointerException.

27. Throws Keyword: Declaring Exceptions

Use throws in a method signature to declare that it may propagate certain checked exceptions to its caller.

28. Throw vs Throws: Throwing and Declaring Exceptions

Throw explicitly raises an exception instance. Throws in a method signature declares which checked exceptions may be propagated.

29. Using Throw: Explicitly Raise an Error

Use throw inside a method to signal a specific error condition by providing an exception instance, e.g., throw new IllegalArgumentException("bad arg");

30. Custom Exceptions: Tailor Error Types

Create a custom exception by extending Exception or RuntimeException to express application-specific error conditions and improve clarity.

31. String API: Working with Text

The String API provides methods to manipulate text: length(), substring(), equals(), indexOf(), replace(), split(), and more. Strings are central for input, output, and data handling.

32. String, StringBuilder, StringBuffer: Mutability and Threading

String is immutable. StringBuilder is mutable and not synchronized, offering fast single-threaded concatenation. StringBuffer is mutable and synchronized, safe for concurrent access.

33. Immutable Objects: Predictable, Thread-Friendly State

Immutable objects cannot change after creation. They simplify reasoning and avoid many concurrency bugs; String is a common example.

34. Wrapper Classes: Object Forms of Primitives

Wrapper classes (Integer, Character, Double, etc.) wrap primitive values into objects so you can use them with collections and APIs expecting objects.

35. Autoboxing and Unboxing: Automatic Conversion

Autoboxing converts primitives to their wrapper types automatically. Unboxing converts wrapper objects back to primitives. Example: Integer i = 5; int j = i;

36. Collections API: Data Structures and Algorithms

The Collections API (java.util) provides interfaces and implementations for lists, sets, queues, and maps, plus utility methods for sorting, searching, and synchronization.

37. Generics: Type-Safe Reusable Code

Generics let you parameterize classes and methods with types. They enforce compile-time type safety and reduce casts, e.g., List<String> avoids inserting wrong types.

38. Iterator Interface: Uniform Traversal

Iterator lets you traverse a Collection with hasNext() and next(), and remove elements safely during iteration.

39. Iterator vs ListIterator: Forward vs Bidirectional

Iterator supports forward traversal and element removal. ListIterator supports bidirectional traversal, element modification, and index queries for lists.

40. Map: Key-Value Data Structures

Map associates unique keys to values. Common implementations include HashMap (fast lookup), TreeMap (sorted keys), and LinkedHashMap (insertion order).

41. Concurrency: Running Tasks in Parallel

Concurrency enables multiple tasks or parts of a program to run at once, improving throughput on multicore systems when designed correctly.

42. Thread: A Path of Execution

A thread represents an independent path of execution within a program. Multiple threads share process memory and can run concurrently.

43. Process vs Thread: Isolation and Sharing

A process is an independent program instance with its own memory and resources. Threads are lightweight execution paths within a process that share memory and resources.

44. Multithreading: Multiple Threads in One Program

Multithreading runs several threads within the same application to perform tasks concurrently, improving responsiveness and resource utilization.

45. Synchronized Keyword: Mutual Exclusion Tool

Use synchronized on methods or blocks to ensure only one thread at a time executes the protected code for a given monitor, preventing race conditions on shared state.

46. Deadlock: Threads Waiting Forever

Deadlock happens when threads wait on each other for locks, creating a cycle with no progress. Avoid by consistent lock ordering or using tryLock with timeouts.

47. Thread States: Life Cycle of a Thread

Threads move through states: New, Runnable, Blocked (waiting for a monitor), Waiting (awaiting another thread), Timed Waiting (waiting with timeout), and Terminated after completion.

48. Volatile Keyword: Visibility Without Locking

Volatile marks a variable whose reads and writes go straight to main memory. It ensures visibility across threads for single reads/writes but does not provide atomicity for compound operations.

49. Thread Safety: Safe Concurrent Use

Thread safety means code behaves correctly when accessed by multiple threads simultaneously. Achieve it via immutability, synchronization, or concurrency utilities from java.util.concurrent.

50. Creating Threads: Two Common Ways

Extend Thread and override run():public class MyThread extends Thread { public void run() { System.out.println("Thread running"); }}Or implement Runnable and pass to a Thread:public class MyRunnable implements Runnable { public void run() { System.out.println("Runnable running"); }}

51. Stream API: Declarative Collection Processing

Streams provide a pipeline for processing collections with operations like map, filter, sort, and reduce, enabling concise and expressive transformations.

52. Benefits of Streams: Cleaner Bulk Operations

Streams make code shorter and clearer for bulk operations, support parallel execution easily, and separate what to do from how to iterate.

53. Obtaining a Stream from a List: Start the Pipeline

Create a stream from a list:List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");Stream<String> myStream = myList.stream();

54. Map vs FlatMap: One-to-One vs Flattening

Map applies a function to each element, producing a stream of results one-to-one. FlatMap maps elements to streams and flattens them into a single stream.

55. Filter in Streams: Keep Elements That Match

Filter takes a Predicate and retains only elements that satisfy it, producing a smaller stream for downstream operations.

56. Sorting a Stream: Use Sorted()

Sort a stream and collect results:List<String> sortedList = myList.stream() .sorted() .collect(Collectors.toList());

57. Terminal Operations: Produce Results or Side Effects

Terminal operations end a stream pipeline and produce a result or side effect. Examples: forEach, collect, reduce, count.

58. Collect Method: Gather Stream Results

Collect is a terminal operation that accumulates stream elements into a collection or other result using Collectors, e.g., Collectors.toList() or Collectors.toMap().

59. ForEach: Iterate a Stream

ForEach applies a Consumer to each element of the stream as a terminal operation. It consumes the stream and cannot be reused afterward.

60. Reduce: Combine Elements Into One

Reduce folds stream elements into a single value using an identity and a BinaryOperator, useful for sums, concatenation, or custom aggregation.

61. JDBC: Java Access to Relational Databases

JDBC is the Java API for executing SQL and interacting with relational databases from Java applications.

62. Core JDBC Components: Building Blocks for DB Access

Core components include DriverManager, Driver, Connection, Statement, ResultSet, and SQLException for managing connections, executing SQL, and handling results.

63. Connecting to a Database: Example Code

Establish a connection:Connection conn = DriverManager.getConnection("jdbc:subprotocol:subname", "user", "password");

64. Statement vs PreparedStatement: Dynamic and Parameterized SQL

Statement executes simple SQL without parameters. PreparedStatement precompiles SQL and accepts parameters, improving performance and preventing SQL injection.

65. Executing a Query in JDBC: Steps to Run SQL

Use a Statement or PreparedStatement and executeQuery:Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("SELECT * FROM myTable");

66. ResultSet: Retrieving Query Results

ResultSet represents rows returned by a query and provides methods like next(), getString(), and getInt() to read column values.

67. Batch Processing in JDBC: Reduce Round Trips

Batch processing groups multiple SQL commands and sends them in a single round trip to the database, improving throughput for bulk operations.

68. JDBC Driver Types: Four Common Approaches

  • Type 1: JDBC-ODBC bridge.
  • Type 2: Native-API/partly Java driver.
  • Type 3: Net-protocol/all-Java driver.
  • Type 4: Native-protocol/all-Java driver (most common today).

69. Handling SQL Exceptions: Catch SQLException

Wrap JDBC calls in try/catch to handle SQLException and free resources in finally, or use try-with-resources:try { // JDBC code} catch (SQLException ex) { // handle error}

70. Connection Pooling: Reuse Database Connections

Connection pooling reuses open connections to reduce the overhead of opening and closing connections, improving performance in database-heavy applications.

71. List Interface: Ordered Collections with Index Access

List represents an ordered sequence allowing positional access, insertion, and removal. Common implementations include ArrayList and LinkedList.

72. Iterating Over a List — Simple Loop Example

Use an enhanced for loop:List<String> list = Arrays.asList("apple", "banana", "cherry");for(String fruit : list) { System.out.println(fruit);}

73. ArrayList vs LinkedList: When to Pick Which

ArrayList uses a dynamic array offering fast random access and good cache locality. LinkedList stores nodes with pointers, providing cheaper insertions/removals in the middle.

74. Removing Elements From a List: By Index or Object

Use remove(Object) to remove the first matching element or remove(index) to remove by position:list.remove("apple");list.remove(0);

75. Vector and Stack Classes: Legacy Synchronized Types

Vector is like ArrayList, but synchronized. Stack extends Vector and provides push, pop, and peek to treat it as a LIFO stack.

76. Convert List to Array: ToArray Usage

Convert a List to an array with:String[] array = list.toArray(new String[list.size()]);

77. Iterator vs ListIterator: Traversal Capabilities Compared

Iterator supports forward traversal and removal. ListIterator supports forward and backward traversal, element replacement, addition, and index queries on lists.

78. SubList Method: View Into a List Segment

subList(fromIndex, toIndex) returns a view of the portion between fromIndex (inclusive) and toIndex (exclusive). Changes affect the original list.

79. Synchronizing a List: Make Thread-Safe Wrapper

Wrap a list with Collections.synchronizedList to coordinate access across threads:List<String> syncList = Collections.synchronizedList(new ArrayList<String>());

80. Generics With List: Type Safety and Clarity

Generics provide compile-time type checking for lists, preventing wrong-type insertion and eliminating most casts, e.g., List<String> ensures only String objects go in.

Related Reading

40+ Java Basic Interview Questions and Answers for Freshers

Blog image

1. How Do You Reverse a String in Java?

This verifies knowledge of core String and char handling and shows whether you use efficient mutable builders when manipulating text. Interviewers look for correct index handling and basic defensive checks like null handling.

How to answer:

  • fdcDescribe converting to char array or using StringBuilder and iterating from end to start.
  • Mention using StringBuilder for efficient appends and adding a null check.
  • Optionally note StringBuilder has a reverse() method if allowed.

Example answer:public class StringPrograms { public static void main(String[] args) { String str = "123"; System.out.println(reverse(str)); } public static String reverse(String in) { if (in == null) throw new IllegalArgumentException("Null is not valid input"); StringBuilder out = new StringBuilder(); char[] chars = in.toCharArray(); for (int i = chars.length - 1; i >= 0; i--) out.append(chars[i]); return out.toString(); }}

2. How Do You Swap Two Numbers Without Using a Third Variable in Java?

This checks comfort with basic arithmetic tricks, operator precedence, and understanding of overflow risk in primitive types. Interviewers use it to see if you consider edge cases and simpler alternatives like XOR.

How to answer:

  • Show arithmetic swap steps and explain each assignment.
  • Mention integer overflow risk and that XOR swap works for integers without overflow.
  • Provide example code and print before/after to verify.

Example answer:public class SwapNumbers {public static void main(String[] args) { int a = 10; int b = 20; System.out.println("a is " + a + " and b is " + b); a = a + b; b = a - b; a = a - b; System.out.println("After swapping, a is " + a + " and b is " + b); }}Outputa is 10 and b is 20After swapping, a is 20 and b is 10

3. Write a Java Program to Check If a Vowel is Present in a String

This confirms knowledge of regex or string methods and case handling. It also shows whether you prefer concise patterns or manual iteration for character checks.

How to answer:

  • Use toLowerCase() then test with regex or check characters against a set.
  • Explain null and empty input handling.
  • Provide a small, readable method that returns boolean.

Example answer:public class StringContainsVowels { public static void main(String[] args) { System.out.println(stringContainsVowels("Hello")); // true System.out.println(stringContainsVowels("TV")); // false } public static boolean stringContainsVowels(String input) { return input.toLowerCase().matches(".*[aeiou].*"); }}

4. Write a Java Program to Check If the Given Number is a Prime Number

This tests algorithmic thinking and complexity awareness for a basic number theory task. Interviewers want to see correct boundary handling and possible optimizations like sqrt(n).

How to answer:

  • Explain the base cases (0, 1 not prime, 2 is prime).
  • Show loop from 2 to sqrt(n) for efficiency and return false on divisible.
  • Mention time complexity O(sqrt(n)) and any integer edge conditions.

Example answer:public class PrimeNumberCheck { public static void main(String[] args) { System.out.println(isPrime(19)); // true System.out.println(isPrime(49)); // false } public static boolean isPrime(int n) { if (n == 0 || n == 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= n / 2; i++) { if (n % i == 0) { return false; } } return true; }}Note: checking up to sqrt(n) is more efficient for large n.

5. Write a Java program to print a Fibonacci sequence using recursion

This assesses recursion basics, exponential-time pitfalls, and whether you know iterative alternatives or memoization. Interviewers often probe for complexity and stack usage.

How to answer:

  • Define base cases for n<=1, then return n.
  • Present the recursive relation F(n)=F(n-1)+F(n-2).
  • Show a loop to print the first N values, calling the recursive Fibonacci method, and mention inefficiency for large N.

Example answer:public class PrintFibonacciRecursive { public static int fibonacci(int count) { if (count <= 1) return count; return fibonacci(count - 1) + fibonacci(count - 2); } public static void main(String args[]) { int seqLength = 10; System.out.print("A Fibonacci sequence of " + seqLength + " numbers: "); for (int i = 0; i < seqLength; i++) { System.out.print(fibonacci(i) + " "); } }}OutputA Fibonacci sequence of 10 numbers: 0 1 1 2 3 5 8 13 21 34

6. How Do You Check If a List of Integers Contains Only Odd Numbers in Java?

This probes knowledge of collections and stream APIs and shows whether you choose clear, efficient iteration or functional style. Interviewers look for early exit strategies on failure.

How to answer:

  • Show simple loop checking i % 2 != 0 with early return false.
  • Mention using streams and allMatch for clear declarative code.
  • Note parallel streams and anyMatch/allMatch implications for short-circuiting.

Example answer:public static boolean onlyOddNumbers(List<Integer> list) { for (int i : list) { if (i % 2 == 0) return false; } return true;}If you prefer streams:return list.stream().allMatch(x -> x % 2 != 0);

7. How Do You Check Whether a String is a Palindrome in Java?

This checks string indexing skills and ability to reason about symmetry without extra allocations. It also shows attention to character normalization and case sensitivity.

How to answer:

  • Compare characters from both ends, moving toward the center.
  • Handle null and empty strings, and decide on case sensitivity.
  • Mention ignoring non-alphanumeric characters if required by the problem variant.

Example answer:boolean checkPalindromeString(String input) { boolean result = true; int length = input.length(); for (int i = 0; i < length/2; i++) { if (input.charAt(i) != input.charAt(length - i - 1)) { result = false; break; } } return result;}

8. How Do You Remove Spaces from a String in Java?

This confirms your knowledge of Character utilities and string immutability, as well as your preference for regex or manual filtering in terms of performance and clarity.

How to answer:

  • Show building a new string using StringBuilder while skipping Character.isWhitespace(c).
  • Mention replaceAll("\\s+", "") as a concise regex option and note regex cost.
  • Include a null or empty input guard.

Example answer:String removeWhiteSpaces(String input) { StringBuilder output = new StringBuilder(); char[] charArray = input.toCharArray(); for (char c: charArray) { if (!Character.isWhitespace(c)) output.append(c); } return output.toString();}

9. How do you remove leading and trailing spaces from a string in Java?

Trimming is common in input validation. Interviewers expect awareness of newer String APIs and Unicode aware behavior.

How to answer:

  • Mention String.strip() (Java 11+) for Unicode-aware trimming and String.trim() as historical option.
  • Explain String immutability and assignment of the result.

Example answer:String s = " abc def\t"; s = s.strip(); System.out.println(s);

10. How Do You Sort an Array in Java?

Sorting tests knowledge of Java utilities and Comparable/Comparator patterns for custom types. Interviewers assess whether you pick the right API.

How to answer:- Use Arrays.sort() for primitives and objects when natural order is fine.- For custom ordering, implement Comparable or pass a Comparator.- Mention stable vs unstable sort details if sorting objects matters.

Example answer:int[] array = {1, 2, 3, -1, -2, 4};Arrays.sort(array);System.out.println(Arrays.toString(array));

11. How Do You Create a Deadlock Scenario Programmatically in Java?

This measures your understanding of concurrency fundamentals, including reasoning about locks, thread scheduling, and diagnostic tools like thread dumps. Interviewers also want to see awareness of prevention strategies.

How to answer:

  • Describe two or more threads that each acquire locks in an opposite order to produce a circular wait.
  • Provide a runnable example demonstrating synchronized blocks causing deadlock.
  • Mention detection via thread dumps and avoidance by lock ordering or timeouts.

Example answer:public class ThreadDeadlock { public static void main(String[] args) throws InterruptedException { Object obj1 = new Object(); Object obj2 = new Object(); Object obj3 = new Object(); Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1"); Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2"); Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3"); t1.start(); Thread.sleep(5000); t2.start(); Thread.sleep(5000); t3.start(); }}class SyncThread implements Runnable { private Object obj1; private Object obj2; public SyncThread(Object o1, Object o2) { this.obj1 = o1; this.obj2 = o2; } @Override public void run() { String name = Thread.currentThread().getName(); System.out.println(name + " acquiring lock on " + obj1); synchronized (obj1) { System.out.println(name + " acquired lock on " + obj1); work(); System.out.println(name + " acquiring lock on " + obj2); synchronized (obj2) { System.out.println(name + " acquired lock on " + obj2); work(); } System.out.println(name + " released lock on " + obj2); } System.out.println(name + " released lock on " + obj1); System.out.println(name + " finished execution."); } private void work() { try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } }}

12. How Can You Find the Factorial of an Integer in Java?

Factorial is a classic recursion example that tests base-case handling and awareness of overflow and recursion depth. Interviewers expect you to state limitations for large n.

How to answer:

  • Show a recursive definition with a base case where n = = 1 returns 1.
  • Mention using long vs BigInteger for significant results and an iterative approach to avoid stack depth issues.

Example answer:public static long factorial(long n) { if (n == 1) return 1; else return (n * factorial(n - 1));}

13. How Do You Reverse a Linked List in Java?

Reversing a linked list tests pointer manipulation and understanding of iterative vs recursive approaches. It shows a grasp of in-place algorithms and edge cases.

How to answer:

  • For Java's LinkedList, you can use descendingIterator to traverse in reverse.
  • For a data-structure interview, explain iterative node pointer reversal with prev, current, next.
  • Show code for whichever interpretation matches the problem statement.

Example answer (using descendingIterator):LinkedList<Integer> ll = new LinkedList<>();ll.add(1);ll.add(2);ll.add(3);System.out.println(ll);LinkedList<Integer> ll1 = new LinkedList<>();ll.descendingIterator().forEachRemaining(ll1::add);System.out.println(ll1);

14. How do you implement a binary search in Java?

Binary search verifies understanding of divide-and-conquer and edge conditions like off-by-one errors. Interviewers want correct index arithmetic and loop invariants.

How to answer:

  • Assume a sorted array, compute the mid safely, compare the key, and move low/high accordingly.
  • Handle not-found by returning -1.
  • Discuss iterative vs recursive implementations and complexity O(log n).

Example answer:public static int binarySearch(int arr[], int low, int high, int key) { int mid = (low + high) / 2; while (low <= high) { if (arr[mid] < key) { low = mid + 1; } else if (arr[mid] == key) { return mid; } else { high = mid - 1; } mid = (low + high) / 2; } if (low > high) { return -1; } return -1;}

15. Write a Java Program that Illustrates Merge Sort

Merge sort checks understanding of divide-and-conquer, stable sorting, and recursion. Interviewers expect a working implementation and discussion of O(n log n) complexity.

How to answer:

  • Explain how to split the array into single elements and then merge the sorted halves.
  • Show a merge helper that merges two sorted arrays.
  • State time and space complexity, and when merge sort is preferred.

Example answer:public class MergeSort { public static void main(String[] args) { int[] arr = { 70, 50, 30, 10, 20, 40, 60 }; int[] merged = mergeSort(arr, 0, arr.length - 1); for (int val: merged) { System.out.print(val + " "); } } public static int[] mergeTwoSortedArrays(int[] one, int[] two) { int[] sorted = new int[one.length + two.length]; int i = 0; int j = 0; int k = 0; while (i < one.length && j < two.length) { if (one[i] < two[j]) { sorted[k] = one[i]; k++; i++; } else { sorted[k] = two[j]; k++; j++; } } if (i == one.length) { while (j < two.length) { sorted[k] = two[j]; k++; j++; } } if (j == two.length) { while (i < one.length) { sorted[k] = one[i]; k++; i++; } } return sorted; } public static int[] mergeSort(int[] arr, int lo, int hi) { if (lo == hi) { int[] br = new int[1]; br[0] = arr[lo]; return br; } int mid = (lo + hi) / 2; int[] fh = mergeSort(arr, lo, mid); int[] sh = mergeSort(arr, mid + 1, hi); int[] merged = mergeTwoSortedArrays(fh, sh); return merged; }}

16. Can You Create a Pyramid of Characters in Java?

Pattern problems test logic, nested loops, and attention to formatting details. Interviewers use them to verify thought process and control flow skills.

How to answer:

  • Explain the nested loop structure that controls rows, spaces, and characters per row.
  • Provide sample code for a simple pyramid and note edge cases for odd/even width.
  • Show how to parameterize height and character.

Example answer:Pattern programs are standard. Use nested loops: outer loop for rows, inner loops for spaces and character printing. Refer to Pyramid Pattern Programs in Java for various patterns.

17. Write a Java Program that Checks If Two Arrays Contain the Same Elements

This test assesses knowledge of collections, sets, and the handling of duplicates and order sensitivity. Interviewers want to see whether you consider unique element sets or multiset equality.

How to answer:

  • Convert arrays to sets to compare unique element equality, or sort arrays and compare for multiset equality.
  • Mention the complexity of each approach and duplicate handling.
  • Provide code using HashSet for unique-element comparison.

Example answer:import java.util.Arrays;import java.util.HashSet;import java.util.Set;public class ArraySameElements { public static void main(String[] args) { Integer[] a1 = {1,2,3,2,1}; Integer[] a2 = {1,2,3}; Integer[] a3 = {1,2,3,4}; System.out.println(sameElements(a1, a2)); System.out.println(sameElements(a1, a3)); } static boolean sameElements(Object[] array1, Object[] array2) { Set<Object> uniqueElements1 = new HashSet<>(Arrays.asList(array1)); Set<Object> uniqueElements2 = new HashSet<>(Arrays.asList(array2)); // if size is different, it means there will be a mismatch if (uniqueElements1.size() != uniqueElements2.size()) return false; for (Object obj: uniqueElements1) { // element not present in both? if (!uniqueElements2.contains(obj)) return false; } return true; }}Outputtruefalse

18. How Do You Get the Sum of All Elements in an Integer Array in Java?

This checks basic iteration and accumulation skills, as well as candidates' knowledge of stream alternatives and overflow considerations.

How to answer:

  • Show a simple loop summing into an int or long accumulator.
  • Mention IntStream.sum() for declarative style and check overflow for large sums.

Example answer:int[] array = { 1, 2, 3, 4, 5 };int sum = 0;for (int i : array) sum += i;System.out.println(sum);

19. How Do You Find the Second-Largest Number in an Array in Java?

This tests single-pass algorithms and careful state updates to track top two values, also handling duplicates and all-negative arrays.

How to answer:

  • Use two variables, highest and secondHighest, initialized to Integer.MIN_VALUE.
  • Iterate once, update both variables when a new highest appears, otherwise update secondHighest if value fits.
  • Handle edge cases such as arrays with fewer than two distinct values.

Example answer:private static int findSecondHighest(int[] array) { int highest = Integer.MIN_VALUE; int secondHighest = Integer.MIN_VALUE; for (int i : array) { if (i > highest) { secondHighest = highest; highest = i; } else if (i > secondHighest) { secondHighest = i; } } return secondHighest;}

20. How Do You Shuffle an Array in Java?

This checks understanding of randomness and uniform swapping patterns, and whether you know Fisher-Yates style shuffling versus naive approaches.

How to answer:

  • Use Random to pick indices and swap elements iteratively.
  • Prefer Fisher-Yates algorithm for uniform shuffle.
  • Show code that swaps current element with a random index.

Example answer:int[] array = { 1, 2, 3, 4, 5, 6, 7 };Random rand = new Random();for (int i = 0; i < array.length; i++) { int randomIndexToSwap = rand.nextInt(array.length); int temp = array[randomIndexToSwap]; array[randomIndexToSwap] = array[i]; array[i] = temp;}System.out.println(Arrays.toString(array));

21. How Can You Find a String in a Text File in Java?

This checks file I/O familiarity and efficient line-by-line scanning. Interviewers want to see proper resource handling and exception awareness.

How to answer:

  • Use Scanner, BufferedReader, or Files.lines to read line by line and check contains().
  • Close resources or use try-with-resources.
  • Return as soon as a match is found for efficiency.

Example answer:boolean findStringInFile(String filePath, String str) throws FileNotFoundException { File file = new File(filePath); Scanner scanner = new Scanner(file); // read the file line by line while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains(str)) { scanner.close(); return true; } } scanner.close(); return false;}

22. How Do You Print a Date in a Specific Format in Java?

This verifies knowledge of date/time APIs and formatting patterns. Interviewers check whether you use modern java.time API alternatives when appropriate.

How to answer:

  • Use SimpleDateFormat for legacy Date formatting, show pattern string.
  • Mention java.time.format.DateTimeFormatter for Java 8+ as a better alternative.

Example answer:String pattern = "MM-dd-yyyy";SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);String date = simpleDateFormat.format(new Date());System.out.println(date); // 06-23-2020

23. How Do You Merge Two Lists in Java?

This checks knowledge of collection operations and how to preserve order or avoid mutation of inputs. Interviewers may probe on duplicates and immutability.

How to answer:

  • Create a new ArrayList from list1 and then call addAll(list2) to preserve the original order.
  • Mention using Streams or collection constructors to control mutability.

Example answer:List<String> list1 = new ArrayList<>();list1.add("1");List<String> list2 = new ArrayList<>();list2.add("2");List<String> mergedList = new ArrayList<>(list1);mergedList.addAll(list2);System.out.println(mergedList); // [1, 2]

24. Write a Java Program that Sorts HashMap by Value

This checks the ability to convert map entries into a sortable structure and knowledge of LinkedHashMap to preserve insertion order. Interviewers look for stream or list-based solutions.

How to answer:

  • Convert entrySet to a list, sort by Entry.getValue(), and then collect into a LinkedHashMap.
  • Mention that HashMap is unordered; LinkedHashMap preserves the new order.
  • Show code clearly sorting by values.

Example answer:import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class SortHashMapByValue { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); scores.put("David", 95); scores.put("Jane", 80); scores.put("Mary", 97); scores.put("Lisa", 78); scores.put("Dino", 65); System.out.println(scores); scores = sortByValue(scores); System.out.println(scores); } private static Map<String, Integer> sortByValue(Map<String, Integer> scores) { Map<String, Integer> sortedByValue = new LinkedHashMap<>(); // get the entry set Set<Entry<String, Integer>> entrySet = scores.entrySet(); System.out.println(entrySet); // create a list since the set is unordered List<Entry<String, Integer>> entryList = new ArrayList<>(entrySet); System.out.println(entryList); // sort the list by value entryList.sort((x, y) -> x.getValue().compareTo(y.getValue())); System.out.println(entryList); // populate the new hash map for (Entry<String, Integer> e : entryList) sortedByValue.put(e.getKey(), e.getValue()); return sortedByValue; }}

25. How Do You Remove All Occurrences of a Given Character from an Input String in Java?

This confirms your comfort with String methods and immutability, as well as your understanding of how replace operations produce new strings.

How to answer:

  • Use String.replace(target, "") for a simple removal.
  • Note strings are immutable and assign the returned value.
  • For single-character removal consider replace(char, char) overloads or building a new string manually.

Example answer:String str1 = "abcdABCDabcdABCD"; str1 = str1.replace("a", ""); System.out.println(str1); // bcdABCDbcdABCD

26. How Do You Get Distinct Characters and Their Count in a String in Java?

These tests use of maps for frequency counting and iteration patterns over characters. Interviewers look for O(n) solutions and clarity.

How to answer:

  • Convert to a char array, iterate and populate Map<Character,Integer> counting occurrences.
  • Return the map or distinct set as needed.
  • Mention case sensitivity and normalization choices.

Example answer:String str1 = "abcdABCDabcd";char[] chars = str1.toCharArray();Map<Character, Integer> charsCount = new HashMap<>();for (char c: chars) { if (charsCount.containsKey(c)) { charsCount.put(c, charsCount.get(c) + 1); } else charsCount.put(c, 1);}System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2, D=1}

27. Can You Prove That a String Object in Java is Immutable Programmatically?

This verifies understanding of Java memory model, string pool semantics, and reference equality. Interviewers want to see clear examples showing that the assignment produces new objects rather than mutating existing ones.

How to answer:

  • Show two references to the same literal and compare with ==.
  • Reassign one reference to another literal and show the other still points to the original.
  • Explain that String methods return new objects rather than modifying in place.

Example answer:String s1 = "Java"; // "Java" String created in pool and reference assigned to s1String s2 = s1; //s2 also has the same reference to "Java" in the poolSystem.out.println(s1 == s2); // proof that s1 and s2 have the same references1 = "Python"; //s1 value got changed above, so how String is immutable?//in the above case a new String "Python" got created in the pool//s1 is now referring to the new String in the pool //BUT, the original String "Java" is still unchanged and remains in the pool//s2 is still referring to the original String "Java" in the pool// proof that s1 and s2 have different referenceSystem.out.println(s1 == s2); System.out.println(s2); // prints "Java" supporting the fact that original String value is unchanged, hence String is immutable

28. Can You Write Some Code to Showcase Inheritance in Java?

This checks OOP fundamentals and the use of extends for single inheritance. Interviewers want to see simple subclassing and method or field reuse.

How to answer:

  • Define a base class with shared members, then use extends to create a subclass that adds behavior.
  • Mention access modifiers and protected vs private visibility as needed.

Example answer:class Animal { String color;}class Cat extends Animal { void meow() { System.out.println("Meow"); }}

29. How Do You Show a Diamond Problem with Multiple Inheritance in Java?

This probes language design knowledge and why Java avoids multiple class inheritance to prevent ambiguity. Interviewers may ask about interfaces and default methods that reintroduce similar issues.

How to answer:

  • Explain the diamond problem: two parents provide the same method, leading to ambiguity.
  • Show that Java disallows class multiple inheritance and provide an example that would not compile.

Example answer:interface I { void foo();}class A implements I { public void foo() {}}class B implements I { public void foo() {}}class C extends A, B { // won't compile public void bar() { super.foo(); }}

30. How Do You Illustrate a Try Catch Example in Java?

Demonstrates exception handling skills and the ability to catch multiple exceptions or use multi-catch. Interviewers check resource handling and checked vs unchecked exceptions.

How to answer:

  • Show try block that can throw, a catch for the specific exception, and demonstrate multi-catch syntax.
  • Mention try-with-resources when dealing with I/O.

Example answer:try { FileInputStream fis = new FileInputStream("test.txt");} catch(FileNotFoundException e) { e.printStackTrace();}From Java 7 onwards, you can also catch multiple exceptions in a single catch block, as shown here:public static void foo(int x) throws IllegalArgumentException, NullPointerException { // some code}public static void main(String[] args) { try { foo(10); } catch (IllegalArgumentException | NullPointerException e) { System.out.println(e.getMessage()); }}

31. Write a Java Program to Show a NullPointerException

This test assesses awareness of null-safety and the occurrence of NPEs. Interviewers expect candidates to show defensive programming and alternative design choices.

How to answer:

  • Provide code that dereferences a null reference to demonstrate NPE.
  • Show a corrected version with a null check or throw an IllegalArgumentException.

Example answer:public static void main(String[] args) { printString(null, 3); }static void printString(String s, int count) { for (int i = 0; i < count; i++) { System.out.println(s.toUpperCase()); // Exception in thread "main" java.lang.NullPointerException }}Safer:static void printString(String s, int count) { if (s == null) return; for (int i = 0; i < count; i++) { System.out.println(s.toUpperCase()); }}

32. How Do You Create a Record in Java?

This checks familiarity with modern Java features and concise POJO creation introduced in recent versions. Interviewers want to see knowledge of generated methods and immutability.

How to answer:

  • Show a record declaration with components; note records are final and provide equals/hashCode/toString/getters.
  • Mention availability since Java 16 as a standard feature.

Example answer:import java.util.Map; public record EmpRecord(int id, String name, long salary, Map<String, String> addresses) {}

33. How Do You Create Text Blocks in Java?

This tests knowledge of language improvements for multiline strings and readability. Interviewers expect awareness of Java 15+ features.

How to answer:

  • Show triple-quote text blocks for multi-line strings.
  • Mention that text blocks include newlines similar to explicit \n sequences.

Example answer:String textBlock = """ Hi Hello Yes""";It behaves like "Hi\nHello\nYes".

34. Show an Example of Switch Expressions and Multi-Label Case Statements in Java

This confirms knowledge of modern switch expressions and cleaner branching added in Java 14+. Interviewers look for clear, concise usage and yield/arrow forms.

How to answer:

  • Show switch expression with multi-label cases, yield, and arrow syntax.
  • Provide examples with both numeric and string cases and mention default handling.

Example answer:int choice = 2;int x = switch (choice) { case 1, 2, 3: yield choice; default: yield -1;};System.out.println("x = " + x); // x = 2String day = "TH";String result = switch (day) { case "M", "W", "F" -> "MWF"; case "T", "TH", "S" -> "TTS"; default -> { if (day.isEmpty()) yield "Please insert a valid day."; else yield "Looks like a Sunday."; }};System.out.println(result); // TTH

35. How Do You Compile and Run a Java Class from the Command Line?

This checks practical tooling knowledge: javac, java, classpath, and package layout understanding. Interviewers want to ensure you can build and run code outside an IDE.

How to answer:

  • Show javac Test.java to compile and java Test to run.
  • Explain package directory mapping and java -cp for external jars.

Example answer:public class Test {public static void main(String args[]) { System.out.println("Hi"); }}Compile:javac Test.javaRun:java TestRecent releases can run .java source directly:java com/example/Test.javaInclude classpath when needed:java -cp .:~/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar com/example/Test.java

36. Create an Enum

Question:

How do you create an enum in Java?

Why you might get asked this: This checks understanding of type-safe enumerations and their features like methods, implemented interfaces, and ordinal behavior. Interviewers may ask when to prefer enum over constants.

How to answer:

  • Show an enum declaration with constant values.
  • Mention enums extend java.lang. Enum can have methods and fields.

Example answer:public enum ThreadStates { START, RUNNING, WAITING, DEAD;}

37. How Do You Use the forEach() Method in Java?

This checks fluency with Java 8+ functional idioms and lambda usage for concise iteration. Interviewers look for the use of method references where appropriate.

How to answer:

  • Show traditional iterator loop, then the concise list.forEach(System.out::print) approach.
  • Mention that forEach accepts a Consumer and does not allow checked exceptions without wrapping.

Example answer:List<String> list = new ArrayList<>();Iterator<String> it = list.iterator();while (it.hasNext()) { System.out.println(it.next());}You can simplify:list.forEach(System.out::print);

38. How Do You Write an Interface with Default and Static Methods?

This verifies knowledge of Java 8 enhancements that let interfaces provide behavior and help with API evolution. Interviewers may ask when to use default vs abstract methods.

How to answer:

  • Show an interface with an abstract method, a default instance method, and a static utility method.
  • Mention default methods provide a fallback implementation, while static methods belong to the interface type.

Example answer:public interface Interface1 { // regular abstract method void method1(String str); default void log(String str) { System.out.println("I1 logging::" + str); } static boolean isNull(String str) { System.out.println("Interface Null Check"); return str == null ? true : "".equals(str) ? true: false; }}

39. How Do You Create a Functional Interface?

This checks lambda readiness and understanding that a single abstract method interface is a functional interface. Interviewers expect @FunctionalInterface usage.

How to answer:

  • Declare an interface with exactly one abstract method and annotate with @FunctionalInterface.
  • This enables the use of lambdas instead of anonymous classes.

Example answer:@FunctionalInterfaceinterface Foo { void test();}

40. Show an Example of Using Lambda Expressions in Java

This confirms the use of lambdas for functional interfaces and concise Runnable or Comparator implementations. Interviewers check readability and intent.

How to answer:

  • Provide a lambda for a standard functional interface like Runnable or Comparator.
  • Mention method references as an alternative when appropriate.

Example answer:Runnable r1 = () -> System.out.println("My Runnable");

41. Show Examples of Overloading and Overriding in Java

This verifies mastery of polymorphism, compile-time vs runtime binding, and correct use of @Override annotation. Interviewers want to see clear differences.

How to answer:

  • Show two methods with the same name but different parameters for overloading.
  • Show a subclass method annotated @Override for overriding behavior.

Example answer:class Foo { void print(String s) { System.out.println(s); } void print(String s, int count) { while (count > 0) { System.out.println(s); count--; } }}class Base { void printName() { System.out.println("Base Class"); }}class Child extends Base { @Override void printName() { System.out.println("Child Class"); }}

42. Guess the Otput: String Identity Comparison Gotcha

String s1 = "abc";String s2 = "abc";System.out.println("s1 == s2 is:" + s1 == s2);

This test evaluates operator precedence and the interaction between + concatenation and == for strings. Interviewers use these to draw attention to the evaluation order.

How to answer:

  • Note that + concatenation happens before == due to left-to-right evaluation of expressions.
  • Recognize the expression is ("s1 == s2 is:" + s1) == s2, comparing two strings by reference.
  • State the Boolean result of that comparison.

Example answer:Outputfalse

43. Guess the Output: Substring with Char as End

String s3 = "JournalDev";int start = 1;char end = 5;System.out.println(s3.substring(start, end));

This checks understanding of substring semantics: start inclusive, end exclusive, and char to int conversion.

How to answer:

  • Explain that substring (start, end) returns characters from index start up to end-1.
  • Convert the character end to its numeric value 5 and compute the substring (1,5).

Example answer:Outputourn

44. Guess the Output: HashSet with Shorts and Removes

HashSet shortSet = new HashSet(); for (short i = 0; i < 100; i++) { shortSet.add(i); shortSet.remove(i - 1);}System.out.println(shortSet.size());

This checks boxing behavior and how remove(Object) uses runtime types; a subtle trap uses Integer vs Short wrapper types.

How to answer:

  • Note adds a box as a Short object; i-1 evaluates to an int and boxes to Integer.
  • Remove (Integer) will not match Short elements, so no removals occur.
  • Conclude size after the loop.

Example answer:Output100

45. Guess the Output: Finally with Infinite Loop or System.exit

try { if (flag) { while (true) { } } else { System.exit(1); }} finally { System.out.println("In Finally");}

This tests finally semantics and when finally executes, including effects of infinite loops and System.exit.

How to answer:

  • If flag true, code never leaves the try block, so finally never executes.
  • If flag false, System.exit terminates JVM and finally does not run.
  • Conclude that no "In Finally" is printed in either controlled case.

Example answer:OutputNo output printed

46. Guess the Output: Equals and Null with Single Bar

String str = null;String str1="abc";System.out.println(str1.equals("abc") | str.equals(null));

This probes understanding of short-circuiting vs non-short-circuiting operators and null dereference timing.

How to answer:

  • Single | evaluates both operands. str1.equals("abc") is true, then str.equals(null) attempts to call equals on null and throws NullPointerException.
  • Explain that a NullPointerException is raised rather than a boolean result being printed.

Example answer:OutputThrows java.lang.NullPointerException

47. Guess the Output: String Concat Immutability

String x = "abc";String y = "abc";x.concat(y);System.out.print(x);

This checks understanding that String.concat returns a new string and does not mutate the original string.

How to answer:

  • State that x.concat(y) creates a new string, but its return value is ignored.
  • x remains "abc" when printed.

Example answer:Outputabc

48. Guess the Output: Arithmetic Precedence and Main Signature

public class MathTest { public void main(String[] args) { int x = 10 * 10 - 10; System.out.println(x); } }

This test evaluates operator precedence and expected arithmetic, while also verifying method signature correctness for the Java entry point.

How to answer:

  • Compute 10 * 10 - 10 = 100 - 10 = 90.
  • Note the provided main is not static; as written it would not run as a normal JVM entry point, but the arithmetic result is 90.

Example answer:Output90

49. Guess the Output: Multi-Catch with Related Exception Types

public class Test { public static void main(String[] args) { try { throw new IOException("Hello"); } catch(IOException | Exception e) { System.out.println(e.getMessage()); } }}

This probes multi-catch rules: you cannot combine related exception types where one is a subtype of the other. Interviewers want to see compile-time understanding.

How to answer:

  • Explain that multi-catch requires disjoint exception types; IOException is a subclass of Exception.
  • Point out that this causes a compile-time error rather than a runtime error.

Example answer:Compilation error: the multi-catch types are not disjoint (IOException is a subtype of Exception)

Related Reading

  • Cybersec
  • Git Interview Questions
  • Front End Developer Interview Questions
  • DevOps Interview Questions And Answers
  • Leetcode Roadmap
  • Leetcode Alternatives
  • System Design Interview Preparation
  • Ansible Interview Questions
  • Engineering Levels
  • jQuery Interview Questions
  • ML Interview Questions
  • Selenium Interview Questions And Answers
  • ASP.NET MVC Interview Questions
  • NodeJS Interview Questions
  • Deep Learning Interview Questions
  • LockedIn

39 Java Intermediate Interview Questions and Answers

Blog image

1. Apart from the Security Aspect, What Are the Reasons Behind Making Strings Immutable in Java?

Interviewers probe design decisions to see if you understand tradeoffs in language design, memory optimization, and concurrency implications. This question tests knowledge of the String intern pool, thread-safety, and how immutability affects collections and caching.

How to answer:

  • Mention String pool and sharing of literals requiring immutability to avoid accidental mutation.
  • Explain thread-safety: immutable objects remove need for synchronization when shared across threads.
  • Describe effects on collections (hash-based keys) and predictable behavior in hashing.

Example answer:Java strings are immutable to enable safe sharing and efficient reuse via the String pool, avoiding copies of identical literal values. Immutability provides inherent thread-safety so strings can be shared across threads without synchronization. Finally, immutable strings make them reliable keys in hash-based collections, preventing changes that would break lookups.

2. Singleton in Java: One Instance, Many Uses

Question:

What is a singleton class in Java? How do you implement a singleton class?

Why you might get asked this:

The question checks understanding of object lifecycle, global access patterns, and thread-safety. Interviewers want to see that you can implement controlled instantiation and discuss concurrency and serialization concerns.

How to answer:

  • Define singleton: a class designed to produce only one instance and provide global access to it.
  • Show a safe implementation and discuss thread-safety and alternatives (double-checked locking, eager initialization, enum).
  • Mention pitfalls: reflection, serialization, classloaders.

Example answer:A singleton ensures only one instance of a class exists and provides a global access point. Use lazy initialization with double-checked locking or prefer enum for a simple, safe singleton. Example (thread-safe, lazy):Approach: lazy init with volatile and double-checked locking.Code:public class MySingleton { private static volatile MySingleton instance; private MySingleton() {} public static MySingleton getInstance() { if (instance == null) { synchronized (MySingleton.class) { if (instance == null) instance = new MySingleton(); } } return instance; }}Commentary: volatile prevents instruction reordering; synchronized block avoids locking every call. For most use cases, an enum-based singleton (enum S { INSTANCE; }) is simpler and handles serialization and reflection better.

3. Array Sizing Pitfalls: Compile vs Runtime Errors

Question:

Which of the following generates a compile-time error? State the reason.

int[] n1 = new int[0];boolean[] n2 = new boolean[-200];double[] n3 = new double[2241423798];char[] ch = new char[20];

Why you might get asked this:

Interviewers want to confirm you know Java array size constraints and the difference between compile-time literal syntax and runtime checks. It tests attention to numeric limits and exceptions.

How to answer:

  • Identify that array sizes must be int values within the Integer range at compile time.
  • Point out which literal is too large for an int and which negative size will cause runtime exception.
  • State resulting errors: compile-time or NegativeArraySizeException at runtime.

Example answer:Line 3 causes a compile-time error: the numeric literal 2241423798 exceeds Java int range so the compiler reports “integer number too large.” Line 2 compiles but throws NegativeArraySizeException at runtime because the array length cannot be negative. Lines 1 and 4 are valid.

4. String vs StringBuffer vs StringBuilder: Pick the Right Mutable Tool

Question:

How would you differentiate between a String, StringBuffer, and a StringBuilder?

Why you might get asked this:

This probes knowledge of immutability, performance, memory, and thread-safety—key topics for core Java and performance-sensitive code.

How to answer:

  • Contrast immutability (String) with mutability (StringBuffer, StringBuilder).
  • State thread-safety: StringBuffer synchronized, StringBuilder not.
  • Compare speed: StringBuilder is fastest for single-threaded concatenation; StringBuffer is slower due to synchronization; String is expensive due to creating new objects.

Example answer:String is immutable and stored in the string pool; use it for fixed text and safe sharing. StringBuilder and StringBuffer are mutable and live on the heap; StringBuilder is faster for single-threaded string construction, while StringBuffer is synchronized for thread-safety. Typical use: StringBuilder for building strings in loops; StringBuffer when multiple threads append to same buffer.

5. Interface vs Abstract Class: Choose the Contract Wisely

Question:

Using relevant properties, highlight the differences between interfaces and abstract classes.

Why you might get asked this:

The question checks your grasp of OOP design in Java, including multiple inheritance, default methods, fields, and visibility—useful for API design decisions.

How to answer:

  • Compare allowed method types: interfaces (default/static/abstract), abstract classes (concrete + abstract).
  • Compare fields: interfaces historically only have public static final; abstract classes can have instance fields with access control.
  • Explain inheritance: multiple interfaces are possible, but single class inheritance is the only option; abstract classes can provide shared state and implementation.

Example answer:Interfaces define a contract and can include abstract methods plus default and static methods; fields are implicitly public static final. Abstract classes can hold instance state, constructors, protected/private members, and concrete methods. Use interfaces for multiple behavioral contracts and abstract classes when you need shared code and state.

6. Illegal Modifiers: Abstract and Final Don't Mix

Question: Is this program giving a compile-time error? If yes, then state the reason and the number of errors it will give. If not, then state the reason.

abstract final class InterviewBit{2. public abstract void printMessage();3. }4. class ScalarAcademy extends InterviewBit{5. public void printMessage(){6. System.out.println("Welcome to Scalar Academy By InterviewBit");7. }8. }9. class ScalarTopics extends ScalarAcademy{10. public void printMessage(){11. System.out.println("Welcome to Scalar Topics By Scalar Academy");12. }13. }public class Main{ public static void main(String[] args) { InterviewBit ib = new ScalarTopics(); ib.printMessage(); }}

Why you might get asked this:

This test assesses your knowledge of Java modifiers and inheritance rules, ensuring you understand incompatible modifiers and how the compiler enforces them.

How to answer:

  • Spot illegal modifier combination: a class cannot be both abstract and final.
  • Note consequence: compiler will produce an error for the illegal modifier and possibly for incorrect inheritance of a final class.

Example answer:Yes, it produces compile-time errors. The class declares both abstract and final, which are incompatible—abstract requires subclassing while final prevents it. Expect at least one compilation error: illegal combination of modifiers. The chain of inheritance would also be affected because a final class cannot be extended.

7. Comparator Basics: Custom Sort Logic

Question:

What is a Comparator in Java?

Why you might get asked this:

Sorting custom objects is a common task; interviewers check if you know how to provide custom ordering separate from natural ordering (Comparable).

How to answer:

  • Define Comparator as a functional interface for custom comparison via compare(T o1, T o2).
  • Use Collections.sort or sort on streams to define ordering independent of an object's natural order.
  • Mention null handling and comparator composition utilities (Comparator.comparing, thenComparing).

Example answer:Comparator is a strategy interface to compare two objects externally. Implement compare(T a, T b) to define ordering, and supply it to Collections.sort(list, comparator) or list.sort(comparator). Java 8+ adds Comparator.comparing and thenComparing for concise, composable comparators.

8. Method Hiding vs Overriding: Static and Private Methods

Question: In Java, static as well as private method overriding is possible. Comment on the statement.

Why you might get asked this: The interviewer wants to confirm you know the difference between overriding and hiding, and how visibility and static context affect polymorphism.

How to answer:- State that static methods are class-level and cannot be overridden; a child can declare the same static signature, but it hides the parent method.- Explain that private methods are not visible to subclasses, so they cannot be overridden; a method with the same name in a subclass is a different method.

Example answer:The statement is false. Static methods are resolved at compile time and can be hidden by a subclass method with the same signature, not overridden. Private methods are not inherited, so a subclass cannot override them; declaring a same-signature private method in subclass defines a separate method.

9. HashSet vs TreeSet: Speed vs Order

Question:

What makes a HashSet different from a TreeSet?

Why you might get asked this:

This checks understanding of core collections, complexity guarantees, ordering guarantees, and object comparison requirements—key for data structure selection.

How to answer:- Explain backing structures: HashSet uses a hash table (unordered), TreeSet uses a red-black tree (sorted).- Mention complexity: HashSet average O(1) for add/contains/remove; TreeSet O(log n).- Note comparison methods and null handling: HashSet uses hashCode/equals; TreeSet uses Comparable or Comparator and does not allow null for elements that require comparison.

Example answer:HashSet stores elements in a hash table for fast average O(1) access and allows one null key; ordering is not guaranteed. TreeSet uses a balanced tree to keep elements sorted and provides O(log n) operations; it requires elements to be Comparable or provide a Comparator and generally disallows null.

10. Secrets in Memory: Char[] vs String for Confidential Data

Question:

Why is the character array preferred over a string for storing confidential information?

Why you might get asked this:

Interviewers want to see awareness of security and memory behavior of Java objects and how immutability affects sensitive data handling.

How to answer:

  • Explain String immutability and string pool lifetime, which prevent strings from being cleared from memory immediately.
  • Show that char[] can be overwritten after use, so sensitive data can be cleared immediately.
  • Mention caveats: even char[] could be swapped to disk by the OS or memory dumps, but it gives more control than String.

Example answer:Strings are immutable and may remain in memory longer (string pool and GC unpredictability), so passwords in String can linger in heap. A char[] lets you overwrite the characters once used, reducing exposure window for memory dumps. Use secure APIs and char[] for password handling when possible.

11. What’s Inside JDK: Tools You Get

Question:

What do we get in the JDK file?

Why you might get asked this:

This verifies that you know the Java toolchain and which components are needed for development versus runtime.

How to answer:

  • Say JDK includes JRE plus development tools such as javac (compiler), javadoc, jar, and debuggers.
  • Clarify JRE contains JVM and standard class libraries; JVM executes bytecode.

Example answer:JDK ships the Java Runtime Environment (JRE) plus development tools: the compiler javac, javadoc, debugger, jar, and other utilities. The JRE bundling includes the JVM and the standard class libraries required to run Java applications.

12. JVM vs JRE vs JDK: Know the Stack

Question:

What are the differences between JVM, JRE, and JDK in Java?

Why you might get asked this:

Interviewers check your understanding of Java’s runtime architecture and which tools are needed for coding versus running applications.

How to answer:

  • Define each: JVM executes bytecode; JRE packages JVM plus core libraries; JDK is JRE plus development tools.
  • State purpose and composition succinctly.

Example answer:JVM is the virtual machine that runs Java bytecode and is platform-specific. JRE packages JVM plus standard libraries to run Java programs. JDK includes the JRE and developer tools like the compiler and debugger to build Java applications.

13. HashMap vs Hashtable: Synchronization and Nulls

Question:

What are the differences between HashMap and HashTable in Java?

Why you might get asked this:

This checks knowledge of legacy vs modern collections, thread-safety, null handling, and iteration behavior.

How to answer:

  • Note synchronization: Hashtable is synchronized; HashMap is not.
  • Describe null handling: HashMap allows one null key and many null values; Hashtable disallows null keys/values.
  • Mention iteration and order: both unordered, but LinkedHashMap preserves insertion order if needed.

Example answer:HashMap is unsynchronized and faster in single-threaded contexts; it allows one null key and multiple null values. Hashtable is synchronized and forbids null keys and values. For predictable insertion order use LinkedHashMap, a HashMap subclass.

14. Reflection in Java: Inspect and Invoke at Runtime

Question:

What is the importance of reflection in Java?

Why you might get asked this:

They want to know if you can use advanced runtime techniques for frameworks, dynamic loading, or tooling, and whether you understand tradeoffs.

How to answer:

  • Define reflection: runtime inspection and invocation of classes, methods, and fields.
  • Give a use case: dynamic method invocation when the type is unknown, frameworks, or dependency injection.
  • Mention downsides: slower calls, weaker type safety, and harder debugging.

Example answer:Reflection allows code inspect types and invoke methods or access fields at runtime, useful for frameworks, plugin loading, or calling unknown methods dynamically. Example: Method m = obj.getClass().getMethod("fooBar"); m.invoke(obj); Reflection is slower, bypasses compile-time checks, and can complicate debugging, so use it sparingly.

15. How to Create Threads: Two Idiomatic Ways

Question:

What are the different ways of using threads?

Why you might get asked this:

Fundamental multithreading knowledge is essential for backend and systems roles, as they require understanding preferred patterns and tradeoffs.

How to answer:

  • Show two common approaches: extend Thread or implement Runnable.
  • State preference: implement Runnable (or use Callable with ExecutorService) to avoid single inheritance limit and allow separation of task from thread.

Example answer:Create threads by extending Thread and overriding run, or by implementing Runnable and passing it to a Thread. Prefer Runnable (or Callable with executors) so you keep class inheritance flexible and separate task logic from thread management. Example Runnable:class MyTask implements Runnable { public void run() { System.out.println("Thread runs..."); }}new Thread(new MyTask()).start();

16. Thread Priorities in Java: What’s Default and Ranges

Question:

What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

Why you might get asked this:

They test your understanding of thread scheduling hints and defaults used by the JVM.

How to answer:

  • List named constants: MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY = 10.
  • State default: threads default to NORM_PRIORITY unless changed.

Example answer:Java defines MIN_PRIORITY (1), NORM_PRIORITY (5), and MAX_PRIORITY (10). The JVM assigns NORM_PRIORITY to new threads by default. Priority is a scheduling hint and behavior can vary across platforms.

17. Program vs Process — code vs execution instance

Question:

What is the difference between the program and the process?

Why you might get asked this:

Interviewers want to ensure you understand OS-level concepts relevant to runtime behavior and resource allocation.

How to answer:

  • Define program as inert code stored on disk; process as a program in execution with resources allocated (memory, registers, threads).
  • Note that a program can spawn multiple processes or threads when executed.

Example answer:A program is static code or binary; a process is an active instance of that program with allocated resources like memory and CPU state. Multiple processes can be created from the same program.

18. Throw vs Throws: When to Declare and When to Raise

Question:

What is the difference between the ‘throw’ and ‘throws’ keywords in Java?

Why you might get asked this:

The question tests exception handling mechanics and how to signal versus declare exceptions in method signatures.

How to answer:

  • Explain throw: used inside code actually to raise an exception instance.
  • Explain throws: part of the method signature to declare that the method can propagate checked exceptions.
  • Show small code showing both in context.

Example answer:throw creates and raises an exception (e.g., throw new IllegalArgumentException()). throws appears in a method declaration to indicate the method may propagate one or more checked exceptions (e.g., void f() throws IOException). Use throw to raise; use throws to advertise exceptions to callers.

19. Constructor vs Method — role and rules

Question:

What are the differences between a constructor and a method of a class in Java?

Why you might get asked this:

This checks object initialization knowledge and practical differences between constructors and ordinary methods.

How to answer:

  • State purpose: the constructor initializes the object state and has no return type; methods define behavior and must have a return type (possibly void).
  • Describe invocation and naming: constructors named after the class and invoked implicitly; methods called explicitly.
  • Mention inheritance and final/detail differences.

Example answer:Constructors initialize new objects, share the class name, and have no return type; methods implement behavior and declare a return type. Constructors run during object creation and cannot be final or inherited; methods are invoked explicitly and can be final or overridden (if allowed).

20. This() vs Super(): Constructor Call Order Rule

Question:

Identify the output of the below Java program and justify your answer.

class Main { public static void main(String args[]) { Scaler s = new Scaler(5); }}class InterviewBit{ InterviewBit(){ System.out.println(" Welcome to InterviewBit "); }}class Scaler extends InterviewBit{ Scaler(){ System.out.println(" Welcome to Scaler Academy "); } Scaler(int x){ this(); super(); System.out.println(" Welcome to Scaler Academy 2"); }}

Why you might get asked this:

This question probes your knowledge of constructor chaining rules and the restriction that either this() or super() must be the first statement.

How to answer:

  • State compilation error occurs because you cannot call both this() and super() in the same constructor body; also, super() must be the first statement.
  • Explain rule: either call this(...) or super(...); if omitted, super() is inserted automatically.

Example answer:This code fails to compile. Java requires a call to super() or this() as the first statement in a constructor; you cannot use both. The Scaler(int) constructor violates that rule by calling this() and then super(), so the compiler rejects it.

21. Java Parameter Passing: Pass-by-Value Explained with Objects

Question:

Java works as a “pass by value” or “pass by reference” phenomenon?

Why you might get asked this:

Many candidates are unclear about Java’s parameter semantics; interviewers check whether you can explain object reference behavior clearly.

How to answer:

  • State Java is strictly pass-by-value: primitives copy values; object references are copied (so both refer to the same object).
  • Show two cases: reassigning the parameter does not affect the caller; mutating the object state does.

Example answer:Java is pass-by-value. For objects, the value copied is the reference, so both caller and callee refer to the same object. Reassigning the parameter inside a method changes only the local copy of the reference, but modifying the object's fields affects the original object.

22. IS-A Relationship: Inheritance Expressed Simply

Question:

What is the ‘IS-A ‘ relationship in OOPs Java?

Why you might get asked this:

Interviewers check understanding of inheritance semantics and proper OO modeling.

How to answer:

  • Define IS-A as inheritance: subclass is a specialized form of the superclass.
  • Provide a concise example mapping to real-world types.

Example answer:IS-A denotes inheritance: class SmartTV IS-A Television, meaning SmartTV extends Television and inherits its behavior and properties. Use IS-A when a subclass truly represents a subtype of the parent.

23. Which to Use When You Update a Lot: String or StringBuffer?

Question:

Which among String or String Buffer should be preferred when there are a lot of updates required to be done in the data?

Why you might get asked this:

The question probes performance and object creation costs related to immutable vs mutable types.

How to answer:

  • Recommend mutable buffer types for frequent modifications to avoid creating many String objects.
  • Prefer StringBuilder for single-threaded updates, StringBuffer only if thread-safety is required.

Example answer:

Use StringBuffer or StringBuilder rather than String when many updates are needed. StringBuilder is fastest for single-threaded use; StringBuffer adds synchronization for multi-threaded contexts.

24. Prevent Serializing a Field: Use Transient

Question:

How do you prevent the serialization of class attributes in Java?

Why you might get asked this:

This checks familiarity with Java serialization controls and how to avoid persisting sensitive or non-serializable data.

How to answer:

  • Use the transient keyword on fields you do not want serialized.
  • Optionally implement writeObject/readObject for finer control or mark class as Externalizable for custom behavior.

Example answer:

Mark fields you want excluded from default serialization as transient:public class Example implements Serializable { private transient String secret; private String name;}Transient fields are skipped by default serialization. For custom serialization control, implement private writeObject/readObject.

25. Missing Static on Main: Runtime Error

Question:

What happens if the static modifier is not included in the main method signature in Java?

Why you might get asked this:

The interviewer wants to confirm you know how the JVM locates the entry point and that static is required for the JVM to call main without an instance.

How to answer:

  • Although there is no compile error, the JVM cannot find the public static void main(String[] args) method, resulting in a NoSuchMethodError at runtime.
  • Mention that the standard JVM startup does not use alternative entry points.

Example answer:

If the main method is not static, the program compiles, but the JVM throws a NoSuchMethodError at startup because it expects a public static void main(String[] args). The JVM cannot instantiate an arbitrary class to call a nonstatic main.

26. Overloaded Mains: JVM Picks the Standard Signature

Question:

Consider the below program, identify the output, and also state the reason for that.public class Main{public static void main(String[] args) { System.out.println(" Hello. Main Method. ");}public static void main(int[] args) { System.out.println(" Hello. Main Method2. ");}}

Why you might get asked this:

This checks whether you know JVM entry point selection and method overloading rules.

How to answer:

  • Explain JVM looks for main(String[]) and ignores overloaded variants for startup.
  • State the program prints the String[] main output.

Example answer:Output: Hello. Main Method. The JVM calls public static void main(String[]), so the overloaded main(int[]) is a valid method, but not used as the program entry point.

27. Can You Make Main a Daemon? No

Question:

Can we make the main() thread a daemon thread?

Why you might get asked this:

This gauges understanding of daemon vs non-daemon threads and their lifecycle impact on JVM termination.

How to answer:

  • The main thread is created by JVM as a non-daemon and cannot be converted into a daemon using Thread.setDaemon because setDaemon must be called before thread start, and main is already started.
  • Note that the main can spawn daemon threads, but main itself remains non-daemon.

Example answer:

No. The main thread is created by the JVM as a non-daemon thread and cannot be turned into a daemon after it starts. You can create daemon worker threads from main, but main itself stays non-daemon.

28. Multiple Mains in One Class: Overload Allowed, Duplicates Not

Question:

What happens if there are multiple main methods inside one class in Java?

Why you might get asked this:

They want to see whether you distinguish between overloading from duplicate definitions.

How to answer:

  • Clarify that overloaded main methods with different signatures compile fine; JVM will call public static void main(String[]).
  • Duplicate methods with identical signatures cause compile-time error due to duplicate definition.

Example answer:

You can overload main with different parameter types and it will compile; the JVM always calls public static void main(String[]). If you declare multiple main methods with the exact same signature, the compiler reports a duplicate method error.

29. Object Cloning: Shallow vs Deep and Cloneable

Question:

What do you understand by Object Cloning and how do you achieve it in Java?

Why you might get asked this:

This checks whether you know cloning mechanics, Cloneable marker, clone() semantics, and pitfalls of shallow copying.

How to answer:

  • Define cloning as creating a copy of an object; mention Object.clone and Cloneable marker interface.
  • Show example override calling super.clone() and discuss shallow copy vs deep copy and why clone() is often avoided in favor of copy constructors or factory methods.

Example answer:

Cloning creates a copy of an object. Implement Cloneable and override clone:@Overrideprotected Object clone() throws CloneNotSupportedException { return super.clone(); // shallow copy}super.clone() does a field-by-field shallow copy. For mutable contained objects you must implement deep cloning manually or prefer copy constructors or serialization-based copying.

30. Header: Exception Propagation: Bubble Up the Call Stack

Question:

How does an exception propagate in the code?

Why you might get asked this:

Interviewers check understanding of try-catch semantics and stack unwinding during exceptions.

How to answer:

  • Describe: when thrown, JVM searches for matching catch in current method; if none found, the exception propagates up the call stack to the caller, and so on.
  • State program terminates if no matching handler is found in main.

Example answer:

When an exception is thrown, the runtime searches for a matching catch in the current method. If absent, it unwinds the stack, passing the exception to each caller until a handler is found. If no handler is found, the exception reaches main and the JVM terminates the program.

31. Unhandled Exceptions: Runtime Effects

Question:

How do exceptions affect the program if it doesn't handle them?

Why you might get asked this:

This tests practical understanding of stability, user experience, and effects of uncaught exceptions.

How to answer:

  • Unhandled runtime exceptions bubble up and typically terminate the thread or the JVM if thrown on the main thread.
  • Describe user-facing impact (crash) and need for proper handling and logging.

Example answer:

Unhandled exceptions bubble up and, if not caught anywhere, terminate the thread; an uncaught exception on the main thread usually terminates the JVM and crashes the application. Proper handling avoids crashes and enables graceful error recovery.

32. Try Without Catch: Finally or Throws Allowed

Question:

Is it mandatory for a catch block to be followed after a try block?

Why you might get asked this:

This checks whether you know valid try statement forms in Java.

How to answer:

  • State try must be followed by either catch or finally (or both). A try without catch must have finally.
  • Mention method can declare throws to propagate exceptions, but try still needs catch or finally.

Example answer:

No. A try block must be followed by at least one catch or a finally block. You can have try...finally without catch to ensure cleanup while letting exceptions propagate.

33. Header: Finally Always Runs (Except System.exit)

Question:

Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?public int someMethod(int i){ try{ //some statement return 1; }catch(Exception e){ //some statement return 999; }finally{ //finally block statements }}

Why you might get asked this:

This verifies your understanding of finally semantics and interaction with return statements.

How to answer:

  • The state is finally run after the try or catch block executes and before the method returns.
  • Note one exception: if System.exit is invoked or the JVM crashes, finally may not execute.

Example answer:

Yes. The finally block executes even if the try or catch contains a return; its code runs before the actual return value is handed to the caller. The only typical exception is when the JVM exits via System.exit or the process is killed.

34. Constructor chaining — call one constructor from another

Question:

Can you call a constructor of a class inside another constructor?

Why you might get asked this:

This checks knowledge of constructor chaining and the this() call rules.

How to answer:

  • Confirm you can use this(...) to call another constructor in the same class; it must be the first statement.
  • Mention use cases: reduce duplication, centralize initialization.

Example answer:

Yes. Use this(args) to chain constructors inside the same class, and that call must be the first statement. Constructor chaining centralizes initialization and reduces duplicate code.

35. ArrayList Storage Model: References Not Contiguous for Objects

Question:

Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

Why you might get asked this:

The interviewer wants to verify internal representation of primitive arrays vs ArrayList of objects and implications for memory and performance.

How to answer:

  • Explain arrays store primitives or object references contiguously; primitives stored directly, object arrays store references contiguously while objects live elsewhere on the heap.
  • Point out ArrayList wraps an Object[] internally that holds references, so objects themselves are not contiguous.

Example answer:

An array of primitives stores values contiguously so memory is packed. ArrayList uses an internal Object[] to hold references; those references are contiguous, but the actual object instances live elsewhere on the heap. Thus, ArrayList doesn’t guarantee contiguous storage of object data.

36. Why Does the Array Index Start at 0: Address Calculation Efficiency

Question:

Why does the Java array index start with 0?

Why you might get asked this:

This checks understanding of low-level address arithmetic and historical language design decisions.

How to answer:

  • Explain index-0 simplifies address calculation: elementAddress = base + index * elementSize.
  • Mention that 1-based indexing would require subtracting 1 from each access, adding overhead.

Example answer:

Index 0 lets the address formula be base + index * size, avoiding an extra subtraction. That simplifies indexing arithmetic and marginally improves performance for array access.

37. Remove Performance: Linked List vs Array Shifting

Question:

Why is the remove method faster in the linked list than in an array?

Why you might get asked this:

This checks understanding of data structure tradeoffs and algorithmic costs for removal.

How to answer:

  • Explain linked list removal adjusts pointers and can be O(1) if the node reference known; array-based structures require shifting elements O(n).
  • Note ArrayList remove at front triggers an array copy to maintain a contiguous layout.

Example answer:

LinkedList removal is faster for known node positions because it re-links neighbor pointers and can run in O(1). In an array or ArrayList, removing an element requires shifting subsequent elements left, which takes O(n) time.

38. How Many Overloaded Add() and AddAll() Methods Are Available in the List Interface? Describe the Need and Uses.

This test assesses your familiarity with the List API, specifically when to use indexed insertion versus bulk operations.

How to answer:

  • There are four overloads total: add(E), add(int, E), addAll(Collection<? extends E>), and addAll(int, Collection<? extends E>).
  • Explain the following use cases: append, insert at index, append collection, and insert collection at index.

Example answer:

List provides add(E) to append, add(int, E) to insert at a position, addAll(Collection) to append all elements from a collection, and addAll(int, Collection) to insert a collection starting at a given index. Use index variants when order matters or when merging lists at a specific position.

39. How Does the Size of ArrayList Grow Dynamically? And Also State How It is Implemented Internally.

Why you might get asked this: Interviewers expect you to know how dynamic arrays work, amortized cost, and internal reallocation strategy for performance tuning.

How to answer:

  • Explain ArrayList holds an internal Object[] capacity; when capacity is exceeded, it creates a larger array (typically grows by 50% or similar), copies elements, and assigns the new array.
  • Note amortized add is O(1) though individual resizes are O(n); removals cause shifting.

Example answer:

ArrayList uses an internal Object[] buffer. When an add would exceed capacity, it allocates a larger array (oldCapacity + oldCapacity/2), copies elements, and inserts the new element. Resizing is costly when it happens, but the amortized cost of repeated additions is constant because copies happen infrequently.

38 Java Interview Questions and Answers For Experienced

Blog image

1. Although Inheritance is a Popular OOPs Concept, It is Less Advantageous than Composition. Explain.

Interviewers test whether you understand object relationships, coupling, testability, and maintainability. This question probes design judgment and practical trade-offs in object-oriented design.

How to answer:

  • Explain composition as "has-a" and inheritance as "is-a", focusing on coupling and flexibility.
  • Give concrete reasons: multiple behavior reuse, encapsulation, easier unit testing, and reduced fragility to superclass changes.
  • Provide a short code example showing how composition avoids a brittle inheritance change and explain the difference.

Example answer:

Composition builds objects by containing other objects; inheritance ties a subclass directly to a superclass. Composition keeps coupling low: you can swap or mock the composed object for testing and extend behavior without changing a class hierarchy. In Java, single inheritance limits reuse; composition composes behavior from multiple helper objects. Code example:class Reader { int read() { return 0; } }class Writer { void write(int v) {} }class FileHandler { private final Reader reader; private final Writer writer; public FileHandler(Reader r, Writer w) { reader = r; writer = w; } public void process() { int v = reader.read(); writer.write(v); }}

Supporting commentary: This shows how independent Reader and Writer are injected into FileHandler. Changes in Reader or Writer don’t force changes to FileHandler beyond the interface, and you can mock either for unit tests.

2. What is the Difference Between ‘>>’ and ‘>>>’ Operators in Java?

The interviewer checks your knowledge of bitwise operators, sign handling, and low-level behavior of integer types in Java. This matters for numeric algorithms and performance-sensitive code.

How to answer:

  • Define >> as arithmetic (signed) right shift that preserves the sign bit.
  • Define >>> as logical (unsigned) right shift that fills high bits with zeros.
  • Give a quick numeric example showing behavior with negative numbers.

Example answer:

>> keeps the sign: it shifts bits right and replicates the sign bit to preserve negativity. >>> shifts right and always inserts zeros on the left, so a negative value becomes a large positive value after >>>.

Example:

int a = 8; // 0000...1000int b = -8; // 1111...1000System.out.println(a >> 1); // 4System.out.println(b >> 1); // -4 (sign preserved)System.out.println(a >>> 1); // 4System.out.println(b >>> 1); // large positive (sign bit cleared)This explains why you choose >>> only when you need a logical shift.

3. What Are Composition and Aggregation? State the Difference

Interviewers want to see if you understand object relationships and lifecycle responsibilities between objects. That guiding understanding influences architecture and memory ownership decisions.

How to answer:

  • Define aggregation as a weak "has-a" where contained objects can outlive the container.
  • Define composition as a strong "has-a" where parts are owned and destroyed with the container.
  • Give clear examples: university-department (composition) vs department-professor (aggregation).

Example answer:

Aggregation means a container holds references to other objects but doesn’t own their lifecycle; those parts can exist independently. Composition gives ownership: when the container is destroyed, the owned parts are also destroyed. For instance, a University composed of Departments implies that departments cannot exist without the university; a Department aggregating Professors implies that professors can associate with other departments or exist independently.

4. How is the Creation of a String Using New() Different from That of a Literal?

Candidates need to know memory use, interning, and identity vs equality with Strings in Java. Misunderstanding leads to bugs and wasted memory.

How to answer:

  • Explain that string literals go to the String constant pool and are interned.
  • Explain new String(...) always creates a new heap object, even with same content.
  • Mention == compares references while equals() compares content.

Example answer:

A literal like "Hello" is placed in the String pool; repeated literals reuse the same object. new String("Hello") allocates a new String on the heap with identical content but a distinct reference. So "a" == "a" is true, while new String("a") == new String("a") is false; always use equals() to compare content.

5. How is the ‘New’ Operator Different from the ‘newInstance()’ Operator in Java?

This exposes familiarity with reflection, runtime instantiation, and checked exceptions. It also tests when dynamic instantiation is appropriate.

How to answer:

  • Say new requires a known compile-time class name; it’s straightforward and throws no checked exception.
  • Say Class.newInstance() (or Constructor.newInstance()) creates objects via reflection and can throw checked exceptions; class may be unknown until runtime.
  • Note newInstance requires accessible zero-arg constructor unless you use Constructor APIs.

Example answer:

Use new when you know the type at compile time. Use Class.forName(...).newInstance() or Constructor.newInstance(...) when the class name comes at runtime. Reflection-based instantiation can throw InstantiationException, IllegalAccessException, or InvocationTargetException and typically needs a no-arg constructor or explicit Constructor handling.

6. Is Exceeding the Memory Limit Possible in a Program despite Having a Garbage Collector?

Interviewers want to verify you know GC mechanics and common heap misuses that still cause OOM. This shows practical debugging ability.

How to answer:

  • Explain GC reclaims only unreachable objects; reachable but unused objects still consume memory.
  • Give examples: accidental strong references, unbounded caches, and infinite loops that keep allocating.
  • Mention that GC may not free enough memory quickly enough or reach unreachable objects if references remain.

Example answer:

Garbage collection reclaims only objects that are no longer reachable. If your code keeps references (for example, in a list or cache), objects remain live and the heap can fill. Infinite allocation loops that never drop references will exhaust memory despite GC. Example:List<String> list = new LinkedList<>();while(true) list.add(new String("leak"));This loop keeps references, so GC cannot reclaim and OOM occurs.

7. Why is Synchronization Necessary? Explain with the Help of a Relevant Example

Interviewers check your understanding of concurrency hazards like race conditions and the tools Java provides to guard shared state.

How to answer:

  • Define the race condition: unsynchronized concurrent access leads to inconsistent state.
  • Show how synchronized or locks serialize access to critical sections so updates are atomic and visible.
  • Provide a compact code example showing wrong and corrected behavior.

Example answer:

Without synchronization, two threads can read-modify-write the same field and overwrite each other’s changes. Marking the method or block synchronized ensures only one thread updates the counter at a time, preserving correctness.

Bad:
class Counting { private int c; public int inc(){ c = c + 1; return c; } }

Good:
class Counting { private int c; public synchronized int inc(){ c = c + 1; return c; } }With synchronized, one thread increments, then the next sees the updated value, so counts don’t get lost.

8. In the Given Code Below, What is the Significance of ...?

public void fooBarMethod(String... variables){ // method code}

The question verifies familiarity with Java method signatures and flexible APIs; varargs are common in library design.

How to answer:

  • Explain that ... defines a varargs parameter allowing zero or more arguments of that type.
  • Mention Java represents it as an array inside the method.
  • Show call forms: multiple arguments, zero arguments, or an explicit array.

Example answer:

String... variables means the method accepts any number of String arguments; inside the method variables is a String[]. You can call fooBarMethod("a","b"), fooBarMethod(), or fooBarMethod(new String[]{"a","b"}). Use for-each to iterate.

9. What Will Be the Output of the Below Java Program, and Define the Steps of Execution of the Java Program with the Help of the Below Code?

[class InterviewBit with static/instance blocks and prints, code omitted for brevity]

Interviewers probe your knowledge of class loading, static initialization order, instance initialization, and constructor invocation. Misunderstanding causes surprising behavior in real code.

How to answer:

  • State the exact printed output in order.
  • Explain class loading: static fields default-initialized, then static blocks run top-to-bottom, and main runs; for each object creation instance fields and instance blocks run top-to-bottom then constructor.

Example answer:

Output:

Static Block 1. Value of j = 0Static method.Static Block 2. Value of j = 10Instance Block 1. Value of i = 0Instance Block 2. Value of i = 5Instance method.Welcome to InterviewBit

Explanation: JVM assigns default values, executes static blocks and static initializers in order, then main creates the object. For each object JVM initializes instance fields and instance blocks top-to-bottom before calling the constructor, which produces the instance prints shown.

10. Define System.out.println().

The question checks if you know standard I/O details and Java core classes, proving familiarity with the standard library.

How to answer:

  • StatY System is java.lang.System, out is a static PrintStream field, and println is a PrintStream method that prints with a newline.
  • Mention PrintStream handles character encoding and may flush depending on configuration.

Example answer:System is a core class. out is a public static final PrintStream instance on System. println(...) is a PrintStream method that writes the argument and then a line separator to the standard output stream. Under the hood PrintStream formats primitives and strings and may auto-flush on newline when connected to a console.

11. Can You Explain the Java Thread Lifecycle?

Thread lifecycle knowledge is essential for correct multithreaded design, coordinating waits, and avoiding deadlocks. Interviewers want to see you map theory to practical state transitions.

How to answer:

  • Describe states: New, Runnable (ready), Running, Blocked/Waiting, Timed Waiting, and Terminated.
  • Explain transitions: start() moves New->Runnable, scheduler moves Runnable->Running, wait/blocked cause non-runnable, notify/interrupt can resume, run ends -> Terminated.
  • Mention causes of Blocked vs Waiting (synchronization vs wait/park).

Example answer:A thread starts in New; calling start() makes it Runnable. The scheduler runs it (Running). If it tries to enter a locked synchronized block held by another thread, it goes Blocked. If it calls wait(), sleep(), or join() it goes Waiting or Timed Waiting until notified or the timeout expires. When run() returns the thread is Terminated. Understanding these states helps you design correct synchronization and avoid misplaced sleep or busy-wait.

12. What Could Be the Tradeoff Between the Usage of an Unordered Array Versus the Usage of an Ordered Array?

Interviewers want to see awareness of algorithmic trade-offs and how data structure choices affect asymptotic cost for common operations.

How to answer:

  • Show unordered: O(1) insertion (append), O(n) search.
  • Show ordered: O(n) insertion (shift), O(log n) search via binary search.
  • Recommend choice depends on workload: many searches → ordered; many inserts → unordered.

Example answer:

An unordered array gives fast insertions (amortized O(1) for append) but linear search O(n). An ordered array enables binary search O(log n) but requires shifting elements on insert O(n). Pick ordered when reads dominate and insertions are rare; pick unordered for frequent writes.

13. Is It Possible to Import the Same Class or Package Twice in Java, and What Happens to It During Runtime?

This checks if you know Java compilation behavior and how imports affect runtime class loading.

How to answer:

  • State that duplicate imports are permitted syntactically, but redundant.
  • Explain the JVM loads classes once; import statements are a compile-time convenience only.

Example answer:

You can import the same class or package multiple times; the compiler treats duplicates as redundant. At runtime, class loading occurs as needed, and each class is loaded once per classloader, so duplicate imports have no runtime effect.

14. Do Package Wildcards Import Subpackages? Clarifying Java Import Rules

In case a package has sub-packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

Why you might get asked this:

The interviewer tests precise knowledge of Java’s import semantics, which affects modularization and package organization.

How to answer:

  • State clearly that importing com.main.* imports only classes in that package, not subpackages.
  • Explain each subpackage must be imported explicitly or imported via its own wildcard.

Example answer:

No. com.myMainPackage.* brings in types declared directly in com.myMainPackage. Subpackages are different packages and must be imported explicitly, for example com.myMainPackage.mySubPackage.*.

15. Will the Finally Block Be Executed If the Code System.exit(0) is Written at the End of Try Block?

This checks knowledge of JVM termination behavior and guaranteed final execution under normal circumstances.

How to answer:

  • State that System.exit terminates the JVM and prevents normal finally execution.
  • Note that shutdown hooks may still run under some conditions, but finally blocks do not run after immediate exit.

Example answer:

No. System.exit(0) initiates JVM termination; finally, blocks are not executed after this immediate termination. Use shutdown hooks if you need cleanup on JVM termination.

16. What do you understand by marker interfaces in Java?

Interviewers assess knowledge of historical Java patterns, type metadata, and design choices for tagging behavior.

How to answer:

  • Define marker interface as an interface with no methods used to tag classes for special treatment.
  • Provide examples of Serializable and Cloneable, and explain how runtime or libraries verify instanceof or utilize behavior based on these markers.

Example answer:

Marker interfaces contain no methods or fields and mark classes for special runtime handling. For example, Serializable tells the JVM or libraries this object can be serialized; code checks the type and enables behavior accordingly.

17. Explain the Term “Double Brace Initialisation” in Java?

The interviewer wants to see if you know compact initialization idioms and their costs, like anonymous inner class creation and hidden references.

How to answer:

  • Explain first brace creates an anonymous subclass; second brace is an instance initializer block used to add elements.
  • Mention downsides: generates an extra class, retains hidden reference to the outer instance, affects serialization and GC.
  • Give a short code example and a caution.

Example answer:

Double brace initialization uses new Type() {{ ... }}. The outer braces create an anonymous subclass; the inner braces run an instance initializer to populate the instance. Example:Set<String> s = new HashSet<String>() {{ add("a"); add("b");}};This is concise, but it creates an extra class and can keep a reference to the enclosing instance, which may complicate garbage collection and serialization.

18. Why is it said that the length() method of String class doesn't return accurate results?

This validates your understanding of character encoding (UTF-16), surrogate pairs, and how Java represents Unicode in Strings.

How to answer:

  • Explain Java uses UTF-16; length() returns number of UTF-16 code units, not Unicode code points.
  • Show that supplementary characters (outside BMP) are represented by two code units, so length() counts 2 for one perceived character.
  • Mention codePointCount() and offsetByCodePoints() as correct alternatives when counting actual characters.

Example answer:

String.length() returns the count of UTF-16 code units. Characters outside the Basic Multilingual Plane use two code units (surrogate pair), so a single user-perceived character may have length 2. Use codePointCount(0, s.length()) to get true Unicode code points.

19. What is the Output of the Below Code and Why?

public class InterviewBit{ public static void main(String[] args) { System.out.println('b' + 'i' + 't'); }} Why you might get asked this: This checks understanding of char type arithmetic vs string concatenation and basic type promotion rules.

How to answer:

  • Explain char literals are numeric (UTF-16/ASCII) and are promoted to int during + operations.
  • Sum numeric values and display result; if they were string literals you'd get concatenation.

Example answer:

Each char is promoted to an int and added: 'b' (98) + 'i' (105) + 't' (116) = 319. So the program prints 319. If the literals were "b" + "i" + "t" the result would be "bit".

20. What Are the Possible Ways of Making Object Eligible for Garbage Collection (GC) in Java?

Interviewers test your grasp of reachability, reference semantics, and how code can create or remove object lifetimes. This matters for memory management.

How to answer:

  • Null out references when no longer needed.
  • Reassign references to other objects so the previous object becomes unreachable.
  • Create islands of isolation where objects only reference each other and nobody else references them.

Example answer:

Set an object reference to null, reassign the reference to another object, or create isolated object graphs that have no external references. For example:obj = null;orobj = anotherRef;If two objects reference each other but no external reference exists, both become eligible for GC.

21. Multidimensional Arrays and GC: Counting Unreachable Arrays

In the below Java Program, how many objects are eligible for garbage collection? class Main{ public static void main(String[] args){ int[][] num = new int[3][]; num[0] = new int[5]; num[1] = new int[2]; num[2] = new int[3]; num[2] = new int[5]; num[0] = new int[4]; num[1] = new int[3]; num = new int[2][]; }} Why you might get asked this: This checks ability to reason about references and object reachability in multidimensional arrays, a common tricky topic in Java interviews.

How to answer:

  • Track each array allocation and whether any live reference points to it at the end.
  • Remember num itself is reassigned at the end to a new array, so prior elements can become unreachable.

Example answer:

Seven objects become eligible. Allocations: initial outer int[3] and later inner arrays. After the reassignments, the first outer array’s inner arrays that were overwritten and the original outer array references become unreachable. Num is reassigned to a new outer array leaving the earlier arrays eligible for GC.

22. What is the Best Way to Inject Dependency? Also, State the Reason

Interviewers test knowledge of DI patterns, immutability, and how injection choices affect testability and API clarity.

How to answer:

  • Recommend constructor injection for mandatory dependencies for immutability and clear invariants.
  • Use setter injection for optional dependencies or circular references, noting trade-offs.
  • Mention frameworks (Spring) support both, and that constructor injection enables easier unit testing.

Example answer:

Prefer constructor injection for mandatory dependencies since it enforces required collaborators at creation and supports immutable fields and simpler testing. Use setter injection for optional dependencies or when you need to break cycles; document defaults clearly.

23. How Can We Set the Spring Bean Scope? And What Supported Scopes Does It Have?

This confirms practical Spring knowledge and howthe bean lifecycle affects concurrency and state.

How to answer:

  • Show ways to set scope: @Scope annotation or scope attribute in XML.
  • List common scopes: singleton, prototype, request, session, globalSession.
  • Mention singleton is default in Spring container.

Example answer:

You set scope with @Scope("prototype") or in XML with <bean scope="prototype">. Supported scopes include singleton, prototype, request, session, and globalSession. Use singleton for shared stateless beans and prototype when each injection needs a new instance.

24. What Are the Different Categories of Java Design Patterns?

Interviewers test familiarity with standard design patterns and the vocabulary used to discuss architecture and code reuse.

How to answer:

  • Name categories: Creational, Structural, Behavioral, and J2EE patterns.
  • List representative patterns for each category.

Example answer:

  • Creational: Factory Method, Abstract Factory, Builder, Prototype, Singleton.
  • Structural: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
  • Behavioral: Interpreter, Template Method, Chain of Responsibility, Command, Iterator, Strategy, Visitor.
  • J2EE patterns: MVC, DAO, Front Controller, Intercepting Filter, Transfer Object.

25. What is a Memory Leak? Discuss Some Common Causes of It.

The interviewer wants to know if you can diagnose long-running application issues and avoid patterns that prevent GC from reclaiming memory.

How to answer:

  • Define memory leak as objects that remain reachable but are no longer helpful, preventing GC from reclaiming them.
  • List common causes: unbounded caches, listeners not removed, static collections, accidental strong references, poorly implemented maps.
  • Suggest mitigation: use weak references, clear collections, or profiling tools.

Example answer:

  • A memory leak occurs when unused objects remain reachable and the GC cannot reclaim them.
  • Common causes: unbounded caches, holding references in static collections, forgotten listeners, or subtle reference chains.
  • Detect leaks with heap dumps and profilers and fix by removing references, using weak/soft references, or bounding caches.

26. Assume a Thread Has a Lock on It, Calling the Sleep() Method on that Thread Will Release the Lock?

This tests nuances of thread behavior: that sleeping does not relinquish monitors while wait() does. Misunderstanding causes concurrency bugs.

How to answer:

  • State that Thread.sleep() does not release any locks; the thread holds the monitor while sleeping.
  • Contrast with Object.wait(), which releases the monitor and waits to be notified.

Example answer:No. sleep() pauses the current thread for a specified duration, retaining any monitors it holds. To release a monitor and wait for notification use wait(), which releases the monitor and puts the thread in the waiting set.

27. Check If a Given String is Palindrome Using Recursion

This assesses recursion reasoning, base case handling, and string manipulation skills.

How to answer:

  • Explain recursive approach: compare first and last chars and recurse on substring excluding them.
  • Describe base cases: An empty or single-character string is a palindrome.
  • Provide code that avoids excPssive substring allocations when possible.

Example answer:

Approach:
compare first and last characters; if they match, recurse on the substring between them; stop when length <= 1. Code:public static boolean isPalindrome(String s) { if (s == null) return false; return isPalHelper(s, 0, s.length() - 1);}private static boolean isPalHelper(String s, int left, int right) { if (left >= right) return true; if (s.charAt(left) != s.charAt(right)) return false; return isPalHelper(s, left + 1, right - 1);}

Commentary: This avoids creating new substring objects and runs in O(n) time with O(n) recursion depth.

28. Write a Java Program to Print Fibonacci Series Using Recursion

The interviewer checks recursion skills and understands performance trade-offs of naive recursion versus iterative or tail-recursive forms.

How to answer:

  • Explain naive recursion has exponential cost; prefer a helper method to generate sequence iteratively or tail-recursively.
  • Provide code that prints an initial seed and then uses a recursive helper to continue.

Example answer:

Approach:
print initial 0 and 1, then recursively print the next numbers using two previous values as parameters. Code:public static void printFib(int a, int b, int n) { if (n == 0) return; System.out.print(a + b + " "); printFib(b, a + b, n - 1);}public static void main(String[] args) { System.out.print("0 1 "); printFib(0, 1, 10);}

Commentary: This runs in O(n) time and avoids the exponential cost of naive recursion.

29. Write a Java Program to Check If the Two Strings Are Anagrams

This probes string manipulation and algorithmic choices such as sorting vs counting and complexity trade-offs.

How to answer:

  • Describe checking lengths first, then either sort both char arrays and compare or count character frequencies using an int[256] (or a Map) for a Unicode-safe approach.
  • Provide code for the sorting approach or frequency approach.

Example answer:

Approach:
Sort both strings' character arrays and compare them. Runtime O(n log n) due to sort; a frequency array yields O(n). Code (sort):public static boolean isAnagram(String s1, String s2) { if (s1.length() != s2.length()) return false; char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); return Arrays.equals(a1, a2);}

Commentary: Use frequency counting for large alphabets or to get O(n) time.

30. Write a Java Program to Find the Factorial of a Given Number

This evaluates basic loop constructs, overflow awareness, and type selection for numeric calculations.

How to answer:

  • Show iterative solution using long and mention overflow for large inputs.
  • Optionally show BigInteger for arbitrary precision.

Example answer:

Iterative code:

long factorial(int n) { long result = 1L; for (int i = 2; i <= n; i++) result *= i; return result;}For large n use java.math.BigInteger:BigInteger fact(BigInteger n) { BigInteger r = BigInteger.ONE; for (BigInteger i = BigInteger.TWO; i.compareTo(n) <= 0; i = i.add(BigInteger.ONE)) r = r.multiply(i); return r; }

31. Given An Array Of Non-Duplicating Numbers From 1 To N, Where One Number is Missing, Write an Efficient Java Program to Find that Missing Number

This tests knowledge of arithmetic identities and O(n)/O(1) space solutions, standard in algorithm interviews.

How to answer:

  • Use the sum formula n*(n+1)/2 minus the actual sum to get the missing number.
  • Alternatively, use XOR across 1..n and array elements.
  • Provide code and mention overflow considerations for huge n.

Example answer:

Approach: compute the expected sum and subtract the actual sum.

Code:
public static int findMissing(int[] arr) { int n = arr.length + 1; long expected = (long)n * (n + 1) / 2; long actual = 0; for (int v : arr) actual += v; return (int)(expected - actual);}

Commentary: This runs O(n) time and O(1) space. Use long to avoid overflow when n is large.

32. Write A Java Program to Check If Any Number is a Magic Number or Not

A number is said to be a magic number if, after summing the digits in each step and in turn doing the sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

The problem checks loop design, repeated reduction techniques, and numerical properties such as digital roots.

How to answer:

  • Explain repeatedly sum digits until a single digit remains; check if result == 1.
  • Provide a loop code that avoids recursion by iterating while the number > 9.

Example answer:

Code:
int n = 163;int sum = 0;while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10;}if (sum == 1) System.out.println("Magic number");else System.out.println("Not a magic number");

Commentary: The loop reduces the number to its digital root; this approach iterates in O(log n) digit steps.

33. Write A Java Program to Create and Throw Custom Exceptions

Interviewers want to know you can model domain errors with custom exceptions, including checked vs unchecked choices and constructors.

  • How to answer:Show creating a class extending Exception (checked) or RuntimeException (unchecked).
  • Demonstrate throwing it and optionally catching it, and include a constructor forwarding the message.

Example answer:

Custom checked exception:

class CustomException extends Exception { public CustomException(String msg) { super(msg); }}Usage:public static void main(String[] args) throws CustomException { throw new CustomException("This is my custom Exception");}

Commentary: Use checked exceptions for recoverable errors and RuntimeException for programming errors.

34. Write a Java Program to Reverse a String

This validates in-place manipulation, pointer technique, and character encoding awareness.

How to answer:

  • Use two pointers, swapping characters in a char array to avoid extra allocations.
  • Provide code and mention StringBuilder.reverse() as a built-in alternative.

Example answer:

Code:

String s = "Welcome to InterviewBit";char[] a = s.toCharArray();int i = 0, j = a.length - 1;while (i < j) { char t = a[i]; a[i] = a[j]; a[j] = t; i++; j--;}System.out.println(new String(a));

Commentary: O(n) time, O(n) extra for char array; StringBuilder.reverse() can also be used.

35. Write a Java Program to Rotate Arrays 90 Degree Clockwise By Taking Matrices from User Input

This tests matrix manipulation and in-place algorithm design, standard in coding rounds.

How to answer:

  • Describe steps: transpose the matrix, then reverse each row.
  • Provide code showing transpose loops and row reversal.

Example answer:

Approach: Transpose A[i][j] with A[j][i], then for each row reverse elements.

Code:

for (int i = 0; i < n; i++) for (int j = i; j < n; j++) { int t = a[i][j]; a[i][j] = a[j][i]; a[j][i] = t; }for (int i = 0; i < n; i++) { int l = 0, r = n - 1; while (l < r) { int t = a[i][l]; a[i][l] = a[i][r]; a[i][r] = t; l++; r--; }}

Commentary: This rotates in-place in O(n^2) time and O(1) extra space for an n x n matrix.

36. Write a Java Program to Check If Any Number Given as Input is the Sum of 2 Prime Numbers

This assesses prime testing, iteration limits, and efficiency for moderate n values; it also ties to basic number theory.

How to answer:

  • Loop i from 2 to n/2; test if i and n-i are prime using a primality helper.
  • Provide code for a reasonable isPrime routine up to sqrt(n).

Example answer:

Code:

private static boolean isPrime(int x) { if (x < 2) return false; for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true;}private static void findPairs(int n) { for (int i = 2; i <= n/2; i++) { if (isPrime(i) && isPrime(n - i)) System.out.println(n + " = " + i + " + " + (n - i)); }}

Commentary: Complexity is roughly O(n sqrt(n)); for large n, use the sieve to speed up.

37. Write a Java Program for Solving the Tower of Hanoi Problem

Interviewers evaluate recursion design, base cases, and understanding of exponential algorithms.

How to answer:

  • Describe recursive rule: move n-1 from source to auxiliary, move nth to dest, then move n-1 from auxiliary to dest.
  • Provide the recursive implementation and show sample output for n=3.

Example answer:

Code:void toh(int n, char src, char aux, char dst) { if (n <= 0) return; toh(n-1, src, dst, aux); System.out.println("Move disk from " + src + " to " + dst); toh(n-1, aux, src, dst);}

To run: toh(3, 'A', 'B', 'C');

Commentary: This yields 2^n - 1 moves and demonstrates clear recursive decomposition.

38. Implement Binary Search in Java using recursion.

Binary search is a standard algorithmic building block; recursion checks your divide-and-conquer thinking and boundary care.

How to answer:

  • Explain mid computation and base case when low > high.
  • Provide recursive calls for left or right subarray and careful mid calculation to avoid overflow: mid = low + (high - low)/2.

Example answer:

Code:boolean binarySearch(int[] a, int low, int high, int key) { if (low > high) return false; int mid = low + (high - low) / 2; if (a[mid] == key) return true; if (key < a[mid]) return binarySearch(a, low, mid - 1, key); return binarySearch(a, mid + 1, high, key);}

Usage: binarySearch(arr, 0, arr.length - 1, target);

Commentary: Runs in O(log n) time and O(log n) recursion depth.

Nail Coding Interviews with Our AI Interview Assistant − Get Your Dream Job Today

Spending months grinding LeetCode, hoping to pass one tech interview? There's a smarter way. Interview Coder is your AI-powered, undetectable coding assistant for coding interviews, completely undetectable and invisible to screen sharing.

While your classmates stress over thousands of practice problems, you'll have an AI interview assistant that solves coding challenges in real-time during your actual interviews.

Confidence Over Grind: Rethinking Interview Prep

Used by 87,000+ developers landing offers at FAANG, Big Tech, and top startups. Stop letting LeetCode anxiety kill your confidence. Join the thousands who've already taken the shortcut to their dream job. Download Interview Coder and turn your following coding interview into a guaranteed win.


Interview Coder - AI Interview Assistant Logo

Ready to Pass Any SWE Interviews with 100% Undetectable AI?

Start Your Free Trial Today