Java Support Interview Questions and Answers
Ques 16. What is the 'volatile' keyword in Java?
'volatile' is used to indicate that a variable's value may be changed by multiple threads simultaneously. It ensures that the variable is always read from and written to the main memory, avoiding thread-local caching.
Example:
Example:
volatile boolean flag = true;
// variable shared among multiple threads
Ques 17. Explain the concept of the 'equals()' and 'hashCode()' contract.
According to the contract, if two objects are equal (according to the 'equals()' method), their hash codes must be equal as well. However, the reverse is not necessarily true: two objects with equal hash codes may not be equal.
Example:
It's important to ensure that the 'equals()' and 'hashCode()' methods are consistently implemented to maintain this contract.
Ques 18. What is the purpose of the 'default' method in Java interfaces?
The 'default' method in Java interfaces provides a default implementation for a method. It allows adding new methods to interfaces without breaking existing implementations.
Example:
Example:
interface MyInterface {
default void myMethod() {
// default implementation
}
}
Ques 19. Explain the 'String' class and why it is immutable in Java.
The 'String' class in Java represents a sequence of characters. It is immutable to enhance performance and security. Once a 'String' object is created, its value cannot be changed. Any operation that appears to modify the 'String' actually creates a new 'String' object.
Example:
Example:
String str = 'Hello';
str = str.concat(' World'); // creates a new String object
Ques 20. What is the purpose of the 'assert' statement in Java?
The 'assert' statement is used for debugging purposes to check if a given boolean expression is true. If it's false, an 'AssertionError' is thrown. 'assert' statements can be enabled or disabled during runtime using the '-ea' or '-da' JVM options.
Example:
Example:
int x = -1;
assert x >= 0 : 'x should be non-negative';
Most helpful rated by users: