Java Support Interview Questions and Answers
Ques 21. Explain the 'Comparator' interface in Java.
The 'Comparator' interface is used to define custom ordering for objects. It provides two methods: 'compare()' to compare two objects and 'equals()' to check if two objects are equal. 'Comparator' is often used with sorting algorithms or data structures that require custom ordering.
Example:
Example:
class MyComparator implements Comparator{
public int compare(MyClass obj1, MyClass obj2) {
// custom comparison logic
}
}
Ques 22. What is the 'classpath' in Java, and how is it set?
The 'classpath' is a parameter in the Java Virtual Machine (JVM) that specifies the location of user-defined classes and packages. It can be set using the '-classpath' or '-cp' option when running Java applications. It includes directories, JAR files, and ZIP archives containing Java classes.
Example:
Example:
java -cp myapp.jar com.example.MyClass
Ques 23. Explain the 'super()' constructor in Java.
'super()' is used to invoke the constructor of the immediate parent class. It should be the first statement in the constructor of the subclass. If not explicitly called, the compiler inserts a 'super()' call by default.
Example:
Example:
class Subclass extends Superclass {
Subclass() {
super(); // invokes the constructor of the parent class
}
}
Ques 24. What is the 'NaN' value in Java, and how is it represented?
'NaN' (Not a Number) is a special floating-point value used to represent undefined or unrepresentable results of mathematical operations. It is typically the result of operations like 0.0/0.0 or Math.sqrt(-1). 'NaN' is represented using the 'Double.NaN' constant.
Example:
Example:
double result = 0.0 / 0.0; // results in NaN
Ques 25. Explain the 'try-with-resources' statement in Java.
The 'try-with-resources' statement is used to automatically close resources (like files or sockets) at the end of the try block. Resources must implement the 'AutoCloseable' interface. It simplifies resource management and reduces the chances of resource leaks.
Example:
Example:
try (BufferedReader br = new BufferedReader(new FileReader('file.txt'))) {
// code that uses 'br'
} catch (IOException e) {
// handle the exception
}
Most helpful rated by users: