Most Popular Java Programming Interview Questions
Q #1) Write a Java Program to reverse a string without using String inbuilt function.
Answer: Here, we are initializing a string variable str and are making use of the string builder class.
The object of the string builder class str2 will be further used to append the value stored in the string variable str.
Thereafter, we are using the inbuilt function of string builder (reverse()) and storing the new reversed string in str2.
Finally, we are printing str2.
1 public class FinalReverseWithoutUsingStringMethods {
2
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 String str = "Automation";
6 StringBuilder str2 = new StringBuilder();
7 str2.append(str);
8 str2 = str2.reverse(); // used string builder to reverse
9 System.out.println(str2);
10 }
11
12 }
Output:
noitamotuA
Q #2) Write a Java Program to reverse a string without using String inbuilt function reverse().
Answer:
Method 1:
There are several ways with which you can reverse your string if you are allowed to use the other string inbuilt functions.
In this method, we are initializing a string variable called str with the value of your given string. Then, we are converting that string into character array with toCharArray() function. Thereafter, we are using for loop to iterate between each character in reverse order and printing each character.
1 public class FinalReverseWithoutUsingInbuiltFunction {
2 public static void main(String[] args) {
3 String str = "Saket Saurav";
4 char chars[] = str.toCharArray(); // converted to character array and printed in reverse order
5 for(int i= chars.length-1; i>=0; i--) {
6 System.out.print(chars[i]);
7 }
8 }
9 }
Output:
varuaS tekaS
Method 2:
This is another method in which you are declaring your string variable str and then using Scanner class to declare an object with predefined standard input object.
This program will accept the string value through the command line (when executed).
We have used nextLine() which will read the input with the spaces between the words of a string. Thereafter, we have used a split() method to split the string into its substrings(no delimiter given here). Finally, we have printed the string in reverse order using for loop.
1 import java.util.Scanner;
2
3 public class ReverseSplit {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 String str;
8 Scanner in = new Scanner(System.in);
9 System.out.println("Enter your String");
10 str = in.nextLine();
11 String[] token = str.split(""); //used split method to print in reverse order
12 for(int i=token.length-1; i>=0; i--)
13 {
14 System.out.print(token[i] + "");
15 }
16
17 }
18
19 }
Output:
Enter your String
Softwaretestinghelp
plehgnitseterawtfoS
Method 3:
This is almost like method 2, but here we did not use the split() method. We have used the scanner class and nextLine() for reading the input string. Then, we have declared an integer length which has the length of the input string.
Thereafter, we have printed the string in the reverse order using for loop. However, we have used charAt(index) method which will return the character at any specific index. After each iteration, the character will be concatenated to reverse the string variable.
Finally, we have printed the reverse string variable.
1 import java.util.Scanner;
2
3 public class Reverse {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 String original, reverse = "";
8 System.out.println("Enter the string to be reversed");
9 Scanner in = new Scanner(System.in);
10 original = in.nextLine();
11 int length = original.length();
12 for(int i=length-1; i>=0; i--) {
13 reverse = reverse + original.charAt(i); //used inbuilt method charAt() to reverse the string
14 }
15 System.out.println(reverse);
16 }
17
18 }
Output:
Enter the string to be reversed
automation testing
gnitset noitamotua
Q #3) Write a Java Program to swap two numbers with using the third variable.
Answer: In this Example, we have made use of the Scanner class to declare an object with a predefined standard input object. This program will accept the values of x and y through the command line (when executed).
We have used nextInt() which will input the value of an integer variable ‘x' and ‘y' from the user. A temp variable is also declared.
Now, the logic of the program goes like this – we are assigning temp or third variable with the value of x, and then we are assigning x with the value of y and again we are assigning y with the value of temp. So, after the first complete iteration, the temp will have a value of x, x will have a value of y and y will have a value of temp (which is x).
1 import java.util.Scanner;
2
3 public class SwapTwoNumbers {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 int x, y, temp;
8 System.out.println("Enter x and y");
9 Scanner in = new Scanner(System.in);
10 x = in.nextInt();
11 y = in.nextInt();
12 System.out.println("Before Swapping" + x + y);
13 temp = x;
14 x = y;
15 y = temp;
16 System.out.println("After Swapping" + x + y);
17
18 }
19
20 }
Output:
Enter x and y
45
98
Before Swapping4598
After Swapping9845
Q #4) Write a Java Program to swap two numbers without using the third variable.
Answer: Rest all things will be the same as the above program. Only the logic will change. Here, we are assigning x with the value x + y which means x will have a sum of both x and y.
Then, we are assigning y with the value x – y which means we are subtracting the value of y from the sum of (x + y). Till here, x still has the sum of both x and y. But y has the value of x.
Finally, in the third step, we are assigning x with the value x – y which means we are subtracting y (which has the value of x) from the total (x + y). This will assign x with the value of y and vice versa.
1 import java.util.Scanner;
2
3 class SwapTwoNumberWithoutThirdVariable
4 {
5 public static void main(String args[])
6 {
7 int x, y;
8 System.out.println("Enter x and y");
9 Scanner in = new Scanner(System.in);
10
11 x = in.nextInt();
12 y = in.nextInt();
13
14 System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
15
16 x = x + y;
17 y = x - y;
18 x = x - y;
19
20 System.out.println("After Swapping without third variable\nx = "+x+"\ny = "+y);
21 }
22 }
Output:
Enter x and y
45
98
Before Swapping
x = 45
y = 98
After Swapping without a third variable
x = 98
y = 45
Q #5) Write a Java Program to count the number of words in a string using HashMap.
Answer: This is a collection class program where we have used HashMap for storing the string.
First of all, we have declared our string variable called str. Then we have used split() function delimited by single space so that we can split multiple words in a string.
Thereafter, we have declared HashMap and iterated using for loop. Inside for loop, we have an if else statement
in which wherever at a particular position, the map contains a key, we set the counter at that position and add the object to the map.
Each time, the counter is incremented by 1. Else, the counter is set to 1.
Finally, we are printing the HashMap.
Note: The same program can be used to count the number of characters in a string. All you need to do is to remove one space (remove space delimited in split method) in String[] split = str.split(“”);
1 import java.util.HashMap;
2
3 public class FinalCountWords {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 String str = "This this is is done by Saket Saket";
8 String[] split = str.split(" ");
9 HashMap<String,Integer> map = new HashMap<String,Integer>();
10 for (int i=0; i<split.length-1; i++) {
11 if (map.containsKey(split[i])) {
12 int count = map.get(split[i]);
13 map.put(split[i], count+1);
14 }
15 else {
16 map.put(split[i], 1);
17 }
18 }
19 System.out.println(map);
20 }
21
22 }
Output:
{Saket=1, by=1, this=1, This=1, is=2, done=1}
Q #6) Write a Java Program to iterate HashMap using While and advance for loop.
Answer: Here we have inserted three elements in HashMap using put() function.
The size of the map can get using size() method. Thereafter, we have used While loop for iterating through the map which contains one key-value pair for each element. Keys and Values can be retrieved through getKey() and getValue().
Likewise, we have used advanced for loop where we have “me2” object for the HashMap.
1 import java.util.HashMap;
2 import java.util.Iterator;
3 import java.util.Map;
4
5 public class HashMapIteration {
6
7 public static void main(String[] args) {
8 // TODO Auto-generated method stub
9 HashMap<Integer,String> map = new HashMap<Integer,String>();
10 map.put(2, "Saket");
11 map.put(25, "Saurav");
12 map.put(12, "HashMap");
13 System.out.println(map.size());
14 System.out.println("While Loop:");
15 Iterator itr = map.entrySet().iterator();
16 while(itr.hasNext()) {
17 Map.Entry me = (Map.Entry) itr.next();
18 System.out.println("Key is " + me.getKey() + " Value is " + me.getValue());
19 }
20 System.out.println("For Loop:");
21 for(Map.Entry me2: map.entrySet()) {
22 System.out.println("Key is: " + me2.getKey() + " Value is: " + me2.getValue());
23 }
24 }
25
26 }
Output:
3
While Loop:
Key is 2 Value is Saket
Key is 25 Value is Saurav
Key is 12 Value is HashMap
For Loop:
Key is: 2 Value is: Saket
Key is: 25 Value is: Saurav
Key is: 12 Value is: HashMap
Q #7) Write a Java Program to find whether a number is prime or not.
Answer: Here, we have declared two integers temp and num and used Scanner class with nextInt(as we have integer only).
One boolean variable isPrime is set to true. Thereafter, we have used for loop starting from 2, less than half of the number are entered and incremented by 1 for each iteration. Temp will have remainder for every iteration. If the remainder is 0, then isPrime will be set to False.
Based on isPrime value, we are coming to the conclusion that whether our number is prime or not.
1 import java.util.Scanner;
2
3 public class Prime {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 int temp, num;
8 boolean isPrime = true;
9 Scanner in = new Scanner(System.in);
10 num = in.nextInt();
11 in.close();
12 for (int i = 2; i<= num/2; i++) {
13 temp = num%i;
14 if (temp == 0) {
15 isPrime = false;
16 break;
17 }
18 }
19 if(isPrime)
20 System.out.println(num + "number is prime");
21 else
22 System.out.println(num + "number is not a prime");
23
24
25 }
26
27 }
Output:
445
445number is not a prime
Q #8) Write a Java Program to find whether a string or number is palindrome or not.
Answer: You can use any of the reverse string program explained above to check whether the number or string
is palindrome or not.
What you need to do is to include one if-else statement. If the original string is equal to a reversed string then the number is a palindrome, otherwise not.
1 import java.util.Scanner;
2
3 public class Palindrome {
4 public static void main (String[] args) {
5 String original, reverse = "";
6 Scanner in = new Scanner(System.in);
7 int length;
8 System.out.println("Enter the number or String");
9 original = in.nextLine();
10 length = original.length();
11 for (int i =length -1; i>=0; i--) {
12 reverse = reverse + original.charAt(i);
13 }
14 System.out.println("reverse is:" +reverse);
15
16 if(original.equals(reverse))
17 System.out.println("The number is palindrome");
18 else
19 System.out.println("The number is not a palindrome");
20
21 }
22 }
Output:
For String-
Enter the number or String
vijay
reverse is:yajiv
The number is not a palindrome
For Number-
Enter the number or String
99
reverse is:99
The number is palindrome
Q #9) Write a Java Program for Fibonacci series.
Answer: Fibonacci series is a series of numbers where after the initial two numbers, every occurring number is the sum of two preceding numbers.
For Example 0,1,1,2,3,5,8,13,21………
In this program, we have used Scanner class again with nextInt (discussed above). Initially, we are entering (through command line) the number of times the Fibonacci has to iterate. We have declared integer num and initialized a,b with zero and c with one. Then, we have used for loop to iterate.
The logic goes like a is set with the value of b which is 0, then b is set with the value of c which is 1. Then, c is set with the sum of both a and b.
1 import java.util.Scanner;
2
3 public class Fibonacci {
4 public static void main(String[] args) {
5 int num, a = 0,b=0, c =1;
6 Scanner in = new Scanner(System.in);
7 System.out.println("Enter the number of times");
8 num = in.nextInt();
9 System.out.println("Fibonacci Series of the number is:");
10 for (int i=0; i<=num; i++) {
11 a = b;
12 b = c;
13 c = a+b;
14 System.out.println(a + ""); //if you want to print on the same line, use print()
15 }
16 }
17 }
Output:
Enter the number of times
9
Fibonacci Series of the number is:
0
1
1
2
3
5
8
13
21
34
Q #10) Write a Java Program to iterate ArrayList using for-loop, while-loop, and advance for-loop.
Answer: In this program, we have inserted three elements and printed the size of the ArrayList.
Then, we have used While Loop with an iterator. Whenever the iterator has (next) element, it will display that element until we reach the end of the list. So it will iterate three times.
Likewise, we have done for Advanced For Loop where we have created an object called obj for the ArrayList called list. Then printed the object.
Thereafter, we have put the condition of For Loop where the iterator i is set to 0 index, then it is incremented by 1 until the ArrayList limit or size is reached. Finally, we have printed each element using a get(index) method for each iteration of For Loop.
1 import java.util.*;
2
3 public class arrayList {
4 public static void main(String[] args) {
5 ArrayList list = new ArrayList();
6 list.add("20");
7 list.add("30");
8 list.add("40");
9 System.out.println(list.size());
10 System.out.println("While Loop:");
11 Iterator itr = list.iterator();
12 while(itr.hasNext()) {
13 System.out.println(itr.next());
14 }
15 System.out.println("Advanced For Loop:");
16 for(Object obj : list) {
17 System.out.println(obj);
18 }
19 System.out.println("For Loop:");
20 for(int i=0; i<list.size(); i++) {
21 System.out.println(list.get(i));
22 }
23 }
24 }
Output:
3
While Loop:
20
30
40
Advanced For Loop:
20
30
40
For Loop:
20
30
40
No comments:
Post a Comment