Java Interview Questions From IBM
Java Interview Questions From IBM
Q2. What do you understand by the term palindrome? Create a code that checks
whether a given text is a palindrome or not.
A word or number that reads the same both forwards and backward, is called a
palindrome.
On the other hand, a static method, also declared static, belongs to the class and
can be invoked without creating an object. Static methods cannot directly access
non-static (instance) variables or methods, as they are not tied to any specific
instance, but they can access other static members.
Q16. What is the difference between deep and shallow copies in Java?
Sample Answer: A shallow copy duplicates references of the objects. Whereas, a deep
copy copies the objects. This means that changes in the original object will affect
the shallow copy but will not affect the deep copy. The following code demonstrates
the difference between shallow and deep copies in Java:
// Shallow copy
List<String> shallowCopy = new ArrayList<>(originalList);
// Deep copy
List<String> deepCopy = new ArrayList<>();
for (String item: originalList) {
}
deepCopy.add(new String(item));
class QueueUsingStacks {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void enqueue(int x) {
}
stack1.push(x);
public int dequeue() {
if (stack2.isEmpty()) {
while (Istack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
}
}
return stack2.pop();
Q23. What is a deadlock in multithreading? How do you avoid it?
Sample Answer: A deadlock occurs when two or more threads are blocked forever
because each is waiting for the other to release resources. There are ways to avoid
deadlocks, by ensuring threads are reconfigured to acquire resources in a given
order, or using timeout mechanisms.
@FunctionalInterface
public interface MyFunction {
void apply();
}
Q28. What is the difference between ‘super’ and ‘this’ in Java?
Sample Answer: The difference between ‘super’ and ‘this’ in Java is:
Pro Tip: If you’re preparing for a mid-level position at IBM, particularly for
roles such as Java Developer, it’s essential to focus on mastering Java-related
concepts. If you’re targeting a Java Developer role at IBM, make sure to review
commonly asked IBM Java developer job interview questions.
All fields are final and private. No setter methods should be there.
The object is completely initialized through the constructor, and its state cannot
be modified afterward.
This ensures immutability, where the object’s data remains consistent and
unchangeable once it is created. The following code demonstrates the implementation
of an immutable class in Java, where the object’s state cannot be changed after
initialization.
Here’s a code:
Q35. Explain the Observer Design Pattern. How would you implement it in Java?
Sample Answer: Observer is a one-to-many dependency where the one that depends on
more than one object is notified if any of the objects on which it depends change
their state.
interface Observer {
void update(String message);
}
class ConcreteObserver implements Observer {
public void update(String message) {
System.out.println("Received message: " + message);
}
}
Q36. Write a function find_missing_number that takes a list of integers from 1 to n
with exactly one number missing. The list contains n-1 numbers. Return the missing
number?
Sample Answer: The find_missing_number function calculates the expected sum of
integers from 1 to n, where n is the list length plus one. It then subtracts the
sum of the given numbers from the expected sum. The difference between these sums
is the missing number in the list.
Here’s a code:
def find_missing_number(nums):
n = len(nums) + 1
expected_sum = n * (n + 1) // 2 # Sum of first n natural numbers
actual_sum = sum(nums) # Sum of numbers in the list
return expected_sum - actual_sum # The missing number is the difference
Q37. What are the distinctions between a HashMap and a TreeMap in Java?
Sample Answer: HashMap does not keep any order of the keys, where O(1) is the time
complexity for all basic operations. TreeMap, on the other hand, is sorted
according to keys and uses a Red-Black Tree internally, giving it a time complexity
of O(logn) for put and get operations.
final is used to define the constant to avoid method overriding and inheritance.
finally is that block that gets executed even if there is no exception generated
after the try block.
finalize is a method of the object class that is called before the object is
garbage collected for cleanup.
Q39. Write a function merge_sorted_arrays that takes two sorted arrays and merges
them into a single sorted array.
Sample Answer: The function merges two sorted arrays by comparing their elements
one by one and adding the smaller element to the result array. After one array is
exhausted, the remaining elements of the other array are appended. This solution
works in O(n + m) time complexity, where n and m are the lengths of the input
arrays.
def rotate_matrix(matrix):
n = len(matrix)
# Transpose the matrix (swap rows and columns)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()
return matrix
Q42. How would you implement a thread-safe LRU (Least Recently Used) cache in Java?
Sample Answer: In this implementation, the LinkedHashMap maintains the order of
access. The removeEldestEntry() method is overridden to remove the oldest entry
once the cache exceeds its capacity. This ensures the least recently used entry is
evicted. The cache is thread-safe because LinkedHashMap is internally synchronized
for single-threaded access. For full thread safety in a multi-threaded environment,
additional synchronization mechanisms like ReentrantLock or synchronized blocks can
be used.
Here’s an example:
import java.util.LinkedHashMap;
import java.util.Map;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
Here’s an example:
Here’s a code:
connection.setAutoCommit(false);
try {
// Execute queries
connection.commit();
} catch (SQLException e) {
}
connection.rollback();