This post is a continuation of Top 25 Java Programming Interview Questions – Part 1 for any QA Automation interview. 

Question 13: Write a Java Program to generate Output "aabbbcccc" with the input "a2b3c4"

Solution 13: In the above problem, we have the numbers in the input. We need to print the as many characters same the number value.

package JavaInterviewQuestions;

public class ConvertNumricToCharExample {

static void convertNumToChar(String s) {

for(int i =0; i < s.length(); i++) {
if(Character.isAlphabetic(s.charAt(i))){
System.out.print(s.charAt(i));
}else {
int a = Character.getNumericValue(s.charAt(i));
for(int j =1; j <a; j++) {
System.out.print(s.charAt(i-1));
}
}
}

}

public static void main(String[] args) {

String str = "a2b3c4"; //output = aabbbcccc
convertNumToChar(str);

}

}

Question 14: Write a Java Program to print the product of an array except self?

Solution 14: In this problem, We need the output which is the product of the all the numbers in the array except self.
 Here we take two arrays, left_products and right_products in which we store the products of all numbers except self.

Then we multiply the left_products and right_products to get the output.

Below is the Java Program:

package JavaInterviewQuestions;

public class ProductArrayExceptSelfExample {

public static void main(String[] args) {

int[] arr = {1,2,3,4};
int N = arr.length;

int[] left_products = new int[N];
int[] right_products = new int[N];

int[] output_array = new int[N];
left_products[0] = 1;
right_products[N-1] = 1;

for(int i = 1; i < N; i++) {
left_products[i] = arr[i-1] * left_products[i-1];
}

for(int i = N-2; i >=0; i--) {
right_products[i] = arr[i+1] * right_products[i+1];
}

for(int i = 0; i < N; i++) {
output_array[i] = left_products[i] * right_products[i];
}

for(int i =0; i < N; i++) {
System.out.print(output_array[i] + " ");
}

}

}

Question 15: Write a Java Program to reverse a number using Stack.

Solution 15: In the above program, we will be using Stack to reverse a number. The idea is to get the digits using the % operator  and push each digit in the Stack. 

Once all digits are pushed in the stack, we pop each digit using the pop method.
Stack is LIFO datastructure thus the output number will be a number in a reverse order.

 Below is the Java Program:

package JavaInterviewQuestions;

import java.util.Stack;

public class ReverseNumberUsingStack {

static Stack<Integer> st = new Stack<>();

static void push_digits(int number) {
while (number != 0) {
st.push(number % 10);
number = number / 10;
}
}

static int reverse_number(int number) {
push_digits(number);
int reverse = 0;
int i = 1;

while (!st.isEmpty()) {
reverse = reverse + (st.peek() * i);
st.pop();
i = i * 10;
}

return reverse;
}

public static void main(String[] args) {

int number = 3997;
System.out.println(reverse_number(number));
}

}

The output to the above program would be 7993.


Question 16:  Write a Java Program to print the second largest number in a given array.

Solution 16: In this problem, to find the second largest number in the array, first we sort the array and then using the for loop we find the second largest number in reverse order.

 Below is the Java Program:

package JavaInterviewQuestions;

public class SecondLargestElementOfArray {

public static void main(String[] args) {

int[] arr = {2,3,1,6,9,9};
int temp;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

for(int i = arr.length -2; i >=0; i--) {
if(arr[i] != arr[arr.length-1]) {
System.out.println("The second largest element " + arr[i]);
break;
}
}

}

}

The output of the above program is 6. In this it also checks that the second largest number is not just based on index. It should be the second largest number in the array.


Question 17: Write a Java Program to print the first non repeating character in a given String.

Solution 17: In the above problem, to find the first non repeating character, first we create a hashmap object and store each character as key and its respective count as values.

Then we run a for loop, and check the value of each character is equal to 1. If it matches then that is the first non repeating character.

Below is the java program:

package JavaInterviewQuestions;

import java.util.HashMap;

public class FirstNonRepeatingCharacterinString {

public static char firstNonRepeat(String s) {

HashMap<Character, Integer> char_count = new HashMap<>();
for(int i = 0; i <s.length(); i++) {
char c = s.charAt(i);
if(char_count.containsKey(c)) {
char_count.put(c, char_count.get(c) + 1);
} else {
char_count.put(c, 1);
}
}

for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(char_count.get(c)== 1)
return c;
}
return '_';


}

public static void main(String[] args) {
System.out.println(firstNonRepeat("GeeksForGeeks"));

}

}

In the above program, the output is F.

Question 18: Write a Java Program to print the maximum consecutive ones in a given array.

Solution 18: In the above problem, we need to find the maximum consecutive ones in a given array.
To solve this, we run a for loop and check each index if it is equal to 1, we increase the counter. Then we use the Math.max() to find out the max counter value.

Below is the Java Program:

package JavaInterviewQuestions;

public class MaxConsecitivesOnesExample {

static void findConsectiveOnes(int[] nums) {

int count = 0;
int max = 0;

for (int i = 0; i < nums.length; i++) {
while( i < nums.length && nums[i] ==1) {
count++;
i++;
}

if(max< count) {
max = count;
}

count=0;

}
System.out.println(max);
}

public static void main(String[] args) {

int[] array = { 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1 };
findConsectiveOnes(array);

}

}

In the above program the output would be 5.


Question 19: Write a Java Program to print the first and last position of a number in a given array.

Solution 19: In this problem, we have been given a target value(in this case it is 8) and we need to find its first and last position of the target value.

Below is the java program :

package JavaInterviewQuestions;

public class FirstAndLastPositionExample {

public static void main(String[] args) {

int[] array = {5,7,7,8,8,10};

int firstIndex = -1;
int lastIndex = -1;

int target =8;

for(int i =0; i < array.length; i++) {
if(array[i] == target && firstIndex == -1) {
firstIndex = i;
}

if(array[i]== target && firstIndex != -1) {
lastIndex = i;
}
}

System.out.println("First Index is: " + firstIndex + " Last Index is: " + lastIndex);

}

}

Question 20: Write a Java Program to print numbers 1 to 100 without using any loop(for/while/do-while).

Solution 20: In this problem, to print the numbers between 1 to 100 we will use the if statement and check the condition.

We will check the condition i.e. num value should be less than equal to 100 and then increment it till it reaches to 100 and thus printing each number.

package JavaInterviewQuestions;

public class PrintNumWithoutUsingLoopExample {

public static void main(String[] args) {
printnum(1);

}

public static void printnum(int num) {
if (num <= 100) {
System.out.println(num);
num++;
printnum(num);

}

}

}

Question 21: Write a Java Program to shift all zeros on the right.

Solution 21: In this Java Program, we create a new array of the same length as the given array and assign all the non zero values in the new array.

Below is the Java Program:

package JavaInterviewQuestions;

import java.util.Arrays;

public class ShiftAllZerosRightExample {

public static int[] shiftAllZerosRight(int[] a) {
if (a.length == 1) {
return a;
}

int[] newArray = new int[a.length];

int count = 0;
for (int number : a) {
if (number != 0) {
newArray[count] = number;
count++;

}
}
return newArray;

}

public static void main(String[] args) {

int[] inputArray = { 1, 0, 2, 0, 3, 0, 0, 0 };

System.out.println(Arrays.toString(shiftAllZerosRight(inputArray)));

}

}

Question 22: Write a Java Program to remove the duplicates from an array.

Solution 22: In this problem, we need to find the total count of unique elements. We iterate through the array and check if the adjacent elements are not duplicate.

Below is the Java Program:

package JavaInterviewQuestions;

import java.util.Arrays;

public class RemoveDuplicateElementsExample {

static int removeDupElements(int[] arr) {
Arrays.sort(arr);
if (arr.length == 0)
return 0;
int j = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[j]) {
j++;
arr[j] = arr[i];
}
}

return j + 1;
}

public static void main(String[] args) {

int[] array = { 3, 2, 1, 1, 2, 2, 3, 2, 1, 3 };
System.out.println(removeDupElements(array));
}

}

In the above program, the unique elements are 1,2,3. So the total count is 3.

Question 23: Write a Java Program to iterate through the HashMap.

Solution 23: There are multiple ways to iterate through the HashMap. We can either use the keySet() or entrySet() and then using the iterator we can iterate through the given HashMap.

package JavaInterviewQuestions;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class HashMapIterateExample {

public static void main(String[] args) {

HashMap<String, String> hash_map = new HashMap<>();

hash_map.put("India", "New Delhi");
hash_map.put("France", "Paris");
hash_map.put("Germany", "Berlin");
hash_map.put("Australia", "Canberra");

// Iterator : Iterate by using keySet()
Iterator<String> it = hash_map.keySet().iterator();

while (it.hasNext()) {
String key = it.next();
String value = hash_map.get(key);
System.out.println("key: " + key + "==>" + "value: " + value);
}

System.out.println("**********************************");

// Iterate by using entrySet()

Iterator<Entry<String, String>> map_entry = hash_map.entrySet().iterator();

while (map_entry.hasNext()) {
Entry<String, String> entry = map_entry.next();
System.out.println("key: " + entry.getKey() + "==>" + entry.getValue());
}

}

}

Question 24: Write a Java Program to convert HashMap to ArrayList.

Solution 24: To solve this problem, we can convert the HashMap keys into an ArrayList and then the HashMap values into an ArrayList.

package JavaInterviewQuestions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HashMapToArrayListExample {

public static void main(String[] args) {

HashMap<String, String> hash_map = new HashMap<>();

hash_map.put("India", "New Delhi");
hash_map.put("France", "Paris");
hash_map.put("Germany", "Berlin");
hash_map.put("Australia", "Canberra");

// convert hashmap keys to ArrayList

List<String> countryNameList = new ArrayList<>(hash_map.keySet());
System.out.println("HashMap keys are: ");
for (String s : countryNameList) {
System.out.println(s);
}

System.out.println("************************");

// convert hashmap values to ArrayList
List<String> capitalNameList = new ArrayList<String>(hash_map.values());
System.out.println("HashMap values are: ");
for (String s : capitalNameList) {
System.out.println(s);
}

}

}

Question 25: Write a Java Program to print the missing number in a given Array.

Solution 25: To solve this problem, we first add the elements of the given array(sum1) and then add the range of elements of the array(sum2).
Then we subtract sum2 - sum1 which would give us the missing number in the given array.

package JavaInterviewQuestions;

public class MissingNumberInArrayExample {

public static void main(String[] args) {

int[] arr = { 1, 2, 3, 4, 5, 7, 8, 9, 10 };

int sum1 = 0;

for (int i = 0; i < arr.length; i++) {
sum1 = sum1 + arr[i];
}

int sum2 = 0;
for (int i = 1; i <= 10; i++) {
sum2 = sum2 + i;
}

System.out.println("Missing number in Array: " + (sum2 - sum1));

}

}


Tags


You may also like

Groups attribute in TestNG 

Groups attribute in TestNG 
Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}