0% found this document useful (0 votes)
2 views11 pages

Java Interview Questions From IBM

The document contains a series of programming questions and answers related to Java, covering topics such as data structures, algorithms, object-oriented programming, and exception handling. It includes code examples for various tasks like checking for palindromes, finding the largest element in an array, and implementing a queue using stacks. Additionally, it discusses concepts like immutability, constructors, and the differences between various Java constructs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

Java Interview Questions From IBM

The document contains a series of programming questions and answers related to Java, covering topics such as data structures, algorithms, object-oriented programming, and exception handling. It includes code examples for various tasks like checking for palindromes, finding the largest element in an array, and implementing a queue using stacks. Additionally, it discusses concepts like immutability, constructors, and the differences between various Java constructs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

Q1. What is the difference between an array and a linked list?

An array is a collection of elements of the same data type, stored in consecutive


memory locations. A linked list, on the other hand, is made up of nodes, where each
node points to the next one.

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.

public boolean isPalindrome(String str) {


String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}

Q3. Give a program to find the largest element in an array.


Sample Answer: To find the largest element in an array, we can iterate through each
element of the array, comparing each element with the current maximum. The Java
code used to find the largest element in an array is:

public int findLargest(int[] arr) {


int max = arr[0];
for (int num: arr) {
if (num > max) {
}
max = num;
}
return max;

Q4. How many orders of growth does a binary search take?


Sample Answer: The order of growth of binary search is O(log n).

Q5. What is the difference between ‘==’ and ‘equals()’ in Java?


Sample Answer: In the case of objects, ‘==’ checks for the equality of references
(memory addresses) whereas ‘equals()’ checks for the equality of the objects
themselves.

Q7. What do you understand by the term OOP?


Sample Answer: OOP (object-oriented programming) is a discipline of software
engineering that organizes software design around data or objects rather than
functions or logic. The four main principles of OOP are encapsulation, inheritance,
polymorphism, and abstraction.

Q8. Differentiate between a stack and a queue.


Sample Answer: A stack operates on a Last-In-First-Out (LIFO) principle, meaning
that the last element added is the first to be removed. On the other hand, a queue
follows a First-In-First-Out (FIFO) principle where the first element added is the
first to be removed.

Q10. What are constructors in Java?


Sample Answer: A constructor is a special function in Java that is invoked when an
object is created for a class. It sets up the state of the object. Constructors are
always class-named and have no return type.
Q9. Write a program that helps to check if a number is prime or not.
Sample Answer: To determine if a number is prime, you need to check for
divisibility by all integers up to its square root. This method efficiently
identifies prime numbers while minimizing unnecessary computations. The program for
checking if a number is prime or not is:

public boolean isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

Q11. Write a program to count the number of vowels in a string.


Sample Answer: Counting vowels in a string involves iterating through each
character and checking if it belongs to a defined set of vowel characters. The code
for counting the number of vowels in a string in Java is:

public int countVowels(String str) {


int count = 0;
for (char c: str.toCharArray()) {
if ("aeiouAEIOU".indexOf(c) != -1) {
count++;
}
}
return count;
}
Q12. Explain the difference between method overloading and method overriding.
Sample Answer: Method overloading occurs when multiple methods within the same
class share the same name but differ in parameter types or counts. On the other
hand, method overriding happens when a subclass provides a specific implementation
for a method already defined in its superclass.

Q13. Create a program to calculate the factorial of a given number.


Sample Answer: Calculating factorials involves recursive or iterative approaches
where one multiplies all positive integers up to that number. The program to
calculate the factorial of a given number is:

public int factorial(int n) {


if (n == 0) return 1;
return n * factorial(n - 1);
}
Q14. What do you understand by the term exception in the context of the Java
programming language? Discuss how exceptions are managed.
Sample Answer: An exception is a situation that arises during the execution of a
program and interferes with its normal functioning. One way to handle exceptions is
by using a try-catch block. The try block contains the code that may cause an
exception, and the catch block is used to handle the exception if it occurs.

Q15. What are static variables and methods in Java?


Sample Answer: In Java, static variables and static methods are associated with the
class rather than individual instances. A static variable, declared with the static
keyword, is shared among class objects, with memory allocated only once at class
loading.

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));

Q17. What is meant by the hash table? Describe how it works.


Sample Answer: A hash table is a data structure that stores key-value pairs, using
a hash function to map keys to indices in an array for fast access. It works by
computing a hash code for a key, which determines the index where its value is
stored. If two keys generate the same index (collision), strategies like chaining
(storing multiple pairs in a bucket) or open addressing (finding another slot) are
used to resolve it. Hash tables offer efficient O(1)O(1) average-time operations
for insertions, deletions, and lookups, but their performance can degrade with poor
hash functions or excessive collisions. They are commonly used in caching,
databases, and dictionaries.

Q18. Write a program that finds the second-largest number in an array.


Sample Answer: The method initializes two variables, ‘largest’ and ‘secondLargest’,
to the minimum possible integer value. It then iterates through the array. If a
number is larger than the current largest, it updates ‘secondLargest’ to the
previously largest and sets ‘largest’ to the current number. If the number is not
equal to the ‘largest’ but is larger than ‘secondLargest’, it updates secondLargest
variable. This ensures that by the end of the loop, secondLargest variable holds
the second-largest number in the array.

The program that finds the second-largest number in an array is:

public int findSecondLargest(int[] arr) {


int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;
for (int num: arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
return secondLargest;

Q19. What is the difference between thread and process?


Sample Answer: A process is an independent program and it runs in its own memory
space, while a thread is a lightweight unit of execution within the process and
shares the same memory space. Threads are used for implementing parallelism in a
program.
Q20. What does it mean for a design pattern to realize the Singleton pattern?
Provide an example.
Sample Answer: The Singleton pattern ensures that a given class has only one
instance and provides one global access point. The following code demonstrates the
implementation of the Singleton design pattern, ensuring only one instance of the
class is created.

public class Singleton {


private static Singleton instance;
private Singleton() {} // Private constructor
public static Singleton getInstance() {
if (instance == null) {
}
instance = new Singleton();
return instance;
}
}
Pro Tip: If you are preparing for interview at IBM, research the common interview
questions. Check out our guide on IBM interview questions and answers and ace the
selection process.

Q21. What are the advantages of linked lists over an array?


Sample Answer: Linked lists and arrays are two fundamental data structures. While
linked lists offer more flexibility in memory allocation and manipulation, arrays
are more efficient for direct access to elements. Here’s a comparison of their
characteristics:

Linked Lists Arrays


Use dynamic memory allocation, allowing for flexible size changes. Have a fixed
size, meaning memory allocation is static.
Efficient insertion and deletion of elements at any position. Insertion and
deletion can be inefficient as elements need to be shifted to maintain order.
Require more memory per element due to the need for storing pointers to the next
node. Provide faster access to elements due to contiguous memory allocation.
Q22. How would you implement a queue using two stacks?
Sample Answer: Implementing a queue with two stacks involves using one stack for
enqueue operations and another for dequeue operations. When dequeuing, if the
second stack is empty, elements are transferred from the first stack to the second
stack, reversing their order and allowing efficient dequeue operations.

The program to implement a queue using two stacks in Java is:

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.

Q24. Illustrate the differences between synchronized blocks and synchronized


methods.
Sample Answer: A synchronized method locks the entire method, ensuring that only
one thread can execute it at a time. In contrast, a synchronized block locks only a
specific section of the method, providing finer control over which resources are
locked. This allows for better performance, as it minimizes the scope of the lock
and reduces contention between threads.

Q25. Write a program to remove duplicates from a sorted array.


Sample Answer: This method takes advantage of the fact that the array is already
sorted. It initializes an index variable to 1, assuming the first element is
unique. The method then iterates through the array starting from the second
element. If the current element is different from the previous one, it assigns the
current element to the index position and increments the index. This effectively
moves the unique elements to the front of the array. The final value of the index
indicates the number of unique elements in the array.

The program to remove duplicates from a sorted array is:

public int removeDuplicates(int[] arr) {


int index = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
arr[index++] = arr[i];
}
}
return index;
}
Q26. What is the difference between ‘ArrayList’ and ‘LinkedList’ in Java?
Sample Answer: An ArrayList is backed by a dynamically resizable array. It is fast
in access and searching but slows down during insertions and deletions in the list.
On the other hand, LinkedList is implemented as a doubly-linked list.

Q27. What are functional interfaces in Java? Give examples.


Sample Answer: A functional interface is an interface that has only one abstract
method. These interfaces can be assigned to a lambda expression. The following code
demonstrates a functional interface in Java, which contains only one abstract
method and can be used with a lambda expression:

@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:

super: It is a reference variable used to refer to the immediate parent class’s


methods and constructors. It is often used to call the parent class’s constructor
or to access methods that are overridden in the child class.
this: It is a reference variable used to refer to the current instance of the
class. It is commonly used to differentiate between class fields and parameters
with the same name, and also to call other constructors within the same class.
Q29. Write a program to find the length of the longest substring without repeating
characters.
Sample Answer: This method uses the sliding window technique. It maintains a window
(from left to right) with unique characters. As the right moves through the string,
it adds characters to a set. If a duplicate is found, the left moves forward to
eliminate the duplicate. The method keeps track of the maximum window size and
returns the length of the longest substring. The program to find the length of the
longest substring without repeating characters is:

public int lengthOfLongestSubstring(String s) { Set<Character> set = new


HashSet<>();
int left = 0, maxLength = 0;
for (int right = 0; right <s.length(); right++) {
while (set.contains(s.charAt(right))) {
set.remove(s.charAt(left));
left++;
}
}
set.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
return maxLength;
Q30. What is the difference between ‘throw’ and ‘throws’ in Java?
Sample Answer: In Java, throw is used to explicitly raise an exception from a
method or block of code, whereas throws is used in a method signature to declare
the types of exceptions that the method may throw. In other words, throw is for
throwing an exception, while throws is for specifying which exceptions a method may
potentially throw.

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.

IBM Coding Interview Questions and Answers for Experienced Professionals


Preparing for an IBM coding interview offers a great opportunity to showcase your
skills, especially for experienced professionals. To help you excel, here are 15
commonly asked IBM coding interview questions, along with their solutions covering
a range of topics.

Q31. Write a program to check if a string is a palindrome.


Sample Answer: This method uses two pointers, left and right, which start at the
beginning and end of the string, respectively. It compares the characters at these
two positions. If they are different, the string is not a palindrome, and the
method returns false. The pointers then move towards the center, and this process
continues until the pointers meet or cross. It returns true if no mismatch can be
found, indicating the string is palindrome.

Here’s a code to check if a string is a palindrome:

public boolean isPalindrome(String str)


{ int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
Q32. How do you implement a custom thread pool in Java?
Sample Answer: A custom thread pool can be implemented using the ExecutorService
interface and the ThreadPoolExecutor class, which defines core pool size, maximum
pool size, and keeping threads alive, among other things. Here’s a code:

ExecutorService executorService = new ThreadPoolExecutor(5, 10, 60,


TimeUnit.SECONDS, new
LinkedBlockingQueue<>());
executorService.submit(new RunnableTask());
Q33. Explain ‘immutability’ in Java. How would you create an immutable class?
Sample Answer: An immutable class is a class whose objects, once created, cannot be
modified. The fields of an immutable class are typically declared as final and
private, and the class provides no setter methods to alter its state. The object’s
state is set only during construction through a constructor, and after that, it
remains constant. This ensures thread safety and consistency, as the object’s data
cannot be changed accidentally or maliciously after creation.

To create an immutable class, you need to perform the following steps:

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:

public final class ImmutableClass{


private final int value;
public ImmutableClass(int value) {
}
this.value = value;
public int getValue() {
return value;
}
Q34. What is the use of the volatile keyword in Java?
Sample Answer: The volatile keyword guarantees that a variable’s value will be read
from and written in the main memory and not be cached in thread memory. It is used
for variables that are accessed and changed by multiple threads, giving visibility
to other threads and ensuring that a thread cannot interfere with the modification
of the values.

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.

The code for implementing this in Java is:

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.

Q38. What do ‘final’, ‘finally’, and ‘finalize’ mean in Java?


Sample Answer: The meaning of ‘final’, ‘finally’, and ‘finalize’ is:

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.

The function for this used in Java is:

def merge_sorted_arrays(arr1, arr2):


merged_array = []
i, j = 0, 0

while i < len(arr1) and j < len(arr2):


if arr1[i] < arr2[j]:
merged_array.append(arr1[i])
i += 1
else:
merged_array.append(arr2[j])
j += 1

# Append remaining elements


merged_array.extend(arr1[i:])
merged_array.extend(arr2[j:])
return merged_array
Q40. Explain the differences between Callable and Runnable in Java.
Sample Answer: Both Callable and Runnable are used for asynchronous task execution,
but Callable can return a value or throw an exception, while Runnable cannot return
values or throw exceptions. While callable works with an ExecutorService, runnable
works under the Thread mechanism.

Q41. Write a function rotate_matrix that takes an n x n matrix and rotates it 90


degrees clockwise. The matrix is given as a list of lists.
Sample Answer: The rotate_matrix function rotates an n x n matrix 90 degrees
clockwise by first transposing it (swapping rows and columns) and then reversing
each row. This in-place solution has a time complexity of O(n^2) and efficiently
modifies the matrix.

The function for the same used in Java is:

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;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {


private final int capacity;

public LRUCache(int capacity) {


super(capacity, 0.75f, true); // True for access order
this.capacity = capacity;
}

@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}

public static void main(String[] args) {


LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "One");
cache.put(2, "Two");
cache.put(3, "Three");
cache.get(1); // Access the key 1
cache.put(4, "Four"); // This will evict key 2
System.out.println(cache); // Output will be {1=One, 3=Three, 4=Four}
}
}
Q43. How would you implement a distributed transaction management system using the
Saga pattern in Java?
Sample Answer: The Saga pattern manages distributed transactions by coordinating a
series of local transactions across services. Each service performs a local
transaction and publishes events, with compensating actions triggered if a failure
occurs, ensuring eventual consistency and reliability in microservices.

Here’s a simplified implementation using the Saga pattern in Java:

public class OrderService {


public void placeOrder(Order order) {
try {
createOrder(order);
InventoryService.updateInventory(order);
} catch (Exception e) {
compensateOrderCreation(order);
}
}

private void createOrder(Order order) { /* Order creation logic */ }


private void compensateOrderCreation(Order order) { /* Compensation logic
*/ }
}

public class InventoryService {


public static void updateInventory(Order order) {
try { /* Update inventory logic */ }
catch (Exception e) { /* Compensation logic */ }
}
}
Q44. How would you implement a thread-safe Singleton pattern using the Bill Pugh
Singleton design in Java?
Sample Answer: The Bill Pugh Singleton design uses a static inner class to
implement the Singleton pattern efficiently. The instance is created only when
needed, ensuring lazy initialization and thread safety. This method avoids
synchronization overhead and leverages the Java ClassLoader mechanism.

Here’s an example:

public class Singleton {


// Private constructor to prevent instantiation
private Singleton() {}
// Static inner class responsible for holding the Singleton instance
private static class SingletonHelper {
// This line will only be executed when getInstance() is called
private static final Singleton INSTANCE = new Singleton();
}
// Public method to provide access to the instance
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}

Q45. How do you process the database transactions in Java?


Sample Answer: Transactions are handled in Java via JDBC or with a framework such
as Hibernate. The Connection object contains the methods commit() and rollback()
that manage transactions accordingly. A transaction is initiated with
setAutoCommit(false) and performed by a commit or rollback transaction based on
whether a transaction was committed or rollback.

Here’s a code:

connection.setAutoCommit(false);
try {
// Execute queries
connection.commit();
} catch (SQLException e) {
}
connection.rollback();

Q46. Write a program to implement a thread-safe Singleton pattern in Java.


Sample Answer: The thread-safe Singleton pattern can be implemented using double-
checked locking. By checking if the instance is null before and after
synchronization, and using the volatile keyword, it ensures that only one instance
is created in a multithreaded environment, improving performance.

Here’s an implementation of a thread-safe Singleton pattern using the ‘Double-


Checked Locking’ mechanism:

public class Singleton {


// Volatile keyword ensures that the instance is correctly handled in a
multithreaded environment
private static volatile Singleton instance;
// Private constructor to prevent instantiation
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
// Double-checked locking to ensure only one instance is created
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

You might also like