Question 1: Write a Java Program to reverse a String.

Solution 1: As asked in the above question, we need to reverse a String. For Ex:
The Input is : "RahulShettyAcademy"
Output should be : "ymedacAyttehSluhaR"

This problem can be solved by writing a simple for loop and print the string in the reverse.

public class ReverseAStringExample {

public static void main(String[] args) {

String inputString = "RahulShettyAcademy";
String outputString = "";

/*
* Writing a for loop and looping in the reverse order to get the reverse String
* as output.
*/

for (int i = inputString.length() - 1; i >= 0; i--) {
outputString = outputString + inputString.charAt(i);
}

System.out.println(outputString);
}

}

This will print the outputString which will be the reverse of the given inputString.

Question 2:  Write a Java Program to swap two given Strings

Solution 2. As asked in the above question, for swapping of two strings we need to use the substring method of the String class in Java.
Substring method returns part of the string.

We have the start index and end index in the substring method where
start index is inclusive and end index is exclusive.

Below is the Java Program to swap two Strings.

package JavaInterviewQuestions;

public class StringSwapExample {

public static void main(String[] args) {

// Take two string s1 and s2 which we need to swap.
String s1 = "Rahul";
String s2 = "Shetty";

// Combine both the strings s1 and s2 using the concatenation(+) operator
s1 = s1 + s2;

// Use the substring method to get the subset of the combined string
s2 = s1.substring(0, s1.length() - s2.length());
s1 = s1.substring(s2.length());

System.out.println("s1 =" + s1);
System.out.println("s2 =" + s2);

}

}

The above program will swap the two Strings s1 and s2.

Question 3: Write a Java Program to print the Fibonacci Series.

Solution 3. As we know Fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers.

For writing a Java Program, first we declare an array and assign the values 0 and 1 to the indexes 0 and 1 of the defined array.
Then we write the logic to get the values of all the indexes of the total Fibonacci series length.

Below the java program to print the Fibonacci series.

package JavaInterviewQuestions;

import java.util.Scanner;

public class FibonacciSeriesExample {

public static void main(String[] args) {

int fiblength;

// Use scanner class to get the user input.
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number : ");
fiblength = sc.nextInt();

int[] num = new int[fiblength];
// Assign values 0 and 1 to the 0 and 1 indices of the defined array
num[0] = 0;
num[1] = 1;

// Logic for getting the values of all the indices of the array using for loop
for (int i = 2; i < fiblength; i++) {
num[i] = num[i - 1] + num[i - 2];
}

System.out.print("fibonacci series: ");
// Printing the fibonacci series
for (int i = 0; i < fiblength; i++) {
System.out.print(num[i] + " ");
}

}

}

The above program will print the Fibonacci series upto the total length i.e. fiblength entered by the user.

Question 4: Write a Java Program to check if a number is Armstrong number or not.

Solution 4: An Armstrong Number is a number in which the sum of the cubes of each digit is equal to the number itself. For ex:

 371 = 3*3*3 + 7*7*7 + 1*1*1

The sum of the cubes is 3,7,1 is equal to 371.Another example is 153 which is an Armstrong number. You can explore other numbers too!!!

Below is the Java Program to check the number is Armstrong or not.

package JavaInterviewQuestions;

public class CheckArmstrongNumberExample {

public static void main(String[] args) {

int num = 371;
int actualnum = num;
double result = 0;

while (actualnum != 0) {
int n = actualnum % 10;
result = result + Math.pow(n, 3);
actualnum = actualnum / 10;
}

if (result == num) {
System.out.println(num + " is an Armstrong number");
} else {
System.out.println(num + " is not an Armstrong number");
}

}

}

The above program would give the output whether a number is Armstrong number.

Question 5: Write a Java Program to print the sum of digits of a given integer.

Solution 5: We can solve the question using a while loop. Using the % operator we get the remainder and keep adding to the sum variable until the number becomes 0. The total sum will be the total of all the digits of the given integer.

Below is the java program :

package JavaInterviewQuestions;

public class SumDigitsExample {

public static int getSumOfAllDigits(int num) {

// Declare variable sum which will store the sum of all digits.
int sum = 0;

// Run a while loop until the num becomes 0.
while (num != 0) {
int rem = num % 10;
sum = sum + rem;
num = num / 10;
}
return sum;

}

public static void main(String[] args) {

// We can pass any integer value of whose sum of the digits is required.
System.out.println(getSumOfAllDigits(549));
}

}

The above program will print the sum of all digits in the console. In the above case, as the input value is 549
the output returned will be 18.

Question 6: Write a Java Program to check if a number is Prime or not.

Solution 6. A prime number is a number which is divisible by 1 and itself. This problem can be solved by a simple for loop and we check the condition that the given number returns a remainder value.

If the remainder is 0, then the number is not prime. Else its a prime number.

Below is the Java Program:

package JavaInterviewQuestions;

public class PrimeNumberExample {

public static boolean isPrime(int num) {
// Validate that the number is neither less than 1 nor equal to 1.
// It should return false as it cannot be a prime number
if (num <= 1)
return false;

// Logic to check if a number is prime or not. If its Prime, returns true else
// return false
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}

return true;

}

public static void main(String[] args) {
// Pass the integer value to check whether it is prime or not.
System.out.println(isPrime(8));

}

}

The above program will return false as 8 is not a prime number.

Question 7:  Write a Java Program to count the number of characters in a given String.

Solution 7: We can use hashmap for counting the number of each character in the given string.
We create hashmap object to store each character as key and the total count of characters as its value.

Then we print the hashmap object.

package JavaInterviewQuestions;

import java.util.HashMap;

public class CountNumOfCharsInStringExample {

static void characterCount(String inputString) {

// Creating a hashmap object.
HashMap<Character, Integer> hash_map = new HashMap<>();
char[] strArray = inputString.toCharArray();

for (char c : strArray) {
if (hash_map.containsKey(c)) {
hash_map.put(c, hash_map.get(c) + 1);
}

else {
hash_map.put(c, 1);
}

}
// Print the hashmap object which gives the number of each character in String.
System.out.println(hash_map);

}

public static void main(String[] args) {
// Input value which needs to be passed in the below method.
characterCount("rahulshettyacademy");

}

}

In the above program as we are printing the hashmap object, it will print each character with the total number of count in the console.

Question 8: Write a Java Program to find the duplicates of a given String.

Solution 8: HashMap is used to store elements in the form of key value pairs. We create a hashmap object and store each character as key
and the total count of each character as value.

Then we check the keys whose values are more than 1 using the keySet() method. Thus we get the duplicates in the given String.

package JavaInterviewQuestions;

import java.util.HashMap;
import java.util.Set;

public class DuplicateCharsInStringExample {

static void duplicateChars(String inputString) {

// Creating a hashmap object.
HashMap<Character, Integer> hash_map = new HashMap<>();
char[] strArray = inputString.toCharArray();

for (char c : strArray) {
if (hash_map.containsKey(c)) {
hash_map.put(c, hash_map.get(c) + 1);
}

else {
hash_map.put(c, 1);
}

}
// Store the key values in a set and then get the number of each duplicate character.
Set<Character> keys = hash_map.keySet();
for (char c : keys) {
if (hash_map.get(c) > 1) {
System.out.println(c + "-->" + hash_map.get(c));
}
}

}

public static void main(String[] args) {
// Input value which needs to be passed in the below method.
duplicateChars("rahulshettyacademy");

}

}

The above program will print all the duplicates in the given String in the console.
 The output would be : 

a-->3
t-->2
e-->2
h-->2
y-->2


Question 9: Write a Java Program for swapping of 2 numbers.

Solution 9: In this problem , we would be given two numbers as input. We need to swap those 2 numbers which can be done a simple logic.

Below is the java program.

package JavaInterviewQuestions;

public class SwapNumbersExample {

public static void main(String[] args) {

int num1 = 10;
int num2 = 20;

// Logic to swap 2 numbers.
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;

System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}

}

The above program would swap the two integer values num1 and num2.

Question 10: Write a Java Program to reverse an array?

Solution 10: In this problem, we are given an array of characters as input. This problem can be solved by writing a while loop.

By using a third variable, we reverse the array as below.

package JavaInterviewQuestions;

public class ReverseAnArray {

public static void main(String[] args) {

char[] s = { 'a', 'b', 'c', 'd', 'e' };

int right = s.length - 1;
int left = 0;

while (left < right) {
char c = s[left];
s[left] = s[right];
s[right] = c;

// Increment the left by 1 and Decrement the right by 1
left += 1;
right -= 1;
}

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

}

}

The above program gives the output: e d c b a. Thus reverse the array.

Question 11: Write a Java Program to get the count of Capitalized words in a String.


Solution 11:  Capitalized words in a given String which are those words which starts with a Capital Letter.
We need the total count of these words. This problem can be solved by using a for loop and iterate through each character in the String. 

We also take a counter variable and increment it when any Capital character is encountered.

package JavaInterviewQuestions;

public class CountCapitalizedWordsInString {

public static int getCapsWordsInString(String inputString) {

int counter = 0;
for(int i = 0; i < inputString.length(); i++) {
if(inputString.charAt(i) >= 'A' && inputString.charAt(i) <= 'Z') {
counter++;
}
}
return counter;
}

public static void main(String[] args) {
System.out.println(getCapsWordsInString("RahulShettyAcademy"));
}

}

The above program will return the total count of Capitalized String i.e. 3.

Question 12: Write a Java Program to find the longest consecutive occurrence of integers in a given array.

Solution 12: In this problem, we need to find the length of the longest consecutive occurrence.
As given in the array below, we have an array of integers. As you can see the longest consecutive occurrence of integers are 6,7,8,9. There is a consecutive increment of 1 . So the output will be 4.

package JavaInterviewQuestions;

public class LongestConsecutiveOccurenceExample {

public static void main(String[] args) {

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

int count = 0;
int max =0;

for(int i = 0; i < arr.length-1; i++) {
if(arr[i] +1== arr[i+1]) {
count++;
}else {
count = 0;
}

max = Math.max(max, count+1);
}
System.out.println(max);
}

}

The above program will give the output as 4. We use the Math.max() to obtain the maximum value between the max and the counter variable.


Tags


You may also like

API Basics and Architecture

API Basics and Architecture
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"}