Skip to content

Java Advanced Concepts - Interview Questions and Answers

  1. What is the main purpose of using generics in Java?

    1. To improve code performance
    2. To enable dynamic typing
    3. To provide type safety
    4. To reduce memory usage
  2. Which collection framework interface provides dynamic resizing of arrays?

    1. List
    2. Set
    3. Map
    4. ArrayList
  3. Which data structure is used by the HashSet class in Java?

    1. Array
    2. Linked List
    3. Hash Table
    4. Tree
  4. In Java, which collection allows duplicate elements?

    1. Set
    2. Map
    3. List
    4. Queue
  5. What is the purpose of the Comparable interface in Java?

    1. To compare two objects based on their hash codes
    2. To specify the natural ordering of objects
    3. To provide a way to iterate over a collection
    4. To filter elements in a collection
  6. Which keyword is used to explicitly throw an exception in Java?

    1. catch
    2. throw
    3. finally
    4. throws
  7. In Java, checked exceptions are subclasses of which class?

    1. RuntimeException
    2. Exception
    3. Error
    4. Throwable
  8. What is the purpose of Java Reflection?

    1. To create new objects
    2. To access and manipulate class metadata at runtime
    3. To handle exceptions
    4. To generate bytecode
  9. Which annotation is used to mark a method that overrides a method in a superclass?

    1. @Override
    2. @OverrideMethod
    3. @Overload
    4. @Overridden
  10. Which of the following statements about custom annotations in Java is true?

    1. Custom annotations can only be used by the Java standard library.
    2. Custom annotations are defined using the @Annotation keyword.
    3. Custom annotations can have runtime retention.
    4. Custom annotations can be used to define new data types.
  11. Which interface in the Java Collections Framework provides a way to store elements as key-value pairs?

    1. List
    2. Set
    3. Map
    4. Collection
  12. In Java, which collection class is synchronized and suitable for multithreaded applications?

    1. ArrayList
    2. HashSet
    3. ConcurrentHashMap
    4. TreeMap
  13. What is the key difference between ArrayList and LinkedList in Java?

    1. ArrayList is faster for random access, while LinkedList is faster for insertions and deletions.
    2. ArrayList allows duplicate elements, while LinkedList does not.
    3. ArrayList uses a doubly-linked list, while LinkedList uses a singly-linked list.
    4. ArrayList is an interface, while LinkedList is a concrete class.
  14. In Java, what does the wildcard character "?" represent in the context of generics?

    1. An unknown data type
    2. A wildcard character
    3. An exception
    4. A generic class
  15. Which method in the Collections class is used to sort a List in natural order?

    1. sort()
    2. order()
    3. arrange()
    4. arrangeInOrder()
  16. In Java, which keyword is used to specify that a method can throw multiple exceptions?

    1. catch
    2. throw
    3. throws
    4. try
  17. What is the purpose of the getClass() method in Java reflection?

    1. To create a new class instance
    2. To retrieve the runtime class of an object
    3. To throw a ClassNotFoundException
    4. To invoke a method on an object
  18. Which annotation is used to suppress compiler warnings in Java?

    1. @SuppressWarnings
    2. @Override
    3. @Deprecated
    4. @SafeVarargs
  19. What is the difference between checked and unchecked exceptions in Java?

    1. Checked exceptions are caught at compile time, while unchecked exceptions are caught at runtime.
    2. Checked exceptions are subclasses of RuntimeException, while unchecked exceptions are not.
    3. Checked exceptions are more severe than unchecked exceptions.
    4. Checked exceptions cannot be caught using try-catch blocks.
  20. Which Java annotation is used to mark a class as serializable?

    1. @Serializable
    2. @Serial
    3. @SerializableClass
    4. @SerializableObject
  21. Implement a generic method in Java that counts the number of occurrences of a specific element in an array.

  22. Create a generic class called Pair that can store two different types of values. Write a Java program to demonstrate its usage.

  23. Write a Java program that uses reflection to create an instance of a class dynamically and invokes one of its methods.

  24. Create a custom annotation called @LogMethod that can be used to annotate methods in a Java class. Write a Java program that uses reflection to check if a method is annotated with @LogMethod and logs a message when the method is called.

  25. Write Java code to create a generic method that swaps two elements in an array.

  26. Implement a custom generic class called Stack that supports push and pop operations. Use generics to allow the stack to store elements of any data type.

  27. Create a custom exception class called InvalidAgeException that extends Exception. Write a Java program that throws this exception when the age of a person is less than 18.

  28. Write a Java program that uses reflection to inspect the methods of a given class and prints their names and parameter types.


Answers

  1. c - To provide type safety
  2. d - ArrayList
  3. c - Hash Table
  4. c - List
  5. b - To specify the natural ordering of objects
  6. b - throw
  7. b - Exception
  8. b - To access and manipulate class metadata at runtime
  9. a - @Override
  10. c - Custom annotations can have runtime retention.
  11. c - Map
  12. c - ConcurrentHashMap
  13. a - ArrayList is faster for random access, while LinkedList is faster for insertions and deletions.
  14. a - An unknown data type
  15. a - sort()
  16. c - throws
  17. b - To retrieve the runtime class of an object
  18. a - @SuppressWarnings
  19. a - Checked exceptions are caught at compile time, while unchecked exceptions are caught at runtime.
  20. d - @SerializableObject

21. Implement a generic method in Java that counts the number of occurrences of a specific element in an array.

public class Main {
    public static <T> int countOccurrences(T[] array, T element) {
        int count = 0;
        for (T e : array) {
            if (e.equals(element)) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1};
        String[] words = {"apple", "banana", "apple", "orange", "apple", "pear"};

        System.out.println(countOccurrences(numbers, 1));
        System.out.println(countOccurrences(words, "apple"));
    }
}

22. Create a generic class called Pair that can store two different types of values. Write a Java program to demonstrate its usage.

public class Pair<LEFT, RIGHT> {
      private LEFT left;
      private RIGHT right;

      public Pair(LEFT left, RIGHT right) {
         this.left = left;
         this.right = right;
      }

      public LEFT getLeft() {
         return left;
      }

      public void setLeft(LEFT left) {
         this.left = left;
      }

      public RIGHT getRight() {
         return right;
      }

      public void setRight(RIGHT right) {
         this.right = right;
      }

      @Override
      public String toString() {
         return "Pair{" +
                  "left=" + left +
                  ", right=" + right +
                  '}';
      }
}

23. Write a Java program that uses reflection to create an instance of a class dynamically and invokes one of its methods.

public class Main {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("java.util.Date");
        Object object = clazz.getDeclaredConstructor().newInstance();
        Method method = clazz.getMethod("toString");
        System.out.println(method.invoke(object));
    }
}

24. Create a custom annotation called @LogMethod that can be used to annotate methods in a Java class. Write a Java program that uses reflection to check if a method is annotated with @LogMethod and logs a message when the method is called.

import java.lang.annotation.*;
import java.lang.reflect.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface LogMethod {
}

class Test {
    @LogMethod
    public void testMethod() {
        System.out.println("testMethod() called");
    }
}

25. Write Java code to create a generic method that swaps two elements in an array.

public class Main {
   public static <T> void swap(T[] array, int i, int j) {
      T temp = array[i];
      array[i] = array[j];
      array[j] = temp;
   }
}

26. Implement a custom generic class called Stack that supports push and pop operations. Use generics to allow the stack to store elements of any data type.

public class Stack<T> {
    private final List<T> elements = new ArrayList<>();

    public void push(T element) {
        elements.add(element);
    }

    public T pop() {
        if (elements.isEmpty()) {
            throw new EmptyStackException();
        }
        return elements.remove(elements.size() - 1);
    }

    public boolean isEmpty() {
        return elements.isEmpty();
    }
}

27. Create a custom exception class called InvalidAgeException that extends Exception. Write a Java program that throws this exception when the age of a person is less than 18.

public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be greater than 18");
        }
        this.name = name;
        this.age = age;
    }
}

28. Write a Java program that uses reflection to inspect the methods of a given class and prints their names and parameter types.

public class Main {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("java.util.Date");
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
            for (Parameter parameter : method.getParameters()) {
                System.out.println(parameter.getType());
            }
        }
    }
}