Java Interview Questions -Set 8
Java Interview Questions -Set 8
Table of Contents
Q: What is the difference between ==
and equals()
in Java?
Answer:
==
and equals()
are used for comparison, but they have different purposes:
==
Operator:- Compares references (memory addresses) of objects.
- Checks if two references point to the same object.
equals()
Method:- Compares the values within the objects.
- Should be overridden in a class to provide meaningful comparison.
Example:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
Q: What are the main features of Java 8?
Answer:
Java 8 introduced several important features, including:
- Lambda Expressions:
- Enables functional programming by allowing the creation of anonymous methods.
- Stream API:
- Facilitates functional-style operations on sequences of elements.
- Default Methods:
- Allows methods in interfaces to have implementations.
- Optional Class:
- Helps to avoid
NullPointerException
by providing a container that may or may not contain a value.
- Helps to avoid
- New Date and Time API:
- Provides a comprehensive and consistent date-time library.
Example:
List<String> names = Arrays.asList("John", "Jane", "Jack", "Doe");
names.stream()
.filter(name -> name.startsWith("J"))
.forEach(System.out::println);
Q: What is the use of the final
keyword in Java?
Answer:
The final
keyword in Java can be used in different contexts:
- Final Variable:
- Value cannot be changed once initialized.
- Example:
final int MAX = 100;
- Final Method:
- Cannot be overridden by subclasses.
- Example:
public final void display() { ... }
- Final Class:
- Cannot be subclassed.
- Example:
public final class Utility { ... }
Example:
public final class Constants {
public static final int MAX_VALUE = 100;
}
public class Main {
public static void main(String[] args) {
System.out.println(Constants.MAX_VALUE);
}
}
React 🔥 if this resource is helpful!
Post Comment