Java Advanced Concepts - Interview Questions and Answers¶
-
What is the main purpose of using generics in Java?
- To improve code performance
- To enable dynamic typing
- To provide type safety
- To reduce memory usage
-
Which collection framework interface provides dynamic resizing of arrays?
- List
- Set
- Map
- ArrayList
-
Which data structure is used by the HashSet class in Java?
- Array
- Linked List
- Hash Table
- Tree
-
In Java, which collection allows duplicate elements?
- Set
- Map
- List
- Queue
-
What is the purpose of the
Comparableinterface in Java?- To compare two objects based on their hash codes
- To specify the natural ordering of objects
- To provide a way to iterate over a collection
- To filter elements in a collection
-
Which keyword is used to explicitly throw an exception in Java?
- catch
- throw
- finally
- throws
-
In Java, checked exceptions are subclasses of which class?
- RuntimeException
- Exception
- Error
- Throwable
-
What is the purpose of Java Reflection?
- To create new objects
- To access and manipulate class metadata at runtime
- To handle exceptions
- To generate bytecode
-
Which annotation is used to mark a method that overrides a method in a superclass?
- @Override
- @OverrideMethod
- @Overload
- @Overridden
-
Which of the following statements about custom annotations in Java is true?
- Custom annotations can only be used by the Java standard library.
- Custom annotations are defined using the
@Annotationkeyword. - Custom annotations can have runtime retention.
- Custom annotations can be used to define new data types.
-
Which interface in the Java Collections Framework provides a way to store elements as key-value pairs?
- List
- Set
- Map
- Collection
-
In Java, which collection class is synchronized and suitable for multithreaded applications?
- ArrayList
- HashSet
- ConcurrentHashMap
- TreeMap
-
What is the key difference between ArrayList and LinkedList in Java?
- ArrayList is faster for random access, while LinkedList is faster for insertions and deletions.
- ArrayList allows duplicate elements, while LinkedList does not.
- ArrayList uses a doubly-linked list, while LinkedList uses a singly-linked list.
- ArrayList is an interface, while LinkedList is a concrete class.
-
In Java, what does the wildcard character "?" represent in the context of generics?
- An unknown data type
- A wildcard character
- An exception
- A generic class
-
Which method in the
Collectionsclass is used to sort a List in natural order?sort()order()arrange()arrangeInOrder()
-
In Java, which keyword is used to specify that a method can throw multiple exceptions?
- catch
- throw
- throws
- try
-
What is the purpose of the
getClass()method in Java reflection?- To create a new class instance
- To retrieve the runtime class of an object
- To throw a ClassNotFoundException
- To invoke a method on an object
-
Which annotation is used to suppress compiler warnings in Java?
- @SuppressWarnings
- @Override
- @Deprecated
- @SafeVarargs
-
What is the difference between checked and unchecked exceptions in Java?
- Checked exceptions are caught at compile time, while unchecked exceptions are caught at runtime.
- Checked exceptions are subclasses of RuntimeException, while unchecked exceptions are not.
- Checked exceptions are more severe than unchecked exceptions.
- Checked exceptions cannot be caught using try-catch blocks.
-
Which Java annotation is used to mark a class as serializable?
- @Serializable
- @Serial
- @SerializableClass
- @SerializableObject
-
Implement a generic method in Java that counts the number of occurrences of a specific element in an array.
-
Create a generic class called
Pairthat can store two different types of values. Write a Java program to demonstrate its usage. -
Write a Java program that uses reflection to create an instance of a class dynamically and invokes one of its methods.
-
Create a custom annotation called
@LogMethodthat 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@LogMethodand logs a message when the method is called. -
Write Java code to create a generic method that swaps two elements in an array.
-
Implement a custom generic class called
Stackthat supports push and pop operations. Use generics to allow the stack to store elements of any data type. -
Create a custom exception class called
InvalidAgeExceptionthat extendsException. Write a Java program that throws this exception when the age of a person is less than 18. -
Write a Java program that uses reflection to inspect the methods of a given class and prints their names and parameter types.
Answers¶
- c - To provide type safety
- d - ArrayList
- c - Hash Table
- c - List
- b - To specify the natural ordering of objects
- b - throw
- b - Exception
- b - To access and manipulate class metadata at runtime
- a - @Override
- c - Custom annotations can have runtime retention.
- c - Map
- c - ConcurrentHashMap
- a - ArrayList is faster for random access, while LinkedList is faster for insertions and deletions.
- a - An unknown data type
- a - sort()
- c - throws
- b - To retrieve the runtime class of an object
- a - @SuppressWarnings
- a - Checked exceptions are caught at compile time, while unchecked exceptions are caught at runtime.
- 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());
}
}
}
}
¶
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());
}
}
}
}