Java Technical Programming Questions With Answers
Java Technical Programming Questions With Answers
It might be surprising, but there is no reverse() utility method in the String class.
But, it’s a very simple task. We can create a character array from the string and
then iterate it from the end to start. We can append the characters to a string builder
and finally return the reversed string.
return out.toString();
}
}
Bonus Points: Adding null check in the method and using StringBuilder for
appending the characters.
Easy to Miss: The indexing in Java starts from 0. So, we have to start at
“chars.length – 1” in the for loop.
It’s a slightly tricky question. It’s a three steps process. It’s better visualized in
code.
int a = 10;
int b = 20;
b = b + a; // now b is sum of both the numbers
a = b - a; // b - a = (b + a) - a = b (a is swapped)
b = b - a; // (b + a) - b = a (b is swapped)
We can’t return multiple variables in Java. Since Java is Pass-by-Value and these
are primitive data types, their values won’t change. For example, below swap
function will not change the input integer values.
We can use regular expression to check if the string contains vowels or not.
System.out.println(stringContainsVowels("Hello")); // true
System.out.println(stringContainsVowels("TV")); // false
return input.toLowerCase().matches(".*[aeiou].*");
System.out.println(isPrime(19)); // true
System.out.println(isPrime(49)); // false
}
return true;
}
}
But, this is not very memory and time-efficient. For a given number N, if there is a
prime number M between 2 to √N (square root of N) that evenly divides it, then N
is not a prime number.
The fibonacci number is generated by adding the previous two numbers – F(N) =
F(N-1) + F(N-2). We can use recursion to print fibonacci series.
We can use for loop and check each element one by one if they are odd or not.
If the list is huge, we can use parallel stream for faster processing.
7. Palindrome Check
A palindrome string is one whose reverse is also the same string. So we can
reverse the input string and check if both strings are equal or not. We can also use
the String charAt(int index) method to check for palindrome string.
for(char c : charArray) {
if (!Character.isWhitespace(c))
output.append(c);
}
return output.toString();
}
Java String class contains two methods to remove leading and trailing whitespaces
– trim(), and strip(). The strip() method was added to the String class in Java 11.
However, the strip() method uses Character.isWhitespace() method to check if the
character is a whitespace. This method uses Unicode code points whereas the
trim() method identifies any character having codepoint value less than or equal to
‘U+0020’ as a whitespace character.
The strip() method is the recommended way to remove whitespaces because it uses
the Unicode standard.
s = s.strip();
System.out.println(s);
Since String is immutable, we have to assign the strip() output to the string.
This question requires a deep understanding of sorting in Java. If you look at the
Arrays utility class, there are many overloaded sort() methods to sort primitive as
well as to object arrays.
If you are sorting a primitive array in the natural order, then it’s very simple. Just
use the Arrays.sort() method.
Arrays.sort(array);
System.out.println(Arrays.toString(array));
But, if you want to sort an array of Objects, then the object must
implement Comparable interface. If you want to specify the sorting criteria, then
you can pass the Comparator for the sorting logic. You should read more about
them at – Comparable and Comparator in Java.
t1.start();
Thread.sleep(5000);
t2.start();
Thread.sleep(5000);
t3.start();
F(n) = F(1)*F(2)…F(n-1)*F(n).
ll.add(1);
ll.add(2);
ll.add(3);
System.out.println(ll);
ll.descendingIterator().forEachRemaining(ll1::add);
System.out.println(ll1);
If you are looking from the data structures and algorithms perspective,
read reversing a linked list.
14. How to implement Binary Search?
The array elements must be sorted for implementing binary search. The binary
search algorithm is based on the following conditions.
If the key is less than the middle element, then we now need to search only in the
first half of the array.
If the key is greater than the middle element, then we need to only search in the
second half of the array.
And if the key is equal to the middle element in the array, then the search ends.
Finally, if the key is not found in the whole array, then it should return -1. This
indicates that the element is not present.
public static int binarySearch(int arr[], int low, int high, int key) {
int mid = (low + high) / 2;
Merge sort is one of the most efficient sorting algorithms. It works on the principle
of Divide and Conquers. It is based on the idea of breaking down a list into several
sub-lists until each sublist consists of a single element. Then merging those sublists
in a manner that results in a sorted list.
int i = 0;
int j = 0;
int k = 0;
if (i == one.length) {
if (j == two.length) {
return sorted;
}
if (lo == hi) {
int[] br = new int[1];
br[0] = arr[lo];
return br;
}
return merged;
}
Pattern programs are used a lot in interviews to understand the logical thinking
abilities of the interviewee. Pyramid patterns are very popular and once we get the
logic on the way it’s created, writing code to achieve the same is an easy task.
I have written an extensive post for different kind of pyramid patterns examples,
read it here.
We will first create a set of elements from both the arrays. Then compare the
elements in these sets to find if there is an element that is not present in both the
sets?
package com.journaldev.programminginterviews;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
System.out.println(sameElements(a1, a2));
System.out.println(sameElements(a1, a3));
return true;
}
}
It’s a very simple program. We can use for loop to iterate over the array elements
and add them to get the final sum.
int[] array = { 1, 2, 3, 4, 5 };
int sum = 0;
System.out.println(sum);
There are many ways to solve this problem. We can sort the array in natural
ascending order and take the second last value. But, sorting is an expensive
operation.
We can also use two variables to find the second largest value in a single iteration.
}
return secondHighest;
}
We can use Random class to generate random index numbers and shuffle the
elements.
int[] array = { 1, 2, 3, 4, 5, 6, 7 };
We can run the shuffling code inside another for loop to shuffle multiple rounds.
We can use Scanner class to read the file contents line by line. Then use String
contains() method to check if the string is present in the file or not.
The above code assumes that the string we are searching for in the file doesn’t
contain newline characters.
We can use SimpleDateFormat class to get the date string into specific formatting.
package com.journaldev.programminginterviews;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
scores.put("David", 95);
scores.put("Jane", 80);
scores.put("Mary", 97);
scores.put("Lisa", 78);
scores.put("Dino", 65);
System.out.println(scores);
scores = sortByValue(scores);
System.out.println(scores);
return sortedByValue;
}
String class doesn’t have any method to remove characters. We can use the
replace() method to create a new string without the given character.
System.out.println(str1); // bcdABCDbcdABCD
The string is immutable in Java. All the string manipulation methods return a new
string. So, it’s necessary that we assign it to another variable.
We can create the character array from the string. Then iterate over it and create a
HashMap with the character as key and their count as value.
for(char c : chars) {
if(charsCount.containsKey(c)) {
charsCount.put(c, charsCount.get(c)+1);
}else
charsCount.put(c, 1);
}
String s2 = s1; //s2 is also having the same reference to "Java" in the pool
s1 = "Python";
//s1 value got changed above, so how String is immutable?
//well, in the above case a new String "Python" got created in the pool
//s1 is now referring to the new String in the pool
//BUT, the original String "Java" is still unchanged and remains in the pool
//s2 is still referring to the original String "Java" in the pool
System.out.println(s2);
// prints "Java" supporting the fact that original String value is unchanged, hence String is
immutable
class Animal {
String color;
}
Java doesn’t allow extending multiple classes. It’s to keep it simple and avoid
diamond problem.
interface I {
void foo();
}
class A implements I{
public void foo() {}
}
class B implements I{
public void foo() {}
}
In above example, if Java would have allowed multiple class inheritance, then
which super foo() method should get called? There could be a mechanism to fix
this, but Java language developers thought it’s better to keep it simple by not
allowing multiple inheritance.
try {
FileInputStream fis = new FileInputStream("test.txt");
}catch(FileNotFoundException e) {
e.printStackTrace();
}
From Java 7 onwards, We can also catch multiple exceptions in a single catch
block. It’s useful when we have the same code in all the catch blocks.
That’s why it’s better to have null check in place for early validation.
import java.util.Map;
public record EmpRecord(int id, String name, long salary, Map<String, String> addresses)
{
}
Java 13 added text blocks as a preview feature. We can create multiline strings
using text blocks.
The switch expressions were added as a preview feature in Java 12. It became a
standard feature in Java 14 release. The below examples show switch expressions
as well as multi-label case statements.
int choice = 2;
};
System.out.println(result); // TTH
35. How to Compile and Run a Java Class from Command Line?
javac Test.java
java Test
From the recent releases, java command will take care of compilation also if the
class file is not present.
If our class requires some additional JARs to compile and run, we can use the -cp
java option.
All Enum implicitly extends java.lang.Enum class and implements Serializable and
Comparable interfaces.
Enum can have methods also, read more at Enums in Java.
The forEach() method provides a shortcut to perform an action on all the elements
of an iterable. Let’s say we have to iterate over the list elements and print it.
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
We can use forEach() method with lambda expression to reduce the code size.
list.forEach(System.out::print);
Java 8 introduced default and static methods in interfaces. This has bridged the gap
between interfaces and abstract classes.
The major benefit of java 8 functional interfaces is that we can use lambda
expressions to instantiate them and avoid using bulky anonymous class
implementation.
@FunctionalInterface
interface Foo {
void test();
}
When a class have two or more methods with the same name, they are called
overloaded methods.
class Foo {
void print(String s) {
System.out.println(s);
}
When a superclass method is also implemented in the child class, it’s a case of
overriding.
class Base {
void printName(){
System.out.println("Base Class");
}
}
1. String s1 = "abc";
2. String s2 = "abc";
3. System.out.println("s1 == s2 is:" + s1 == s2);
4. Output: false
5. String s3 = "JournalDev";
6. int start = 1;
7. char end = 5;
8. System.out.println(start + end);
9. System.out.println(s3.substring(start, end));
10.Output: ourn
Explanation: The given statements output will be “ourn”. First character will
be automatically type caste to int. After that since in java first character
index is 0, so it will start from ‘o’ and print till ‘n’. Note that in String
substring function it leaves the end index.
17.Output: 100
Explanation: The size of the shortSet will be 100. Java Autoboxing feature
has been introduced in JDK 5, so while adding the short to HashSet<Short>
it will automatically convert it to Short object. Now “i-1” will be converted
to an int while evaluation and after that it will autoboxed to Integer object
but there is no Integer object in the HashSet, so it will not remove anything
from the HashSet and finally its size will be 100.
18.What will be the boolean “flag” value to reach the finally block?
19. try {
20. if (flag) {
21. while (true) {
22. }
23. } else {
24. System.exit(1);
25. }
26. } finally {
27. System.out.println("In Finally");
28. }
Explanation: The finally block will never be reached here. If flag will be
TRUE, it will go into an infinite loop and if it’s false it’s exiting the JVM.
So finally block will never be reached here.
37.Output: abc
Explanation: The x.concat(y) will create a new string but it’s not assigned to
x, so the value of x is not changed.
Explanation: This is a tricky question, it looks like the test is about the order
of execution of the mathematical operators and syntax of main method will
get overlooked. It will produce Runtime error because main method is
not static, something like below.
package com.journaldev.programming-interviews;