Java programming Q and A
Java programming Q and A
Problem Statement:
Write a Java method that formats a string by inserting a specified character at a specified interval from
the right. For example, if the input string is "1234567890", the character to insert is '-', and the interval is
3, the output should be "1-234-567-890".
sb.append(insertChar);
sb.append(input.charAt(i));
return sb.toString();
int interval = 3;
}
Question - 2
Check for Balanced Brackets in a String
Problem Statement:
Write a Java function that takes a string containing any combination of the characters '(', ')', '{',
'}', '[' and ']', and checks if the brackets in the string are balanced. A string is considered balanced
if every opening bracket has a corresponding closing bracket of the same type and the pairs of
brackets are properly nested.
Examples:
import java.util.Stack;
char x = expr.charAt(i);
stack.push(x);
continue;
// If current character is not opening bracket, then it must be closing. So stack cannot be empty at
this point.
if (stack.isEmpty())
return false;
char check;
switch (x) {
case ')':
check = stack.pop();
return false;
break;
case '}':
check = stack.pop();
return false;
break;
case ']':
check = stack.pop();
return false;
break;
}
// Check Empty Stack
return (stack.isEmpty());
// Function call
if (areBracketsBalanced(expr))
System.out.println("Balanced ");
else
Explanation:
This solution employs a Stack to keep track of the opening brackets encountered as we iterate
through the string. When we encounter a closing bracket, we pop the top of the stack (which
represents the most recently encountered opening bracket) and check if it matches the type of the
closing bracket. If at any point we find a mismatch, or if the stack is empty when we encounter a
closing bracket (indicating there's no corresponding opening bracket), we return false. If the
stack is empty after processing the entire string, it means every opening bracket had a matching
closing bracket, and we return true, indicating the brackets are balanced.
Question – 3
Find Missing Number in an Array
Problem Statement:
Given an array of n integers where the array elements are in a range from 1 to n+1. Every
number appears exactly once, hence one number is missing. Write a Java function to find the
missing number.
Examples:
int n = arr.length;
int total = (n + 1) * (n + 2) / 2; // Using the formula for the sum of first n natural numbers
total -= arr[i];
return total;
The function findMissingNumber calculates the sum of the first n+1 natural numbers using the formula
(n+1)∗(n+2)22(n+1)∗(n+2), where n is the length of the given array (since one number is missing in the array).
Then, it iterates through the array, subtracting each number from the total. The remaining total after this loop is the
missing number, as it accounts for the sum of all numbers from 1 to n+1 minus the sum of the array elements.
Question – 4
Implement a Custom String Formatter
Problem Statement Recap: Write a Java method that formats a string by inserting a specified
character at a specified interval from the right. For example, if the input string is "1234567890",
the character to insert is '-', and the interval is 3, the output should be "1-234-567-890".
int index = 0;
formattedString.append(input.charAt(index));
formattedString.append(input.charAt(index++));
}
return formattedString.toString();
int interval = 3;
Explanation:
The solution uses a StringBuilder to build the formatted string efficiently. It begins by
calculating the length of the first group of characters, which might be shorter than the specified
interval if the total length of the input string is not a multiple of the interval. After adding the
first group of characters to the StringBuilder, it iterates through the rest of the input string,
inserting the specified character at the specified interval and then adding the subsequent group of
characters up to the interval length or until the end of the string is reached.
Question – 5
Implement a Thread-safe Singleton Design Pattern
Problem Statement:
Design and implement a thread-safe Singleton design pattern in Java. A Singleton pattern
ensures that a class has only one instance and provides a global point of access to that instance.
The implementation must be thread-safe to ensure correct behavior when accessed by multiple
threads simultaneously.
// Private static variable of the same class that is the only instance of the class
private Singleton() {}
// Public static method that returns the instance of the class, this is the global access point for outer
world to get the instance of the singleton class
// Double-checked locking
synchronized (Singleton.class) {
return instance;
singleton.show();
Explanation:
This solution employs the "double-checked locking" idiom to reduce the use of synchronization
in getInstance(). The first check (if (instance == null)) is without synchronization,
which avoids the overhead of acquiring a lock every time the method is called after the first
initialization. If instance is null, synchronization is performed on the class object to ensure
that only one thread can execute the initialization block at a time. Within the synchronized block,
the second check ensures that instance has not been initialized by another thread while the
current thread was waiting to enter the synchronized block.
This pattern of double-checked locking is a common solution for implementing lazy initialization
in a thread-safe manner. However, it's important to note that it can be tricky to implement
correctly in languages other than Java because of memory model semantics. In Java, declaring
the instance variable volatile ensures visibility of its latest value to all threads, which is crucial
for the correctness of this pattern.