Java Programming Interview Questions
This post is related to programming questions that are asked in interview for freshers and
experienced both to check the base.
First we need to understand the question , we need to write an algorithm for the first non repeated character in a string , for example :
If the word "participation" is input then it should print 'r' as output .
If the word "teeter" is input then it should print 'r' as output .
If the word "stress" is input then it should print 't' as output .
Logic
Pseudo Code
1. First create the character count hash table .
For each character
If there is no value stored in the character
set it to 1 .
else
increment the value of the character by 1 .
2. Scan the string
For each character
return character if the count in hash table is 1 .
If no character have count 1 , return null
Code :
package basiccode;
import java.util.HashMap;
import java.util.Scanner;
public class FirstNonRepeatedCharacter {
public static void main(String args[]){
System.out.println("Please Enter the input string:::");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char c= firstNonRepetableCharter(s);
System.out.println("First Non Repetable character is==>"+c);
}
private static Character firstNonRepetableCharter(String s) {
HashMap<Character,Integer> hmap = new HashMap<Character,Integer>();
int length;
Character c;
length= s.length();// scan and build hash table
for(int i=0;i<length;i++){
c=s.charAt(i);
if(hmap.containsKey(c)){
hmap.put(c, hmap.get(c)+1);
}
else{
hmap.put(c,1);
}
}
// Search hmap in in order of string str
for(int i=0;i<length;i++){
c=s.charAt(i);
if(hmap.get(c)==1){
return c;
}
}
return null;
}
}
Question .2 ➤ How to reverse a String in java?
Pseudo Code Method 1:
1. The user will input the string to be reversed.
2. First we will convert String to character array by using the built in java String class method toCharArray().
3. Then , we will scan the string from end to start, and print the character one by one.
2. First we will convert String to character array by using the built in java String class method toCharArray().
3. Then , we will scan the string from end to start, and print the character one by one.
Code->
public class ReverseString {
public static void main(String args[]){
String input="";
System.out.println("Enter the input String");
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
System.out.println(input);
char[] charArr=input.toCharArray();
for(int i=charArr.length-1;i>=0;i--){
System.out.print(charArr[i]);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Method-2
String class does not have reverse method but we could use
built in reverse() method of the StringBuilder class
public class reverseString {
public static void main(String[] args) {
String input="MyInput";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1=input1.reverse();
for (int i=0;i<input1.length();i++)
System.out.print(input1.charAt(i));
}}
Method-3
1.
Convert the input string into character array by using the toCharArray() built in method of the String Class .
2.
In this method we will scan the character array from both sides , that is from the start index (left) as well as from last index(right) simultaneously.
3.
Set the left index equal to 0 and right index equal to the length of the string -1.
4.
Swap the characters of the start index scanning with the last index scanning one by one .After that increase the left index by 1 (left++) and decrease the right by 1 i.e (right--) to move on to the next characters in the character array .
5.
Continue till left is less than or equal to the right .
write below code in main method::
String str="Devenra";
char[] inputArr=str.toCharArray();
int left,right=0;
right=inputArr.length-1;
for(left=0;left<right;left++,right--){
//swap left and right values
char temp = inputArr[left];
inputArr[left]=inputArr[right];
inputArr[right]=temp;
}
for(char c:inputArr){
System.out.print(c);
System.out.println();
}
Method-4
use recursion to reverse the string.
//Mehod 4 using Recursion
String input1 = "Devendra";
//create Method and pass input string as parameter
String reversed = reverseString(input1);
System.out.println("The reversed string is: " + reversed);
private static String reverseString(String input) {
if (input.isEmpty()){
return input;
}
//Calling Function Recursively
return reverseString(input.substring(1))+input.charAt(0);
}
Question 3.➤How to Determine if String has all unique characters
Input : Alive is awesome
Output : false
Input : Show Rev
Output: true
Output : false
Input : Show Rev
Output: true
1.
For this method we need to know about two inbuilt functions in java , indexOf() which returns the index of first occurrence of the character in the string , while second function lastIndexOf() returns the index of last occurence of the character in the given string.
2. First , we convert the given inputstring into characterarray by using toCharArray() function.
3. Calculate the indexOf() and lastIndexOf() for each character in the given inputstring
4. If both are equal then continue and make result= true
else set flag result = false
5. Return result
Code-
public class UniqueChar {
public static void main (String args[])
{
boolean result=false;
String inputstring="Alive is awesome";
System.out.println("String method 4 answer "+ checkuniqueChar(inputstring));//false
String inputstring2="Show Rev";
System.out.println("String method 4 answer "+ checkuniqueChar(inputstring2));//true
}
private static boolean checkuniqueChar(String inputstring) {
boolean result=true;
for(char ch:inputstring.toCharArray()){
if(inputstring.indexOf(ch)==inputstring.lastIndexOf(ch)){
result=true;
}
else{
result=false;
break;
}
}
return result;
}
}
Question 3.➤How to count number of words present in given string
package basiccode.allstring.examples;
public class WordCount {
static int i,c=0,res;
public static void main(String args[]){
res=WordCount.wordcount(" jony jony yes papa ");
//string is always passed in double quotes
System.out.println("The number of words in the String are : "+res);
}
private static int wordcount(String s) {
char ch[]= new char[s.length()]; //in string especially we have to mention the () after length
int count=0;
for(int i=0;i<s.length();i++){
ch[i]= s.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) ) {
count++;
}
}
return count;
}
}
Question 4.➤Java Program to remove all the white-spaces in the String?
The process of removing all the white spaces in the string is called squeezing.
Squeezing is the combination of left trimming ,right trimming and the trimming of spaces that exist between the words.
for example :
If the original string is : " Devendra is here "
after squeezing
"Devendraishere"
If the original string is : " Devendra is here "
after squeezing
"Devendraishere"
code:
squeeze(String s) { for(i=0;i<s.length();i++) { char ch=s.charAt(i); if(ch != ' ') System.out.print(ch); } }
Question 5.➤ Java code to write Armstrong number
If the sum of the cubes of the digit is equal to the number then the number is called as Armstrong number .
Armstrong number is also known as narcissistic number or a plus perfect number.
Let k be the number of digits in a number, n, and d1,d2,d3,d4... be the digits of n.
Armstrong iff n=d1k+d2k+d3k+d4k+...
Code-
public class CheckArmestornNumber {
public static void main(String args[]){
boolean isArmestron=false;
String s="371";
int x= Integer.parseInt(s);
int sum=0;
int temp=0;
temp=x;
int divd,rem=0;
while(x!=0){
rem=x%10;
x=x/10;
sum=sum+(rem*rem*rem);
}
System.out.print(temp+" "+sum+" ");
if(temp==sum){
isArmestron=true;
}
if(isArmestron)
System.out.println("The number is Armestrong number::");
}
}
Question 6.➤ Anagram Program
what is Anagram?
If two strings contain same set of characters but in different order then the two
strings are called anagrams.
for example :
1. "LISTEN" and "SILENT"
2. "ton" and "not"
3. "TRIANGLE" and "INTEGRAL"
Code-
public class AnagramString {
public static void main(String args[]){
boolean result = isAnagram("LISTEN","SILENT");
System.out.println(result);
if(result)
System.out.println("The two strings are"
+ " anagram of each other");
}
private static boolean isAnagram(String s1, String s2) {
//first remove all white space and convert string to lower case letter
s1=s1.replaceAll("\\s", "").toLowerCase();
s2=s2.replaceAll("\\s", "").toLowerCase();
//2. check the length of strings are equal or not
if(s1.length()!=s2.length())
return false;
//3. sort the arry by converting to array
char[] f1Array=s1.toCharArray();
char[] f2Array=s2.toCharArray();
Arrays.sort(f1Array);
Arrays.sort(f2Array);
// Compare sorted strings
for (int i = 0; i < f1Array.length; i++)
if (f1Array[i] != f2Array[i])
return false;
return true;
}
}
Question 7.➤ Programs In Java to Count Occurrences Of Character In String
public class EachCharacterCountInString
{
public static void main(String[] args)
{
characterCount("Alive is Awesome");
characterCount("Java Hungry");
characterCount("USA has 50 states");
}
static void characterCount(String inputString)
{
//Creating a HashMap, key :Character value : occurrences as Integer
HashMap<Character, Integer> eachCharCountMap = new HashMap<Character, Integer>();
//Converting inputString to char array
char[] charArray = inputString.toCharArray();
//traversal of each Character of charArray
for (char c : charArray)
{
if(eachCharCountMap.containsKey(c))
{
//If char is present in eachCharCountMap, increment count by 1
eachCharCountMap.put(c, eachCharCountMap.get(c)+1);
}
else
{
//If char is not present in eachCharCountMap,
//Putting this char to eachCharCountMap with 1 as it's initial value
eachCharCountMap.put(c, 1);
}
}
//Showing the eachCharCountMap
System.out.println(eachCharCountMap);
}
}
Question .8➤Print all permutations of the String ?
In maths ,
you can calculate how many permutations of the word are possible , by using the formula
nPr = n! / (n-r)!
- Define a string.
- Fix a character and swap the rest of the characters.
- Call the generatePermutation() for rest of the characters.
- Backtrack and swap the characters again.
Output:
All the permutations of the string are:
ABC
ACB
BAC
BCA
CBA
CAB
Question .9➤Palindrome Program in Java
Question .➤ Different Number Pattern Programs In Java
https://javacmlearning.blogspot.com/2019/10/different-number-pattern-programs-in.html
No comments:
Post a Comment
Note: only a member of this blog may post a comment.