Interview Questions

Basic

  1. Difference between == and .equals()?
  2. What is Java and why is it platform-independent?
  3. Explain JDK, JRE, and JVM. What are their differences?
  4. What is bytecode in Java?
  5. Difference between compiled and interpreted languages. Where does Java fit?
  6. What is the significance of public static void main(String args[]) in Java?
  7. What is the significance of final keyword?
  8. What is the static keyword and its uses?
  9. What is the volatile keyword in Java?
  10. What is garbage collection in Java?
  11. How garbage collection works? Algorithm?
  12. Types of garbage collectors
  13. What is memory leak in Java?
  14. What is finalize() method?
  15. Can we force garbage collection?
  16. What is the difference between stack and heap memory?
  17. What is serialization in Java?
  18. How JVM works internally?
  19. How java compilation works?
  20. Difference between call by value and call by reference? Which one is Java?
  21. Why new keyword will create anything in heap?

Datatypes

  1. What are primitive data types in Java?
  2. Difference between int and Integer in Java
  3. What is autoboxing and unboxing?
  4. Explain wrapper classes in Java
  5. What are the size ranges for different primitive types?
  6. What are the methods provided by wrapper classes?

Conditional/Control Flow Statements

  1. What is the difference between if-else and switch statements?
  2. When would you use a switch statement instead of multiple if-else statements?
  3. Can you use a switch statement with String values? Since which Java version?
  4. What's new in switch expressions (Java 14+)?
  5. What happens if you don’t use break in a switch case?
  6. What are the limitations of switch statements?
  7. Explain the difference between while and do-while loops.
  8. What is an enhanced for loop (for-each)? When would you use it?
  9. How do break and continue statements work in nested loops?

Strings

  1. Why are Strings immutable in Java? What are the advantages?
  2. What's the difference between String, StringBuffer, and StringBuilder?
  3. How does string comparison work with == vs equals() method?
  4. What is String pool and how does it work?
  5. What’s the difference between substring() and charAt() methods?
  6. How do you convert String to lowercase/uppercase?
  7. What is the trim() method?
  8. How do you replace characters in a string?
  9. How do you convert int to String and vice versa?
  10. How do you split a string in Java?
  11. How do you join strings in Java?
  12. How do you remove spaces from a string?
  13. How do you find the occurrence of a character in string?
  14. Common String methods?
  15. Explain string interning in Java.

Arrays

  1. What’s the difference between arrays and ArrayList?
  2. How to copy arrays?
  3. How do you find the length of an array vs length of a string?
  4. What are jagged arrays? How do you create them?
  5. Can array size be changed after declaration?
  6. What happens when you access an array index out of bounds?
  7. What is the difference between a dictionary and array in terms of performance?

Date And time

  1. What’s the difference between Date and LocalDate classes?
  2. Difference between Date and LocalDateTime?
  3. Which package contains the new Date-Time API introduced in Java 8?
  4. How do you format and parse dates using DateTimeFormatter?
  5. What are the main classes in java.time package?
  6. How do you calculate the difference between two dates?
  7. What is ZonedDateTime and when would you use it?
  8. How do you convert between different date-time classes?

Searching/Sorting

  1. When would you use binary search? What are its prerequisites?
  2. When would you use merge sort vs quick sort?
  3. What sorting algorithms does Java use internally?
  4. What’s the difference between stable and unstable sorting algorithms?

OOP

  1. Explain the four pillars of OOP with examples. Difference between them
  2. Difference between association, aggregation and composition
  3. What’s the difference between method overloading and method overriding?
  4. Can you override static methods? Why or why not?
  5. What’s the difference between abstract classes and interfaces?
  6. Explain the concept of polymorphism with a real-world example.
  7. Explain Encapsulation with a real-time example
  8. Explain a real world use case of interface? Can we modify an interface after it has been created?
  9. What is Inheritance? Types of inheritance in Java
  10. What is Abstraction and how is it achieved in Java?
  11. What are access modifiers? Explain their scope.
  12. What’s the difference between this and super keywords?
  13. Can a class extend multiple classes in Java? Why?
  14. What is method hiding vs method overriding?
  15. Explain constructor chaining.
  16. Can you overload the main method in Java?
  17. Can we have static methods in interfaces?
  18. What is dynamic method dispatch?
  19. Can we override private methods?
  20. What is a class and object in Java?
  21. Can we have private constructors?
  22. Difference between default constructor and parameterized constructor
  23. Can constructors be overloaded?
  24. What is constructor? Types of constructors
  25. What is deconstructor?
  26. Can we use both this() and super() in the same constructor?
  27. Can abstract classes have constructors?
  28. Why can’t interfaces have constructors?
  29. What are default methods in interfaces (Java 8)?
  30. What is multiple inheritance and how is it achieved in Java?
  31. Why java is not pure oops based language?

Collections Framework

  1. Difference between Collection and Collections
  2. Difference between ArrayList and Vector
  3. What is the initial capacity of ArrayList?
  4. How does Collections.binarySearch() work?
  5. What’s the difference between indexOf() and contains() methods in collections?
  6. How does Collections.sort() work internally?
  7. How do you sort custom objects using Comparable and Comparator?
  8. What's the hierarchy of Collection framework? What is it?
  9. Difference between ArrayList and LinkedList? When to use which?
  10. How does HashMap work internally?
  11. What’s the difference between HashMap and HashTable?
  12. HashMap vs TreeMap vs LinkedHashMap?
  13. HashSet vs TreeSet vs LinkedHashSet?
  14. What are iterators?
  15. What is fail-fast vs fail-safe iterators?
  16. Explain the difference between Set, List, and Map.
  17. What are the different ways to iterate over a collection?
  18. How to sort custom objects?
  19. How does HashSet ensure uniqueness?
  20. What's the load factor in HashMap?
  21. Difference between HashMap and ConcurrentHashMap?
  22. What are generics in Java? Benefits?
  23. Can we store different data types in ArrayList?

Functional Programming

  1. What are lambda expressions? Provide syntax and examples.
  2. What are functional interfaces? Name some built-in ones.
  3. Can a functional interface have more than one abstract method?
  4. What's the difference between Predicate, Function, and Consumer interfaces?
  5. What are method references? What are the different types?
  6. When would you use method references over lambda expressions?
  7. Write examples of static method reference and instance method reference.
  8. What is Optional class and why was it introduced?
  9. How do you create Optional objects?
  10. What’s the difference between orElse() and orElseGet()?
  11. When should you avoid using Optional.get()?
  12. What are Streams? How are they different from collections?
  13. What's the difference between intermediate and terminal operations?
  14. Explain lazy evaluation in streams.
  15. How do you convert a stream to a list or array?
  16. What’s the difference between map() and flatMap()?
  17. How do parallel streams work? When should you use them?
  18. What’s the difference between findFirst() and findAny()?
  19. What is forEach() method?
  20. What is filter() method in streams?

Exception Handling

  1. What's the difference between checked and unchecked exceptions?
  2. Explain the exception hierarchy in Java.
  3. What happens if you use return statement inside a finally block?
  4. What’s the difference between throw and throws keywords?
  5. Can you have multiple catch blocks for a single try block?
  6. What happens if an exception occurs in a finally block?
  7. What’s try-with-resources? Provide an example.
  8. Can you have a try block without catch or finally?
  9. What's the difference between Error and Exception?
  10. How do you create custom exceptions?
  11. Can we rethrow an exception?
  12. What is suppressed exception?
  13. How do you handle multiple exceptions in a single catch block?
  14. What happens if you don’t handle a checked exception?
  15. What are some common exceptions and when do they occur?

Swing/GUI

  1. What is Java Swing?
  2. AWT vs Swing?
  3. Key components
  4. Event handling
  5. Layout managers

Threading

  1. What is multithreading in Java?
  2. How do you create threads in Java?
  3. Difference between extending Thread class and implementing Runnable
  4. What is the thread lifecycle?
  5. What are different thread states?
  6. What is synchronization in Java?
  7. What is the synchronized keyword?
  8. Difference between synchronized method and synchronized block
  9. What is thread safety?
  10. What are race conditions?
  11. What is deadlock and how to avoid it?
  12. What is volatile keyword and when to use it?
    • What is the volatile keyword in Java?
    Link to original
  13. Difference between volatile and synchronized
  14. What is ThreadLocal in Java?
  15. What are wait(), notify(), and notifyAll() methods?
  16. Difference between sleep() and wait() methods
  17. What is join() method in threads?
  18. What is daemon thread?
  19. How do you stop a thread in Java?
  20. What is thread pool and executor framework?

File Handling

Networking

Coding Questions

Reverse a String without Using Built-in Methods

public String reverseString(String str) {
    char[] chars = str.toCharArray();
    int left = 0;
    int right = chars.length - 1;
    while (left < right) {
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
    }
    return new String(chars);
}

How to Check if Two Strings Are Anagrams

public boolean areAnagrams(String s1, String s2) {
    if (s1.length() != s2.length()) {
        return false;
    }
    char[] arr1 = s1.toCharArray();
    char[] arr2 = s2.toCharArray();
    Arrays.sort(arr1);
    Arrays.sort(arr2);
    return Arrays.equals(arr1, arr2);
}

Find the Second Largest Element in an Array

public int findSecondLargest(int[] arr) {
    int largest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;
    for (int num : arr) {
        if (num > largest) {
            secondLargest = largest;
            largest = num;
        } else if (num > secondLargest && num != largest) {
            secondLargest = num;
        }
    }
    return secondLargest;
}

Find Duplicate Elements in an Array

public void findDuplicates(int[] arr) {
    Set<Integer> seen = new HashSet<>();
    Set<Integer> duplicates = new HashSet<>();
    for (int num : arr) {
        if (!seen.add(num)) {
            duplicates.add(num);
        }
    }
    System.out.println("Duplicate elements: " + duplicates);
}

Remove Duplicates from a List

public <T> List<T> removeDuplicates(List<T> list) {
    return new ArrayList<>(new HashSet<>(list));
}

Implement Binary search Algorithm

public int binarySearch(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) {
            return mid;
        }
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

Find First and Last Occurrence of an Element in a Sorted Array

public int[] findFirstAndLast(int[] arr, int target) {
    int first = -1;
    int last = -1;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            if (first == -1) {
                first = i;
            }
            last = i;
        }
    }
    return new int[]{first, last};
}

Implement Sorting Algorithms (Bubble Sort)

public void bubbleSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

Check if a Number is even or Odd Using the Ternary Operator

public String checkEvenOdd(int num) {
    return (num % 2 == 0) ? "Even" : "Odd";
}
public void printPrimes(int limit) {
    for (int i = 2; i <= limit; i++) {
        boolean isPrime = true;
        for (int j = 2; j <= Math.sqrt(i); j++) {
            if (i % j == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            System.out.print(i + " ");
        }
    }
}

Find the Sum of Squares of even Numbers Using Streams

import java.util.stream.IntStream;
 
public int sumOfSquaresOfEvens(int[] numbers) {
    return IntStream.of(numbers)
                   .filter(n -> n % 2 == 0)
                   .map(n -> n * n)
                   .sum();
}

Find Duplicate Characters in a String

public void findDuplicateChars(String str) {
    Map<Character, Integer> charCount = new HashMap<>();
    for (char c : str.toCharArray()) {
        charCount.put(c, charCount.getOrDefault(c, 0) + 1);
    }
    for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
        if (entry.getValue() > 1) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Find the Intersection of Two Arrays

public int[] findIntersection(int[] arr1, int[] arr2) {
    Set<Integer> set1 = new HashSet<>();
    for (int num : arr1) {
        set1.add(num);
    }
    List<Integer> intersectionList = new ArrayList<>();
    for (int num : arr2) {
        if (set1.contains(num)) {
            intersectionList.add(num);
        }
    }
    return intersectionList.stream().mapToInt(i -> i).toArray();
}

Sort a Map by Its Values

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
              .stream()
              .sorted(Map.Entry.comparingByValue())
              .collect(Collectors.toMap(
                  Map.Entry::getKey,
                  Map.Entry::getValue,
                  (e1, e2) -> e1, LinkedHashMap::new));
}

Count Frequency of Each Character in a String Using Streams

public Map<Character, Long> countCharacters(String str) {
    return str.chars()
              .mapToObj(c -> (char) c)
              .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

Count Vowels and Consonants in a String

public void countVowelsAndConsonants(String str) {
    int vowels = 0;
    int consonants = 0;
    String vowelsStr = "aeiouAEIOU";
    for (char c : str.toCharArray()) {
        if (Character.isLetter(c)) {
            if (vowelsStr.indexOf(c) != -1) {
                vowels++;
            } else {
                consonants++;
            }
        }
    }
    System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
}

Find the Factorial of a Number

public long factorial(int n) {
    if (n < 0) throw new IllegalArgumentException("Number must be non-negative");
    long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

Generate Fibonacci Series

public void generateFibonacci(int n) {
    int a = 0, b = 1;
    System.out.print(a + " " + b + " ");
    for (int i = 2; i < n; i++) {
        int next = a + b;
        System.out.print(next + " ");
        a = b;
        b = next;
    }
}

Find a Palindrome Number

public boolean isPalindrome(int num) {
    int originalNum = num;
    int reversedNum = 0;
    while (num > 0) {
        int digit = num % 10;
        reversedNum = reversedNum * 10 + digit;
        num /= 10;
    }
    return originalNum == reversedNum;
}

Count Digits in a Number

public int countDigits(long num) {
    if (num == 0) return 1;
    int count = 0;
    while (num != 0) {
        num /= 10;
        count++;
    }
    return count;
}

How to Find Armstrong Numbers

public boolean isArmstrong(int num) {
    int originalNum = num;
    int sum = 0;
    int power = String.valueOf(num).length();
    int temp = num;
    while (temp > 0) {
        int digit = temp % 10;
        sum += Math.pow(digit, power);
        temp /= 10;
    }
    return sum == originalNum;
}

How to Find the Missing Number in an Array

public int findMissingNumber(int[] arr) {
    int n = arr.length + 1;
    int totalSum = n * (n + 1) / 2;
    int arraySum = 0;
    for (int num : arr) {
        arraySum += num;
    }
    return totalSum - arraySum;
}

Generate Random Numbers in Java

import java.util.Random;
 
public int generateRandomNumber(int min, int max) {
    Random random = new Random();
    return random.nextInt(max - min + 1) + min;
}

Check if a Year is a Leap Year

public boolean isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

Count Number of Words in a Sentence

public int countWords(String sentence) {
    if (sentence == null || sentence.isEmpty()) {
        return 0;
    }
    String[] words = sentence.trim().split("\\s+");
    return words.length;
}

Explain Tower of Hanoi

The Tower of Hanoi is a classic recursive puzzle. The goal is to move a stack of discs of different sizes from a source peg to a destination peg, with the help of an auxiliary peg. The rules are:

  1. Only one disc can be moved at a time.
  2. A larger disc can never be placed on top of a smaller disc.
  3. The top disc is the only one that can be moved.

The solution is recursive:

  1. Move n-1 discs from the source to the auxiliary peg.
  2. Move the largest disc (n) from the source to the destination peg.
  3. Move the n-1 discs from the auxiliary to the destination peg.

Find if a String is Interleaved of 2 other Strings

public boolean isInterleaved(String s1, String s2, String s3) {
    if (s1.length() + s2.length() != s3.length()) {
        return false;
    }
    boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];
    dp[0][0] = true;
 
    for (int i = 0; i <= s1.length(); i++) {
        for (int j = 0; j <= s2.length(); j++) {
            if (i > 0 && s1.charAt(i - 1) == s3.charAt(i + j - 1)) {
                dp[i][j] = dp[i][j] || dp[i - 1][j];
            }
            if (j > 0 && s2.charAt(j - 1) == s3.charAt(i + j - 1)) {
                dp[i][j] = dp[i][j] || dp[i][j - 1];
            }
        }
    }
    return dp[s1.length()][s2.length()];
}