Top 70 Java Program Interview Questions: Here, we will list down all the Java Programs.
No | Input | Output | Link |
---|---|---|---|
1 | dadeadrs | dddaaers | Link |
2 | int [] ar = {3,8,2,3,3,2}; int [] ar1 = {7,1,2,8,2}; int [] ar2 = {3,1,4,1,5}; int [] ar3 = {5,5,5,5,5,5}; int [] ar4 = {5,5,5,5,5}; | int[] intArray = {3,8,2,3,3,2}; // Output : 3 int[] intArray1 = {7,1,2,8,2}; // Output : 2 int[] intArray2 = {3,1,4,1,5}; // Output : 0 int[] intArray3 = {5,5,5,5,5,5}; // Output : 0 int[] intArray4 = {5,5,5,5,5}; // Output : 5 | Link |
3 | Today is January 5th | 5thJa nu aryisTo day | Link |
4 | 1234 | [1234, 11223344, 111222333444, 1111222233334444] | Link |
5 | AAAADDDCCCA | A4D3C3A1 | Link |
6 | [1,2,2,3,4,5,5,3] | [1,3,4,3] | Link |
7 | he is a good boy | yo bd o ogas ieh | Link |
8 | {“looking”, “you”, “handsome”, “are”} | [you, are, looking, handsome] | Link |
9 | reverse me without split | esrever em tuohtiw tilps | Link |
10 | My n@me is 12Rahul | yM em@n si 12luhaR | Link |
11 | amZgxY | x | Link |
12 | {1,2,3,4,5} | 21435 | Link |
13 | {2,1,1,4,5,5,6,7} | [2, 4, 6, 7] | Link |
14 | [()]{}{[()()]()} | balanced | Link |
15 | AAABBBBCC | A3B4C2 | Link |
16 | weelccoommee hhoommeee | welcome home | Link |
17 | abCdefGHijkl | ab Cdef G Hijkl | Link |
18 | abc | abc,acb,bac,bca,cba,cab, | Link |
19 | test986java656hello | tset986avaj656olleh | Link |
20 | String input1 = “38”; String input2 = “1485631”; String input3 = “0”; | String input1 = “38”;———>2 String input2 = “1485631”;—>1 String input3 = “0”;———>0 | Link |
21 | {1,2,3,4,9,5,6,7,8,10,0} | The Combinations in the array whose sum is 10 are: (1,9) (2,8) (3,7) (4,6) (5,5) (0,10) | Link |
22 | Automation Testing | aUTOMATION tESTING | Link |
23 | Monojjonon | Character occurrence in a string- {j=2, M=1, n=3, o=4} Min Value : 1 Max Value : 4 Ascending order values – {M=1, j=2, n=3, o=4} | Link |
24 | [ 1,2,3,4 ] | [ 24,12,8,6 ] | Link |
25 | Hello Interview Is Going On Now | hello interview is going on now | Link |
26 | {2,3,4,1,4,5} | 1 | Link |
27 | {1 , 2 , 3 , 4 , 5 , 5 } | 1 2 3 4 5 5 | Link |
28 | 01230 | 03210 | Link |
Java Programs
Input String arr[] = {“Rama”, “Test”, “Type”, “Tata”}
Output should be – “RTTTaeyamsptatea”
Java Program Interview Concatenate Characters From Each String: This program aims to concatenate characters from each string in an input array based on their positions. It utilizes a LinkedHashMap to store the characters at each position and then generates the expected output string. The output for the given input array {“Rama”, “Test”, “Type”, “Tata”} would be “RTTTaeypmsptatea”.
Input: {“Rama”, “Test”, “Type”, “Tata”}
Output: RTTTaeyamsptatea
For More Java Interview Programs, you Can check Here.
Concatenate Characters From Each String
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; public class InterviewPrograms1 { // For More Programs Visit: https://www.softwaretestingo.com/ /*Input String arr[] = {"Rama", "Test", "Type", "Tata"} Output should be - "RTTTaeyamsptatea" */ public static void main(String[] args) { String arr[] = {"Rama", "Test", "Type", "Tata"}; System.out.println("Inpu Array Is: "+ "{\"Rama\", \"Test\", \"Type\", \"Tata\"}"); LinkedHashMap<Integer, ArrayList<String>> map= new LinkedHashMap<>(); String ans=""; for (int i = 0; i<=arr.length-1; i++) { String word= arr[i]; for (int j = 0; j <=word.length()-1; j++) { ArrayList<String> list= new ArrayList<>(); if(map.containsKey(j)) { ArrayList<String> list1= map.get(j); list1.add(String.valueOf(word.charAt(j))); map.put(j, list1); } else { list.add(String.valueOf(word.charAt(j))); map.put(j, list); } } } for(Map.Entry<Integer, ArrayList<String>> e:map.entrySet()) { // System.out.print(e.getKey()+"" +e.getValue()); ArrayList<String> l1= e.getValue(); for (int i = 0; i <=l1.size()-1; i++) { ans=ans+l1.get(i); } } System.out.println("Expected Output Is: "+ans); } }
Output:
Inpu Array Is: {"Rama", "Test", "Type", "Tata"} Expected Output Is: RTTTaeyamsptatea
Explanation:
Here’s the flow of the Java program:
- Import the necessary classes from the java.util package.
- Declare a public class named InterviewPrograms1 in the com.softwaretestingo.interviewprograms package.
- Within the class, define the main method, which is the entry point of the program.
- Declare and initialize an array of strings named arr with the given input values.
- Print the input array to the console for reference.
- Create a LinkedHashMap named map to store characters based on their positions.
- Declare an empty string named ans to hold the final concatenated output.
- Start a loop to iterate over each element in the arr array.
- Within the loop, assign the current element to a string variable named word.
- Start a nested loop to iterate over each character in the word string.
- Create a new ArrayList named list to store the characters for the current position.
- Check if the map already contains the current position j.
- If the map contains the position j, retrieve the existing list from the map, add the current character to the list, and put the updated list back into the map.
- If the map does not contain the position j, create a new list, add the current character to it, and put the list into the map at position j.
- After processing all characters in the current string, the outer loop proceeds to the next string in the arr array.
- Iterate over the entries in the map.
- Retrieve the characters stored at each position and assign them to an ArrayList named l1.
- Iterate over each character in l1 and append it to the ans string.
- Finally, print the expected output, which is the concatenated string stored in ans.
Alternative Way:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms1_1 { public static void main(String[] args) { String[] strArray = { "Rama", "Test", "Type", "Tata" }; int maxLength = 0; for (String str : strArray) { maxLength = str.length(); } String result = ""; for (int i = 0; i < maxLength; i++) { for (String str : strArray) { if (i < str.length()) { result = result + str.charAt(i); } } } System.out.println(result);//RTTTaeyamsptatea } }
Output:
RTTTaeyamsptatea
That’s the flow of the Java program. It takes an array of strings, processes them to concatenate characters based on their positions, and produces the expected output.
Input: today110is210my310interview
Output: yadot110si210ym310weivretni
Reverse Characters Only From String: This Java program aims to reverse the order of non-numeric substrings within a given input string while keeping the numeric substrings unchanged.
Reverse Characters Only With Out Changing The Digits
Input – today10is20my30interview.
Output- yadot10si20ym30weivretni.

Solution 1:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms2 { // For More Programs Visit: https://www.softwaretestingo.com/ /* Input - today10is20my30interview. * Output- yadot10si20ym30weivretni. */ public static void main(String[] args) { String s = "today110is210my310interview"; String[] arr = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); for (int i = 0; i< arr.length; i++) { if(!Character.isDigit(arr[i].charAt(0))) { arr[i] = String.valueOf(new StringBuilder(arr[i]).reverse()); } } System.out.println(String.join("", arr)); } }
Output:
Input: today110is210my310interview Output: yadot110si210ym310weivretni
Here’s a step-by-step explanation of the program:
- The program starts by defining a class named “InterviewPrograms2” in the package “com.softwaretestingo.interviewprograms”.
- The main method is declared as public and static, allowing it to be accessed without creating an instance of the class.
- A string variable named “s” is declared and assigned the value “today110is210my310interview”.
- The input string “s” is printed using the System.out.println() statement.
- The string “s” is split into an array of strings using the split() method with a regular expression as the parameter. The regular expression matches the positions between a non-digit character followed by a digit, or a digit followed by a non-digit. This effectively separates the alphabets and digits into separate elements in the array.
- A for loop is used to iterate over each element in the array.
- Within the loop, an if condition checks if the first character of the current array element is not a digit using the Character.isDigit() method.
- If the condition is true, it means the element contains alphabets. In this case, the element is reversed using a StringBuilder and converted back to a string using the toString() method.
- Finally, the modified array is printed as the output using the System.out.println() statement. The elements are joined together using the join() method of the String class, with an empty string as the delimiter.
The Java concepts used in the given program are:
- Classes and Objects: The program defines a class named “InterviewPrograms2” and uses the main method as the entry point for the program execution.
- String Manipulation: The program performs various operations on strings. It uses the String class methods like split(), charAt(), and length(). It also uses the StringBuilder class to reverse a string.
- Arrays: The program declares and uses an array of strings named “arr”. It iterates over the array using a for loop and accesses individual elements using array indexing.
- Conditional Statements: The program uses an if condition to check if the first character of a string element is a digit or not. It uses the negation operator (!) and the Character class method isDigit() to perform the check.
- Looping: The program uses a for loop to iterate over the elements of the array.
- Output: The program uses the System.out.println() method to print the input and output strings to the console.
Overall, the program demonstrates the usage of core Java concepts such as classes, objects, strings, arrays, conditional statements, looping, and output handling.
Solution 2:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms2_1 { /* Input - today10is20my30interview. * Output- yadot10si20ym30weivretni. */ public static void main(String[] args) { String input = "today10is20my30interview"; System.out.println("Input: "+input); StringBuilder res = new StringBuilder ( ); StringBuilder temp = new StringBuilder ( ); for ( int i = 0 ; i < input.length ( ) ; i ++ ) { char ch = input.charAt (i); if ( Character.isDigit (ch) ) { while ( i < input.length ( ) && Character.isDigit ( input.charAt ( i ) ) ) { temp.append ( input.charAt ( i ) ) ; i ++ ; } res.append ( temp ) ; temp.setLength ( 0 ) ; i-- ; } else { temp.insert ( 0 , ch ) ; } } res.append(temp); System.out.println("Output: "+res.toString()); } }
Output:
Input: today10is20my30interview Output: yadot10si20ym30weivretni
- The class InterviewPrograms2_1 is declared as public. The name of the class should ideally be in camel case format, like InterviewPrograms. The class contains the main method, where the program execution starts.
- There’s a comment that explains the input and expected output of the program. The input is the string “today10is20my30interview“, and the expected output is “yadot10si20ym30weivretni” with reversed non-numeric substrings.
- The main method is declared with the public and static modifiers. It takes an array of strings named args as a parameter. This array is used to pass command-line arguments to the program, although in this case, it is not utilized.
- Inside the main method, a string variable input is declared and initialized with the input string “today10is20my30interview”.
- The program prints the input string to the console for reference.
- Two StringBuilder objects, res, and temp, are declared and instantiated. The res StringBuilder will hold the final reversed output, while the temp StringBuilder is used to store temporary substrings.
- A for loop is used to iterate over each character in the input string. The loop variable i starts from 0 and goes up to the length of the input string minus 1.
- Inside the loop, the current character ch is obtained using the charAt method.
- An if statement checks if the current character is a digit using the Character.isDigit method.
- If the character is a digit, a nested while loop is used to collect all consecutive digits. The loop continues as long as there are more digits in the input string.
- Within the nested loop, each digit is appended to the temp StringBuilder and the loop variable i is incremented.
- The collected digits are then appended to the res StringBuilder, and the temp StringBuilder is cleared.
- If the current character is not a digit, it is inserted at the beginning of the temp StringBuilder.
- After processing all characters, the remaining characters in the temp StringBuilder are appended to the res StringBuilder.
- Finally, the program prints the reversed output string to the console.
In summary, this program takes an input string, splits it into separate elements of alphabets and digits, reverses the elements containing alphabets, and then joins all the elements back together to form the transformed string, which is then printed as the output.
String s =“lekhale” How many times “le” is Getting repeated
Input: lekhale
Output: 2
Find the Number Of Times Substring Appear In a String: This Java program aims to count the number of times a specific substring (“le” in this case) is repeated within a given input string.
If you are preparing for any interview and you are looking for some real-time Java Programs, then you can visit this blog post of softwaretestingo.
Find the Number Of Times Substring Appear in a String
Solution 1:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms3 { /* * String s =“lekhale” How many times “le” is Getting repeated, write a code to * find out using java. */ public static void main(String[] args) { String s="lekhale"; System.out.println("Input: "+s); //This will print the length of the string (7) //System.out.println(s.length()); //this will give you the total length of the string after replace le with space(3) //System.out.println((s.replaceAll("le","").length())); //Need to divide the number of character int result = (s.length()-s.replaceAll("le","").length())/2; System.out.println("Output: "+result); } }
Output:
Input: lekhale Output: 2
Here’s a step-by-step explanation of the program:
- The program starts by defining a class named “InterviewPrograms3” in the package “com.softwaretestingo.interviewprograms”.
- The main method is declared as public and static, allowing it to be accessed without creating an instance of the class.
- A string variable named “s” is declared and assigned the value “lekhale”.
- The input string “s” is printed using the System.out.println() statement.
- The program calculates the number of occurrences of the substring “le” by performing the following steps:
- The replaceAll() method is used to remove all occurrences of the substring “le” from the original string. The resulting string will have all “le” instances replaced with an empty string.
- The length() method is called on the modified string to determine its length. This represents the total length of the string after removing the “le” instances.
- The length of the original string “s” is subtracted from the modified string’s length to get the number of characters that were removed by replacing “le” with an empty string.
- Since each occurrence of “le” consists of two characters, the difference obtained in the previous step is divided by 2 to get the number of times the substring “le” is repeated within the original string.
- The result is stored in the variable “result”.
- Finally, the output is printed using the System.out.println() statement, displaying the number of times the substring “le” is repeated within the input string.
The program achieves the goal of counting the occurrences of the substring “le” within a given string by utilizing string manipulation methods, mathematical calculations, and basic string length operations. It demonstrates concepts such as string manipulation, arithmetic operations, output handling, and string length calculation.
Solution 2:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms3_1 { /* * String s =“lekhale” How many times “le” is Getting repeated, write a code to * find out using java. */ public static void main(String[] args) { String s = "lekhale"; int count = 0; int index = s.indexOf("le"); while (index != -1) { count++; index = s.indexOf("le", index + 1); } System.out.println("The substring 'le' is repeated " + count + " times in the given string."); } }
Output:
The substring 'le' is repeated 2 times in the given string.
Explanation:
- The class InterviewPrograms3_1 is declared as public. The name of the class should ideally be in camel case format, like InterviewPrograms. The class contains the main method, where the program execution starts.
- There’s a comment that explains the requirement. The program needs to count how many times the substring “le” is repeated within the input string.
- The main method is declared with the public and static modifiers. It takes an array of strings named args as a parameter. This array is used to pass command-line arguments to the program, although in this case, it is not utilized.
- Inside the main method, a string variable s is declared and initialized with the input string “lekhale”.
- An integer variable count is declared and initialized with 0. This variable will hold the count of occurrences of the substring “le” in the input string.
- An integer variable index is declared and assigned the index of the first occurrence of the substring “le” within the input string using the indexOf method.
- A while loop is used to iterate as long as the index is not -1, which means there are still occurrences of the substring “le” to be found.
- Inside the loop, the count is incremented by 1 for each occurrence of the substring “le” found.
- The indexOf method is called again with the second argument set to index + 1, which finds the index of the next occurrence of the substring “le” starting from the previous index.
- After all occurrences have been counted, the program prints the final count to the console, indicating how many times the substring “le” is repeated in the input string.
Solution 3:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms3_2 { /* * String s =“lekhale” How many times “le” is Getting repeated, write a code to * find out using java. */ public static void main(String[] args) { String s = "lekhale"; int occurence = s.split("le").length; System.out.println("The substring 'le' is repeated " + occurence + " times in the given string."); } }
Output:
The substring 'le' is repeated 2 times in the given string.
Here’s a step-by-step explanation of the program:
- The class InterviewPrograms3_2 is declared as public. The name of the class should ideally be in camel case format, like InterviewPrograms. The class contains the main method, where the program execution starts.
- There’s a comment that explains the requirement. The program needs to count how many times the substring “le” is repeated within the input string.
- The main method is declared with the public and static modifiers. It takes an array of strings named args as a parameter. This array is used to pass command-line arguments to the program, although in this case, it is not utilized.
- Inside the main method, a string variable s is declared and initialized with the input string “lekhale”.
- The program uses the split method of the string class to split the input string s into an array of substrings using “le” as the delimiter. The split method returns an array of substrings.
- The length of the resulting array, which represents the number of times the substring “le” occurs in the input string, is obtained using the length property of the array.
- The program assigns the length value to an integer variable named occurrence.
- Finally, the program prints the count of occurrences of the substring “le” to the console.
Input string: “dadeadrs”
Output: “dddaaers”
Order Character Based On Number Of Occurrences: This Java program aims to rearrange the characters in a given input string by grouping them based on their appearances. The program achieves this by creating a new list and iterating over the input string.
It checks if a character is already present in the list, and if not, it adds the character to the list and looks for additional occurrences in the remaining characters. Finally, the program prints the characters in the modified order.
If you are preparing for your next job, then we recommend that you check this blog post on java programs for interview questions.
Order Character Based On Number Of Occurrences
package com.softwaretestingo.interviewprograms; import java.util.LinkedList; import java.util.List; public class InterviewPrograms4 { /* * Input string: "dadeadrs" * Output: "dddaaers" */ public static void main(String[] args) { String s="dadeadrs"; List <Character> ls = new LinkedList<>( ); for(int i=0;i<s.length();i++) { if(!ls.contains(s.charAt(i))) { ls.add(s.charAt(i)); for (int j=i+1; j<s.length(); j++ ) { if ( s.charAt ( i ) == s.charAt ( j ) ) { ls.add (s.charAt (j)) ; } } } } for ( Character character : ls) { System.out.print (character) ; } } }
Output:
dddaaers
Here’s a step-by-step explanation of the program:
- The class InterviewPrograms4 is declared as public. The name of the class should ideally be in camel case format, like InterviewPrograms. The class contains the main method, where the program execution starts.
- There’s a comment that explains the input and expected output of the program. The input string is “dadeadrs”, and the expected output is “dddaaers” with rearranged characters based on their appearances.
- The program imports the LinkedList and List classes from the java.util package. These classes are used for list manipulation.
- The main method is declared with the public and static modifiers. It takes an array of strings named args as a parameter. This array is used to pass command-line arguments to the program, although in this case, it is not utilized.
- Inside the main method, a string variable s is declared and initialized with the input string “dadeadrs”.
- A new linked list called ls is created using the LinkedList class, which will hold the rearranged characters.
- A for loop is used to iterate over each character in the input string. The loop variable i starts from 0 and goes up to the length of the input string minus 1.
- Inside the loop, an if statement checks if the current character is already present in the linked list ls using the contains method.
- If the character is not present, it is added to the linked list using the add method.
- A nested for loop starts from the next index (i+1) and goes up to the length of the input string. It checks for additional occurrences of the character.
- If an additional occurrence is found, it is added to the linked list ls using the add method.
- After processing all characters, a for-each loop is used to iterate over each character in the linked list ls.
- Inside the loop, each character is printed using the System.out.print method.
- Finally, the program outputs the rearranged characters to the console.
The Java concepts used in the given program are:
- Classes and Objects: The program defines a class named “InterviewPrograms4” in the package “com.softwaretestingo.interviewprograms”.
- Lists: The program imports the LinkedList and List interfaces from the java.util package. It uses the LinkedList class to create a linked list object named “ls” to store characters.
- String Manipulation: The program performs operations on strings. It uses the String class methods like length() and charAt() to access characters in the input string.
- Looping: The program uses a for loop to iterate over the characters of the input string.
- Conditional Statements: The program uses an if condition to check if a character is already present in the linked list using the contains() method.
- Adding and Accessing Elements in a List: The program uses the add() method to add characters to the linked list. It also uses an enhanced for loop to iterate over the elements in the linked list and print them.
- Output: The program uses the System.out.print() statement to print the characters from the linked list, which represents the modified string.
The program achieves the goal of transforming the input string by removing duplicate characters and preserving their order. It utilizes the concept of a linked list to store unique characters and then iterates over the input string to find and add non-duplicate characters to the list. Finally, it prints the characters from the list as the output, representing the modified string.
That’s the step-by-step explanation of the given Java program. If you have any specific questions or need further clarification, feel free to ask!
Input: Welcome to Mis2is2ip2i Bla4k Adam
Output:Welcome to Mississippi Blaaaak Adam
This Java program aims to expand the characters in a given input string based on the preceding digit. If a digit is encountered in the input string, the program repeats the preceding character by the value of the digit minus one. The expanded string is then printed as the output.
Follow this link for the Java programs for interview questions.
Print the Preceding Character By the Value
package com.softwaretestingo.interviewprograms; public class InterviewPrograms6 { public static void main(String[] args) { String input = "Welcome to Mis2is2ip2i Bla4k Adam"; System.out.println("Input: "+input); StringBuilder res = new StringBuilder(); for ( int i = 0 ; i <input.length(); i ++ ) { char currentCharacter = input.charAt(i); if ( Character.isDigit (currentCharacter)) { int count = Character.getNumericValue (currentCharacter) ; char charToAppend = input.charAt (i-1); while (count -- >1) { res.append (charToAppend); } } else { res.append (currentCharacter); } } System.out.println("Output:"+res); } }
Output:
Input: Welcome to Mis2is2ip2i Bla4k Adam Output:Welcome to Mississippi Blaaaak Adam
Here’s a step-by-step explanation of the program:
- The class InterviewPrograms6 is declared as public. The name of the class should ideally be in camel case format, like InterviewPrograms. The class contains the main method, where the program execution starts.
- The main method is declared with the public and static modifiers. It takes an array of strings named args as a parameter. This array is used to pass command-line arguments to the program, although in this case, it is not utilized.
- Inside the main method, a string variable input is declared and initialized with the input string “Welcome to Mis2is2ip2i Bla4k Adam”.
- The program prints the input string to the console for reference.
- A StringBuilder variable named res is declared to store the expanded string.
- A for loop is used to iterate over each character in the input string. The loop variable i starts from 0 and goes up to the length of the input string minus 1.
- Inside the loop, the current character at index i is retrieved using the charAt method and stored in the variable currentCharacter.
- An if statement checks if the current character is a digit using the Character.isDigit method.
- If the current character is a digit, the program retrieves the numeric value of the digit using the Character.getNumericValue method and assigns it to the variable count.
- The character to append is obtained from the preceding character at index i-1 in the input string and stored in the variable charToAppend.
- A while loop is used to repeat the character to append by decrementing the count until it becomes 1.
- Inside the while loop, the character to append is added to the res string using the append method of the StringBuilder.
- If the current character is not a digit, it is directly appended to the res string.
- After processing all characters, the program prints the expanded string stored in the res variable to the console as the output.
That’s the step-by-step explanation of the given Java program. If you have any specific questions or need further clarification, feel free to ask!
Input= abbcccdeee
Output= a1b2c3d1e3
Print Character And Count Of a Word: This Java program aims to count the occurrences of each character in a given input string and generate an output string that represents each character followed by its count.
The specific transformation is applied to the input string “abbcccdeee” to obtain the output string “a1b2c3d1e3”.
Check frequently asked Java programs for interviews.

Print Character And Count Of a Word
package com.softwaretestingo.interviewprograms; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class InterviewPrograms7 { /* * Input= abbcccdeee * Output= a1b2c3d1e3 */ public static void main(String[] args) { String s="abbcccdeee"; char [ ] ch= s.toCharArray(); Map<Character, Integer> maps= new LinkedHashMap<Character,Integer>(); for (Character c:ch) { Integer count = maps.get(c); if (count != null) { maps.put (c, ++count); } else { maps.put(c,1); } } StringBuffer sb = new StringBuffer(); for (Entry< Character , Integer > entry : maps.entrySet()) { sb.append(entry.getKey()).append(entry.getValue()); } System.out.println (sb); } }
Output:
a1b2c3d1e3
Here’s a step-by-step explanation of what we are achieving through this program:
- The program starts by defining a class named “InterviewPrograms7” in the package “com.softwaretestingo.interviewprograms”.
- The main method is declared as public and static, allowing it to be accessed without creating an instance of the class.
- A string variable named “s” is declared and assigned the value “abbcccdeee”.
- The input string “s” is converted into a character array using the toCharArray() method.
- A LinkedHashMap named “maps” is created to store characters as keys and their respective counts as values. LinkedHashMap is used to preserve the insertion order.
- The program iterates over each character in the character array using an enhanced for loop.
- Within the loop, it checks if the character is already present as a key in the “maps” LinkedHashMap.
- If the character is present, it retrieves the current count from the “maps” LinkedHashMap and increments it by 1.
- If the character is not present, it adds the character as a key to the “maps” LinkedHashMap and sets its count to 1.
- After iterating through all the characters in the input string, a StringBuffer named “sb” is created.
- The program iterates over each entry (key-value pair) in the “maps” LinkedHashMap using a for-each loop.
- Within the loop, it appends the character and its count to the StringBuffer “sb”.
- Finally, the program prints the StringBuffer “sb” as the compressed output string.
Through this program, we achieve the goal of transforming the input string “abbcccdeee” into its compressed representation “a1b2c3d1e3” by counting the occurrences of each character and appending their counts to the respective characters.
Explanation:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms11_1 { /* * Input string =abbcccdeee * Output= a1b2c3d1e3 */ public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String str = "abbcccdeee"; String[] strArray = str.split(""); int i = 0 ; while ( i < strArray.length ) { int counter=0 ; int j = i ; while ( j < strArray . length ) { if ( ! strArray [ i ] .equals ( strArray [ j ] ) ) break; counter++ ; j++; } sb.append ( strArray [ i ] ) . append ( counter ) ; i = j ; } System.out.println (sb.toString()); } }
Create a StringBuilder: We create a StringBuilder object named sb to construct the final output string.
StringBuilder sb = new StringBuilder();
Initialize the input string: We assign the string value “abbcccdeee” to the variable str. This serves as the input for our program.
Split the input string into an array: We split the input string into an array of individual characters using the split(“”) method. Each character is stored as a separate element in the strArray.
String[] strArray = str.split("");
Process the input array and generate the output string: We use nested loops to iterate through the input array strArray. The outer loop iterates over each character, and the inner loop counts the consecutive occurrences of the current character. Once a different character is encountered, we break out of the inner loop. The character and its count are appended to the StringBuilder sb. The outer loop then continues from the next distinct character.
int i = 0; while (i < strArray.length) { int counter = 0; int j = i; while (j < strArray.length) { if (!strArray[i].equals(strArray[j])) break; counter++; j++; } sb.append(strArray[i]).append(counter); i = j; }
Print the output string: We print the generated output string by converting the StringBuilder sb to a string using the toString() method.
System.out.println(sb.toString());
In summary, this program takes an input string, counts the consecutive occurrences of each character, and generates an output string by concatenating each character with its respective count. The program demonstrates the usage of loops, string manipulation, and the StringBuilder class in Java.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms38 { /* * Input = AAABBBBCC * Output = A3B4C2 */ public static void main(String[] args) { String str = "AAABBBBCC"; int length = str.length ( ) ; // Created an object of a StringBuffer class . StringBuffer sb= new StringBuffer(); int count = 1; // counter for counting number of occurrences // input String // length of a String . for ( int i=0; i<length; i++) { // if i reaches at the end then append all and break the loop if (i == length-1) { sb.append(str.charAt(i)+""+count); break ; } // if two successive chars are equal then increase the if (str.charAt(i) == str.charAt(i+1)) { count ++ ; } else { // else append character with its count sb.append(str.charAt(i)+""+count); count = 1 ; // resetting the counter } } // String representation of a StringBuffer object System.out.println(sb.toString()); } }
Output
A3B4C2
Solution: Answer
Input { “Hi” , “maven” , “selenium ” , “java” }
Output { “Hi”, “java”, “maven” , “selenium” }
WAP to Sort Array Of String According To String Length: The program InterviewPrograms52 aims to sort an array of strings based on the lengths of the strings in ascending order.
In this program, we have used the concepts of For Loop and If Statement. For better understanding, you can follow the tutorials which we have already shared by clicking on the below link:
Sort Array Of String According To Strig Length
package com.softwaretestingo.interviewprograms; import java.util.Arrays; public class InterviewPrograms52 { /* * Input { "Hi" , "maven" , "selenium " , "java" } * Output{ "Hi", "java", "maven" , "selenium" } */ public static void main(String[] args) { String ip[]={"Hi","maven","selenium","java"}; for(int i=0;i<ip.length;i++) { for(int j=i+1;j<ip.length;j++) { if(ip[i].length()>ip[j].length()) { String temp=ip[j]; ip[j]=ip[i]; ip[i]=temp; } } } System.out.println(Arrays.toString(ip)); } }
Output
[Hi, java, maven, selenium]
Here’s how the program works:
- The input array ip contains four strings: “Hi”, “maven”, “selenium”, and “java”.
- The program uses nested loops to compare each string’s length with all other strings in the array.
- Starting from the first string (“Hi”), it compares its length with the lengths of the other strings (“maven”, “selenium”, and “java”).
- If the length of the current string (“Hi”) is greater than the length of any other string, it swaps their positions in the array.
- The program continues this process until the array is fully sorted based on the lengths of the strings in ascending order.
- After sorting, the program prints the sorted array to the console using Arrays.toString(ip).
In this specific case, the program will output:
[Hi, java, maven, selenium]
The output represents the array of strings sorted based on their lengths in ascending order. The string “Hi” has the shortest length, followed by “java”, “maven”, and “selenium,” which has the longest length.
Input is a phone number Ex : 1234567890
Output: (123)45-67-890
The program InterviewPrograms50 aims to format a given phone number by inserting parentheses and hyphens at specific positions to make it more readable.
Format a Phone Number in Human-Readable View
package com.softwaretestingo.interviewprograms; public class InterviewPrograms50 { /* * Input is a phone number Ex : 1234567890 * Output: (123)45-67-890 */ public static void main(String[] args) { String input="1234567890"; String output=input.replaceFirst("(\\d{3})(\\d{2})(\\d{2})(\\d+)", "($1)$2-$3-$4"); System.out.println(output); String output1="("+input.substring(0,3)+")"+input.substring(3,5)+"-"+input.substring(5,7)+"-"+input.substring(7); System.out.println(output1); } }
Output
(123)45-67-890 (123)45-67-890
Here’s how the program works:
- The input phone number is initialized as a string with the value “1234567890”.
- The program uses the replaceFirst() method to apply a regular expression pattern on the input phone number. The regular expression (\\d{3})(\\d{2})(\\d{2})(\\d+) is used to capture groups of digits with specific lengths.
- The regular expression contains four capturing groups represented by (\\d{3}), (\\d{2}), (\\d{2}), and (\\d+), which correspond to the area code, first two digits, next two digits, and the remaining digits of the phone number, respectively.
- The replacement pattern ($1)$2-$3-$4 is used to format the phone number. The $1, $2, $3, and $4 represent the captured groups, which will be substituted with their respective values from the regular expression.
- The resulting formatted phone number is stored in the output variable and printed to the console using System.out.println().
- Additionally, the program uses string slicing with substring() method to achieve the same formatting without using regular expressions. The output1 variable stores the formatted phone number using this approach.
- The program then prints both formatted phone numbers to the console.
In this specific case, the program will output:
(123)45-67-890 (123)45-67-890
Both outputs represent the same phone number with the area code enclosed in parentheses, followed by two-digit groupings separated by hyphens. The final group may have more than two digits if the input phone number has more than 10 digits.
Alternative Way 1:
This Java program takes an input phone number and formats it into a specific pattern. The input is a 10-digit long phone number (represented as phoneFmt), and the desired output is in the format (XXX)-XX-XX-XXX, where X represents a digit from the original number.
package com.softwaretestingo.interviewprograms; import java.text.DecimalFormat; public class InterviewPrograms50_1 { /* * Input is a phone number Ex : 1234567890 * Output: (123)45-67-890 */ public static void main(String[] args) { long phoneFmt = 123456789L; //get a 12 digits String, filling with left '0' (on the prefix) DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000"); String phoneRawString= phoneDecimalFmt.format(phoneFmt); java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}"); //suposing a grouping of 3-3-4 String[] phoneNumArr={phoneRawString.substring(0, 3), phoneRawString.substring(3,6), phoneRawString.substring(6)}; System.out.println(phoneMsgFmt.format(phoneNumArr)); } }
Output:
(012)-345-6789
Let’s go through the program step-by-step:
- long phoneFmt = 123456789L;: This line initializes a long variable phoneFmt with the value 123456789L, which represents the input phone number.
- DecimalFormat phoneDecimalFmt = new DecimalFormat(“0000000000”);: Here, we create a DecimalFormat object called phoneDecimalFmt. The format pattern “0000000000” ensures that the output will always be a 10-digit string, filled with leading zeros if necessary.
- String phoneRawString = phoneDecimalFmt.format(phoneFmt);: The input phone number phoneFmt is formatted into a string phoneRawString using the defined format from the phoneDecimalFmt object.
- java.text.MessageFormat phoneMsgFmt = new java.text.MessageFormat(“({0})-{1}-{2}”);: A MessageFormat object called phoneMsgFmt is created with the pattern “({0})-{1}-{2}”. This pattern will be used to format the phone number into the desired output pattern.
- String[] phoneNumArr = {…};: An array phoneNumArr of strings is declared to hold the formatted phone number digits. The phone number is divided into three groups: the first three digits, the next two digits, and the last five digits.
- phoneRawString.substring(0, 3): This extracts the first three digits from the phoneRawString.
- phoneRawString.substring(3, 6): This extracts the next two digits from the phoneRawString.
- phoneRawString.substring(6): This extracts the last five digits from the phoneRawString.
- phoneMsgFmt.format(phoneNumArr): The format() method of phoneMsgFmt is used to format the phoneNumArr array according to the pattern “({0})-{1}-{2}”. The placeholders {0}, {1}, and {2} will be replaced with the elements from the phoneNumArr array.
- System.out.println(…): The formatted phone number is printed to the console, resulting in the output format (XXX)-XX-XX-XXX.
In summary, this program demonstrates how to format a 10-digit phone number into a specific pattern (XXX)-XX-XX-XXX using DecimalFormat and MessageFormat classes in Java.
Input: “minimum”
Output: n=1
The program InterviewPrograms49 aims to find the first non-repeated character in a given string (s). The program uses two nested loops to compare each character of the string with every other character to count the number of occurrences (distinct) of each character.
Find the first non-repeated character in a word in Java
package com.softwaretestingo.interviewprograms; public class InterviewPrograms49 { /* wap to find the first non repeating character. */ public static void main(String[] args) { String s="minimum"; int distinct=0; for(int i=0;i<s.length();i++) { for(int j=0;j<s.length();j++) { if(s.charAt(i)==s.charAt(j)) { distinct++; } } if(distinct==1) { System.out.println(s.charAt(i)+"--"+distinct+"\n"); break; } String d=String.valueOf(s.charAt(i)).trim(); s.replaceAll(d,""); distinct=0; } } }
Output
n--1
Here’s how the program works:
- First, the given string s is initialized with the value “minimum”.
- The variable distinct is used to count the occurrences of each character and is initially set to 0.
- The program then enters a loop that iterates through each character of the string using the index i.
- Inside the outer loop, there is another loop that uses index
j
to compare each character with every other character in the string. - If the characters at indices i and j are the same, the distinct variable is incremented.
- After the inner loop finishes, the program checks if the distinct count is equal to 1, indicating that the character is non-repeating.
- If the condition is true, the program prints the non-repeating character along with its count using System.out.println().
- The program then breaks out of the loop to end the execution, as the first non-repeating character is found.
- If the condition is false (meaning the character is repeating), the program removes all occurrences of the current character from the string s using replaceAll().
- The distinct count is reset to 0.
- The program continues with the next character in the outer loop until it finds the first non-repeating character and prints its count.
In this specific case with the input string “minimum”, the program will output “n–1”, indicating that the first non-repeating character is ‘n’ and it occurs only once in the string.
Input=”1222bbbbcccaaaammmmm”
Output=”1222cccbbbbaaaammmmm”
Wap To Print Characters As Per Number Of Occurrences: The program InterviewPrograms47 aims to sort a given string based on the frequency of characters in ascending order.
Print Characters As Per the Number Of Occurrences
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; public class InterviewPrograms47 { /* * String input="1222bbbbcccaaaammmmm" * String output="1222cccbbbbaaaammmmm" * * We need to sort the string base on character size */ public static void main(String[] args) { System.out.println(sortFreq("1222bbbbcccaaaammmmm")); } public static String sortFreq(String str) { StringBuilder sb = new StringBuilder(); Map<Character, Integer> hm = new HashMap<>(); for (Character c : str.toCharArray()) { hm.put(c, hm.getOrDefault(c, 0) + 1); } System.out.println("frequency map of the String is " + hm); hm.entrySet().stream() .sorted(Map.Entry. <Character, Integer>comparingByValue()) .forEach(a -> {Character key = a.getKey(); int value = a.getValue(); for (int i = 0; i < value; i++) { sb.append(key); } }); System.out.println(sb); return sb.toString(); } }
Output
frequency map of the String is {1=1, a=4, 2=3, b=4, c=3, m=5} 1222cccaaaabbbbmmmmm 1222cccaaaabbbbmmmmm
Here’s a step-by-step explanation of the program:
- public static void main(String[] args): This is the entry point of the program. It calls the sortFreq method and passes the input string “1222bbbbcccaaaammmmm” as an argument.
- public static String sortFreq(String str): This method takes a string str as input and returns the sorted string based on character frequency. It uses a StringBuilder named sb to construct the sorted output.
- Map<Character, Integer> hm = new HashMap<>();: This line initializes a HashMap called hm to store character-frequency pairs. The program iterates through each character in the input string and updates the frequency in the map.
- hm.entrySet().stream()…: This part of the code uses the Java Stream API to sort the hm map based on the values (character frequencies) in ascending order. The entrySet() method provides a stream of key-value pairs, which is then sorted using Map.Entry.comparingByValue() comparator.
- forEach(a -> {…}: The sorted stream of key-value pairs is iterated using the forEach method. For each entry (character-frequency pair), the program extracts the character key and its corresponding frequency value.
- for (int i = 0; i < value; i++) {…}: For each character in the map, the program appends the character to the StringBuilder sb as many times as its frequency value.
- The final sorted string is obtained by converting the StringBuilder sb to a string using the toString() method and returned from the sortFreq method.
The program successfully sorts the input string “1222bbbbcccaaaammmmm” based on character frequency and produces the output “1222cccbbbbaaaammmmm”.
Alternative 1
In this program InterviewPrograms47_1, we are sorting a given string based on the frequency of characters in ascending order.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; public class InterviewPrograms47_1 { /* * String input="1222bbbbcccaaaammmmm" * String output="1222cccbbbbaaaammmmm" * * We need to sort the string base on character size */ public static void main(String[] args) { String input = "1222cccbbbbaaaammmmmmm"; Map<String, Integer> outputMap = new HashMap<>(); for (String letter : input.split("")) { outputMap.compute(letter, (k,v)->v==null?1:v+1); } System.out.println(outputMap); Map<Integer, List<String>> inversed = outputMap .entrySet() .stream().collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); inversed.values().forEach(list->list.sort(null)); new TreeMap<>(inversed).forEach((k,v)->v.forEach(letter-> System.out.print(letter.repeat(k)))); } }
Output
{a=4, 1=1, b=4, 2=3, c=3, m=7} 1222cccaaaabbbbmmmmmmm
Here’s a step-by-step explanation of the program:
- public static void main(String[] args): This is the entry point of the program. It starts by defining the input string “1222cccbbbbaaaammmmmmm”.
- Map<String, Integer> outputMap = new HashMap<>();: The program creates a HashMap called outputMap to store character-frequency pairs. It then iterates through each character in the input string and calculates its frequency using the compute method of the HashMap.
- Map<Integer, List<String>> inversed = …: The program converts the outputMap to a frequency-inverted map, where the keys are frequencies and the values are lists of characters with the corresponding frequency. It uses Java Stream API’s groupingBy and mapping collectors to achieve this.
- inversed.values().forEach(list->list.sort(null));: The characters in each frequency group are sorted alphabetically using the sort method.
- new TreeMap<>(inversed).forEach(…);: The frequency-inverted map is converted to a TreeMap, which automatically sorts the frequencies in ascending order. The forEach method is used to iterate through the sorted frequencies and their corresponding character lists.
- System.out.print(letter.repeat(k)): For each character in the sorted frequency group, the program prints the character repeated k times, where k is the frequency of that character.
By the end of the program, the output is obtained as “1222cccbbbbaaaammmmmmm”, where the string is sorted based on character frequency in ascending order.
Find Sum of numbers in given strings.
Input : “Welcome[21], Java1How are you78”
OutPut : 100 [21+1+78]
Find Sum of digits in given strings.
Input : “Welcome[21], Java1How are you78”
OutPut : 19 [2+1+1+7+8]
Sum Of Digits Of a String: This Java program achieves two tasks:
- Finding the sum of numbers in the given string:
- The program takes an input string containing alphanumeric characters and special characters.
- It extracts all the numeric values from the string and calculates their sum.
- For the input string “Welcome[21], Java1How are you78”, the output will be 100 (21 + 1 + 78).
- Finding the sum of digits in the given numbers:
- The program takes the same input string as above and extracts the numeric values.
- For each extracted number, it calculates the sum of its digits.
- The digits of the numbers are summed, and the final output is the sum of these digits.
- For the input string “Welcome[21], Java1How are you78”, the output will be 19 (2 + 1 + 1 + 7 + 8).
Sum Of Digits Of a String
package com.softwaretestingo.interviewprograms; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class InterviewPrograms46 { /* * 1. Find Sum of numbers in given strings. * Input : "Welcome[21], Java1How are you78" * OutPut : 100 [21+1+78] * * 2. Find Sum of digits in given strings. * Input : "Welcome[21], Java1How are you78" * OutPut : 19 [2+1+1+7+8] */ public static void main(String[] args) { InterviewPrograms46 main = new InterviewPrograms46(); String testData = "Welcome[21], Java1How are you78"; List<Integer> integers = main.getIntegers(testData); System.out.println("Sum of numbers : " + integers.stream().reduce(0, (n1, n2) -> n1 + n2)); System.out.println("Sum of digits of numbers : " + integers.stream().filter(num->num>0).map(num -> main.sumOfDigits(num)).reduce(0, (n1, n2) -> n1 + n2)); } private Integer sumOfDigits(Integer number) { int sum = 0; while (number > 0) { sum += number % 10; number = number / 10; } return sum; } private List<Integer> getIntegers(String testData) { return Arrays.asList(testData.split(" ")).stream().map(word -> getNumber(word)).collect(Collectors.toList()); } private Integer getNumber(String data) { String num = ""; try { for (Character ch : data.toCharArray()) { if (Character.isDigit(ch)) num += String.valueOf(ch); } } catch (Exception ex) { return 0; } return num.length() > 0 ? Integer.parseInt(num) : 0; } }
Output
Sum of numbers : 100 Sum of digits of numbers : 19
Let’s break down the program section by section:
- public static void main(String[] args): This is the entry point of the program. It initializes the InterviewPrograms46 class, defines the input string testData, and proceeds to perform the two tasks: finding the sum of numbers and the sum of digits.
- private Integer sumOfDigits(Integer number): This method calculates the sum of digits of a given integer number. It uses a while loop to extract the individual digits of the number and adds them to the variable sum. Finally, it returns the sum of the digits.
- private List<Integer> getIntegers(String testData): This method takes the input string testData, splits it into words using space as a delimiter, and then maps each word to an integer by calling the getNumber method on each word. The resulting integers are collected into a list using the collect method of the Stream API, and this list of integers is returned.
- private Integer getNumber(String data): This method takes a word data and extracts the numeric part from it. It iterates through each character of the word, and if the character is a digit, it appends it to the num string. Finally, it parses the num string to an integer using Integer.parseInt. If there are no digits in the word or an exception occurs during parsing, it returns 0.
The program effectively demonstrates how to extract numbers from a string and perform various operations on them using Java’s Stream API, making it a concise and efficient solution to the given problem.
Input INDIA
Output INDIIA
Print Duplicate Character Based on its Occurrence Times: The given Java program takes an input string “INDIA” and finds and duplicates each character in the output string based on its occurrence. The output will be “INDIIA,” where each character that appears more than once in the input string is duplicated in the output string.
Print Duplicate Character Based on its Occurrence Times
package com.softwaretestingo.interviewprograms; import java.util.HashMap; public class InterviewPrograms45 { /* * Input INDIA * Output INDIIA */ public static void main(String[] args) { findDuplicate("INDIA"); } public static void findDuplicate(String str) { String newStr = ""; HashMap<Character,Integer> hm = new HashMap<Character,Integer>(); for(int i=0;i<str.length();i++) { if(hm.containsKey(str.charAt(i))) { newStr = newStr+str.charAt(i)+str.charAt(i); } else { newStr = newStr+str.charAt(i); hm.put(str.charAt(i),1); } } System.out.println(newStr); } }
Output
INDIIA
Here’s a step-by-step explanation of the program:
- Define the main method:
- The program starts executing from the main method.
- Call the findDuplicate method:
- The findDuplicate method is called with the input string “INDIA.”
- Define the findDuplicate method:
- The method takes a string str as input.
- Initialize variables:
- A new string newStr is initialized to store the modified output.
- A HashMap hm is initialized to keep track of character occurrences.
- Iterate through the input string:
- A loop runs from index 0 to the length of the string – 1.
- Check for duplicate characters:
- In each iteration, it checks if the character at the current index exists in the HashMap hm.
- If the character exists in the HashMap, it means it is a duplicate, and it appends it twice to the newStr.
- If the character does not exist in the HashMap, it means it is not a duplicate, and it appends it once to the newStr.
- Update the HashMap:
- After appending the character to the newStr, it adds the character to the HashMap with a count of 1 (indicating its first occurrence).
- Print the modified string:
- After the loop, the modified string newStr is printed as the output.
The program finds duplicate characters in the input string and duplicates them in the output string, producing the final output “INDIIA.”
Input: “HELLO WORLD”
Output: “HExxxO WORxxxD”
WAP to Replace a Character Sequence With Increase Order: The given Java program manipulates a given input string “HELLO WORLD” to replace each occurrence of the letter ‘L’ with a sequence of ‘x’ characters. The output will be “HExxxO WORxxxD,” where the number of ‘x’ characters increases for each occurrence of ‘L.’
Replace a Character Sequence With Increase Order
package com.softwaretestingo.interviewprograms; public class InterviewPrograms44 { /* * input: "HELLO WORLD" * Output: "HExxxO WORxxxD" */ public static void main(String[] args) { String s="HELLO WORLD"; String z=""; int count=1; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='L') { for(int j=0;j<count;j++) { z=z+'x'; } count++; } else { z=z+s.charAt(i); } } System.out.println(z); } }
Output
HExxxO WORxxxD
Here’s a step-by-step explanation of the program:
- Define the main method:
- The program starts executing from the main method.
- Initialize the input string:
- The input string s is initialized with the value “HELLO WORLD.”
- Initialize variables:
- A new string z is initialized to store the modified output.
- An integer variable count is initialized to keep track of the number of ‘x’ characters to be added for each ‘L’ occurrence. It is initially set to 1.
- Iterate through the input string:
- A loop runs from index 0 to the length of the string – 1.
- Check for ‘L’ occurrences:
- In each iteration, it checks if the character at the current index is ‘L.’
- If ‘L’ is found, it enters a nested loop.
- Add ‘x’ characters:
- The nested loop runs count times, and in each iteration, it appends ‘x’ to the string z.
- This will add ‘x’ characters based on the current value of count for each occurrence of ‘L.’
- Increment count:
- After the nested loop, count is incremented to increase the number of ‘x’ characters for the next ‘L’ occurrence.
- Add other characters:
- If the current character is not ‘L,’ it directly appends the character to the string z.
- Print the modified string:
- After the loop, the modified string z is printed as the output.
The program replaces each occurrence of ‘L’ with an increasing number of ‘x’ characters based on the variable count and outputs the final modified string “HExxxO WORxxxD.”
Input= AB2C99423A
Output =A2B9C9A423
Separate Two Characters With a Digit: The given Java program takes an input string AB2C99423A and rearranges its characters to separate alphabetic and non-alphabetic characters. The resulting output is A2B9C9A423.
Separate Two Characters With a Digit
package com.softwaretestingo.interviewprograms; public class InterviewPrograms41 { /* * String input= AB2C99423A * String output =A2B9C9A423 */ public static void main(String[] args) { String s = "AB2C99423A"; char[] cArr = s.toCharArray(); char resultArr[] = new char [cArr.length*2]; int evenCount = 0 ; int oddcount = 1 ; for ( int i=0 ; i<s.length(); i++ ) { if ( Character.isAlphabetic(cArr[i])) { resultArr [evenCount] = cArr[i]; evenCount = evenCount+2; } else if(!Character.isAlphabetic(cArr[i])) { resultArr [oddcount]= cArr[i]; oddcount = oddcount+2 ; } } System.out.println(resultArr); } }
Output
A2B9C9A4
Here’s a step-by-step explanation of the program:
- Define the main method:
- The program starts executing from the main method.
- Initialize the input string and convert it to a character array:
- The input string s is initialized with the value “AB2C99423A”.
- The toCharArray() method is used to convert the input string into a character array cArr.
- Initialize the result array:
- A new character array resultArr is created with twice the length of the original character array cArr. This is because the result array will contain both alphabetic and non-alphabetic characters, and we need space for both.
- Separate alphabetic and non-alphabetic characters:
- Two variables, evenCount and oddcount, are initialized to keep track of the indices for alphabetic and non-alphabetic characters in the resultArr, respectively.
- The program iterates through each character in the input string using a loop.
- If the character is alphabetic (determined using Character.isAlphabetic(cArr[i])), it is placed at the evenCount index in the resultArr, and then evenCount is incremented by 2 to maintain space between alphabetic characters.
- If the character is non-alphabetic (not alphabetic), it is placed at the oddcount index in the resultArr, and then oddcount is incremented by 2 to maintain space between non-alphabetic characters.
- Print the output:
- The program prints the resultArr, which contains the rearranged characters with alphabetic and non-alphabetic characters separated.
For the given input “AB2C99423A”, the program rearranges the characters as “A2B9C9A423”. Alphabetic characters (A, B, C, A) are separated by non-alphabetic characters (2, 9, 9, 3).
Alternative Way 1:
The given Java program takes an input string AB2C99423A and rearranges its characters to separate alphabetic and numeric characters. The resulting output is A2B9C9A423.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms41_1 { /* * String input= AB2C99423A * String output =A2B9C9A423 */ public static void main(String[] args) { String inpu = "AB2C99423A"; String charac = ""; String intege = ""; String result=""; for(int i=0;i<inpu.length();i++) { if(Character.isLetter(inpu.charAt(i))) { charac = charac + inpu.charAt(i); } else if(Character.isDigit(inpu.charAt(i))) { intege = intege + inpu.charAt(i); } } int index1=0, index2=0; for(int i=0;i<inpu.length();i++) { if(i%2==0 && charac.length()>index1) { result = result + charac.charAt(index1); index1++; } else { if(intege.length()>index2) { result = result + intege.charAt(index2); index2++; } } } System.out.println(result); } }
Output
A2B9C9A423
Here’s a step-by-step explanation of the program:
- Define the main method:
- The program starts executing from the main method.
- Initialize the input string and other required variables:
- The input string inpu is initialized with the value “AB2C99423A”.
- Three empty strings, charac, intege, and result, are initialized to store alphabetic characters, numeric characters, and the final rearranged string, respectively.
- Separate alphabetic and numeric characters:
- The program iterates through each character in the input string using a loop.
- If the character is a letter (alphabetic character), it is appended to the charac string.
- If the character is a digit (numeric character), it is appended to the intege string.
- Rearrange the characters:
- The program uses two indices, index1 and index2, to keep track of the current positions in the charac and intege strings, respectively.
- The program iterates through each character in the input string using another loop.
- If the current index is even, the character at the corresponding position in the charac string is added to the result string, and index1 is incremented.
- If the current index is odd, the character at the corresponding position in the intege string is added to the result string, and index2 is incremented.
- Print the output:
- The program prints the result string, which contains the rearranged characters with alphabetic and numeric characters separated.
For the given input “AB2C99423A”, the program rearranges the characters as “A2B9C9A423”. Alphabetic characters (A, B, C, A) are separated by numeric characters (2, 9, 9, 3).
Input : Aut@oma#tion@#
Output: Aut@oma#tion..
Replace Last Two Special Character With Dots: This Java program aims to remove the last alphanumeric character from a given input string and replace it with dots.
Replace Last Two Special Character With Dots
package com.softwaretestingo.interviewprograms; public class InterviewPrograms40 { /* * Input string : Aut@oma#tion@# * Output: Aut@oma#tion.. * Input maybe any string, but only the last alphanumeric character should be removed */ public static void main(String[] args) { String s = "Aut@oma#tion@#"; String [ ] newstring = s.split(""); int count = 0 ; String last = ""; for ( int i = s.length()-1; i>=0;i--) { if (!newstring[i].matches("[a-zA-Z]")) { count++; last=last+"."; } else { break; } } System.out.print(s.substring(0, s.length()-count)+last); } }
Output
Aut@oma#tion..
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the input string and split it into an array of characters:
- The string s is initialized with the value “Aut@oma#tion@#”.
- The split(“”) method is used to convert the input string into an array of characters named newstring.
- Find the last non-alphanumeric character:
- A variable count is initialized to zero to keep track of the number of non-alphanumeric characters at the end of the string.
- A variable last is initialized as an empty string to store the dots that will replace the removed characters.
- The program iterates through the characters in reverse order (from the end of the string to the beginning).
- If a character is not a letter (uppercase or lowercase) using the regex [a-zA-Z], it means it is non-alphanumeric.
- If the character is non-alphanumeric, the count is incremented, and a dot is appended to the last string.
- If a letter is encountered, the loop breaks since we have reached the last alphanumeric character.
- Build the output string:
- The program constructs the output string by removing the last count characters from the original string s and appending the last string (dots) at the end.
- Print the output:
- The program prints the final s string, which has the last alphanumeric character replaced with dots.
For the given input “Aut@oma#tion@#”, the program removes the last alphanumeric character “n” and replaces it with dots, resulting in “Aut@oma#tion..”.
Input : { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ }
Output: true
Check Consecutive Character Sequence in an Array: This Java program aims to check whether the elements of an integer array form a consecutive sequence starting from a specific value. It does so by converting the characters from a given char array into integers and then checks for consecutive values in the resulting integer array.
Check Consecutive Character Sequence in an Array
package com.softwaretestingo.interviewprograms; public class InterviewPrograms37 { public static void main(String[] args) { char[] JavaCharArray = { 'a', 'b', 'c', 'd', 'e' }; int val[]=new int[5]; for(int i=0;i<5;i++) { val[i]=(int)JavaCharArray[i]; } System.out.println(checker(val)); } public static boolean checker(int[] array) { int array_element_count=array.length; int f_val=array[0]; int count=0; for(int i=0;i<5;i++) { if(array[i]==(f_val+i)) { count++; } } if(count==array_element_count) { return true; } return false; } }
Output
true
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the char array and integer array:
- The char array JavaCharArray is initialized with characters ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’.
- The integer array val is declared and allocated memory to store integers corresponding to the characters in JavaCharArray.
- Convert characters to integers:
- The program uses a for loop to convert each character in JavaCharArray to its corresponding ASCII value and stores it in the val array.
- Call the checker method:
- The checker method is called with the val array as an argument, which checks whether the elements in the array form a consecutive sequence.
- Define the checker method:
- The checker method takes an integer array array as input.
- It initializes array_element_count with the length of the input array.
- It sets f_val to the value of the first element in the array.
- The method then iterates through the array and compares each element to the expected value based on the first element’s value and its index. If the elements are consecutive, it increments the
count
. - Finally, the method checks if the count is equal to the array_element_count. If true, it returns true, indicating that the elements form a consecutive sequence; otherwise, it returns false.
The program then prints the result returned by the checker method. If the val array contains consecutive integers (e.g., [97, 98, 99, 100, 101]), the output will be true. Otherwise, if the array elements are not consecutive (e.g., [97, 98, 101, 102, 103]), the output will be false.
Input – Hi I am Naveen I need and answer
Output – answer and deen I Naveen ma I Hi
Reverse Every Third Word In a String: This Java program rearranges the words in the input string in a specific pattern. It reverses every third word in the input string and then prints the modified string.
Reverse Every Third Word In a String
package com.softwaretestingo.interviewprograms; public class InterviewPrograms29 { /* * Input - Hi I am Naveen I need and answer * Output - answer and deen I Naveen ma I Hi */ public static void main(String[] args) { String str = "Hi I am Naveen I need and answer"; String[] sp=getPattern(str); // print Array for(int j=sp.length-1; j>=0; j--) { System.out.print(sp[j] + " "); } } private static String[] getPattern(String revStr) { String[] splitStr = revStr.split(" "); for ( int j = splitStr.length-3; j>=0 ; j=j-3) { String temp=splitStr[j]; StringBuilder sb = new StringBuilder(temp); splitStr[j] = sb.reverse().toString(); } return splitStr ; } }
Output
answer and deen I Naveen ma I Hi
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize variables and process the input string:
- The input string str is initialized with the value “Hi I am Naveen I need and answer”.
- The program calls the getPattern method, passing the input string as an argument, and stores the result in the sp array.
- The getPattern method:
- The getPattern method takes a string revStr as input.
- It splits the input string into words using the space character as a delimiter, and the result is stored in the splitStr array.
- The method then iterates through the array starting from the third-to-last element, in reverse order (every third word).
- For each of these words, it reverses the characters using a StringBuilder.
- The modified array is then returned.
- Print the modified string:
- After processing the input string, the program loops through the sp array in reverse order (from last to first) and prints each word followed by a space.
Overall, this program reverses every third word in the input string and then prints the modified string. The output will be “answer and deen I Naveen ma I Hi” for the given input string.
Alternative 1
This Java program rearranges the words in the input string in a specific pattern. It reverses every third word in the input string and then prints the modified string.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms29_1 { /* * Input - Hi I am Naveen I need and answer * Output - answer and deen I Naveen ma I Hi */ public static void main(String[] args) { String input = "Hi I am Naveen i need and answer"; String[] inputArr=input.split(" "); String outputStr = "" ; int j = 0 ; for (int i=inputArr.length-1; i>=0 ; i-- ) { ++ j ; String indexedStr = ""; if (j%3==0) { for (int k=inputArr[i].length()-1 ; k>=0 ; k--) { indexedStr = indexedStr + inputArr[i].charAt(k); } } else { indexedStr=inputArr[i]; } outputStr = outputStr + " " + indexedStr; } System.out.println(outputStr.trim()); } }
Output
answer and deen i Naveen ma I Hi
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize variables and process the input string:
- The input string input is initialized with the value “Hi I am Naveen I need and answer”.
- The program splits the input string into words using the space character as a delimiter, and the result is stored in the inputArr array.
- A string outputStr is initialized to store the final modified string.
- Loop through the words in reverse order:
- The program iterates through the inputArr array from the last element to the first using a for loop.
- Determine whether to reverse the word:
- For each word, a counter j is incremented.
- If the counter j is divisible by 3 (i.e., every third word), the characters of the word are reversed and stored in indexedStr.
- If the counter j is not divisible by 3, the word remains unchanged, and the original word is stored in indexedStr.
- Build the modified string:
- The indexedStr (either reversed or original) is appended to the outputStr with a space.
- Print the modified string:
- After processing all words in the input string, the program prints the outputStr after trimming any leading or trailing spaces.
Overall, this program reverses every third word in the input string and then prints the modified string. The output will be “answer and deen I Naveen ma I Hi” for the given input string. The program uses basic looping and string manipulation to achieve the desired result.
Input – Ramakant
Output – R1a1m1a2k1a3n1t1
Print Character and Occurrences Count: This Java program takes an input string and generates a new string where each character is followed by the count of its occurrences in the original string. For instance, for the input string “Ramakant,” the output will be “R1a1m1a2k1a3n1t1.”
Print Character and Occurrences Count
package com.softwaretestingo.interviewprograms; public class InterviewPrograms35 { /* * Input - Ramakant * Output - R1a1m1a2k1a3n1t1 * I have to take input string and in output will print no of occurance after each character */ public static void main(String[] args) { String name = "Ramakant"; String text = ""; for (int i = 0; i < name.length(); i++) { char[] ch = name.toCharArray(); text = text + ch[i] + ((name.substring(0, i).length())-(name.substring(0, i).replace(String.valueOf(ch[i]),"").length())+1); } System.out.println(text); } }
Output
R1a1m1a2k1a3n1t1
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the input string:
- The input string name is initialized with the value “Ramakant.”
- Count occurrences and create the new string:
- The program uses a for loop to iterate through each character of the input string.
- Within the loop, it converts the input string name to a character array ch using name.toCharArray().
- It calculates the count of occurrences of the current character ch[i] by comparing the length of the substring up to index i with the length of the substring after removing all occurrences of the character.
- It concatenates the current character ch[i] with its count and stores the result in the string variable text.
- Print the modified string:
- After processing all characters, the program prints the modified string text, which represents the original characters along with the count of their occurrences.
Overall, this program uses a for loop and string manipulation to achieve the task of counting occurrences of each character in the input string and creating a new string with character occurrences appended next to each character.
Input :Hello world,welcome to my world,my world
Output:world Hello ,world my to welcome ,world my
Reverse String Based on Commas: This Java program takes an input string containing comma-separated phrases, and for each phrase, it reverses the order of words within that phrase while keeping the phrases themselves in the same order. It achieves this without using any predefined functions for string manipulation.
Reverse String Based on Commas
package com.softwaretestingo.interviewprograms; public class InterviewPrograms30 { /* * Input :Hello world,welcome to my world,my world * Output:world Hello ,world my to welcome ,world my * my Condition: without using predefined function */ public static void main(String[] args) { String str1 = "Hello world,welcome to my world,my world"; String arr[] = str1.split(","); String res = ""; for(int i=0;i<arr.length;i++) { String[] de = arr[i].split(" "); for(int j=de.length-1;j>=0;j--) { res = res + de[j] + " "; } res = res + ","; } res = res.substring(0,res.length()-1); System.out.println(res); } }
Output
world Hello ,world my to welcome ,world my
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize variables and process the input string:
- The input string str1 is initialized with the value “Hello world,welcome to my world,my world”.
- The program splits the input string into an array of phrases using a comma as a delimiter and stores it in the arr array.
- Loop through each phrase:
- The program iterates through each phrase in the arr array using a for loop.
- Split and reverse words:
- For each phrase, it splits the phrase into individual words using a space as a delimiter and stores them in the de array.
- The program then iterates through the de array from the last word to the first using another for loop, effectively reversing the order of words.
- Build the modified string:
- The reversed words are concatenated together, separated by spaces, and appended to the
res
string. - A comma is also appended to the res string to separate the phrases.
- The reversed words are concatenated together, separated by spaces, and appended to the
- Finalize the output:
- After processing all phrases, the program removes the last comma from the res string.
- The modified string res is then printed as the final output.
Overall, this program reverses the order of words within each phrase of the input string while maintaining the order of the phrases themselves. The output will be “world hello ,world my to welcome ,world my” for the given input string. The program achieves this without using any predefined functions for string manipulation and relies on basic looping and string concatenation.
Alternative 1
This Java program takes an input string containing comma-separated phrases. For each phrase, it reverses the order of words within that phrase while keeping the phrases themselves in the same order. The program achieves this without using any predefined functions for string manipulation, relying on basic looping and string concatenation.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms30_1 { /* * Input :Hello world,welcome to my world,my world * Output:world hello ,world my to welcome ,world * my Condition: without using predefined function */ public static void main(String[] args) { //inbuilt function split(); String input = "Hello world,welcome to my world,my world" ; String output = ""; //inbuilt function1 String[] str_array= input.split(","); int len1= str_array.length; //System.out.println("Level 1 array length "+len1); System.out.println("Input String == "+input); for (String s : str_array) { //System.out.println("Level words "+s); String[] sub_str_array = s.split(" ") ; int len2= sub_str_array.length; //System.out.println("Level 2 array length "+len2); if(len2>1) { String gap=" "; int c=0; for (int i=len2; i>0; i-- ) { if (i==len2) { //System.out.println("Level 2 Reverse words "+sub_str_array[i-1]); output=output+sub_str_array[i-1]; } else { output=output+gap+sub_str_array[i-1]; } c++; } } //if1 end //add , after each string except for the last one in each loop if(s==str_array[len1-1]) {} else output= output+","; } //End of 1st for loop System.out.println("Output String == "+output); } //main function //class end }
Output
Input String == Hello world,welcome to my world,my world Output String == world Hello,world my to welcome,world my
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize variables and process the input string:
- The input string input is initialized with the value “Hello world,welcome to my world,my world”.
- An empty string output is initialized to store the final modified string.
- Split the input string:
- The program splits the input string into an array of phrases using a comma as a delimiter, and the result is stored in the str_array array.
- Loop through each phrase and reverse words:
- For each phrase, the program iterates through the str_array array using an enhanced for loop.
- Each phrase is split into individual words using a space as a delimiter, and the result is stored in the sub_str_array array.
- The program then iterates through the sub_str_array array in reverse order, effectively reversing the order of words.
- The reversed words are concatenated together, separated by spaces, and appended to the output string.
- Add commas between phrases and print the final output:
- After processing all phrases, the program adds commas between the phrases in the
output
string, except for the last phrase. - The modified string
output
is then printed as the final output.
- After processing all phrases, the program adds commas between the phrases in the
Overall, this program achieves the same functionality as the previous one by reversing the order of words within each phrase of the input string while maintaining the order of the phrases themselves. The output will be “world hello ,world my to welcome ,world my” for the given input string. The program demonstrates similar logic as the previous one but uses comments and additional variables to clarify each step.
List a[ ] = [2, 1,1,4,5,5,6,7]
Expected output : [2,4,6,7] (Delete Duplicate Ones)
Print Unique Digits Of an Array: This Java program takes an input array of integers, removes any repeated numbers, and creates a new list containing only the unique numbers. It achieves this using a HashMap to track the occurrence of each number.
Print Unique Digits Of an Array
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class InterviewPrograms34 { /* * List a[ ] = [2, 1,1,4,5,5,6,7] * Expected output : [2,4, 6,7] * Numbers which gets repeated we should remove and make output as above I know using HashSet * we get as [2, 1,4,5 , 6,7] But interviewee asked about deleting repeated ones */ public static void main(String[] args) { Integer arr[]= {2,1,1,4,5,5,6,7}; List <Integer> ar = Arrays.asList(arr); HashMap<Integer,Integer> hm = new HashMap<>(); ar.forEach(e ->{if(hm.containsKey(e)) { hm.remove(e); } else { hm.put(e,1); }}); ar = new ArrayList<>(hm.keySet()); System.out.println(ar); } }
Output
[2, 4, 6, 7]
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the input array:
- The input array arr is initialized with the values {2, 1, 1, 4, 5, 5, 6, 7}.
- Convert array to a list:
- The program uses Arrays.asList() to convert the input array arr into a list ar.
- Remove repeated numbers using a HashMap:
- The program creates a HashMap called hm to track the occurrence of each number.
- It uses the forEach method to iterate through each element e of the list.
- If hm already contains the element e as a key, it means e is a repeated number. In this case, the program removes the key-value pair from the hm.
- If e is not already present in hm, it means it is a unique number, and the program puts e as the key in hm with a value of 1.
- Create a new list with unique numbers:
- After processing all elements, the program creates a new ArrayList ar by extracting the keys (unique numbers) from the hm using hm.keySet().
- Print the modified list:
- The program prints the modified list ar, which now contains only the unique numbers.
Overall, this program removes any repeated numbers from the input array and creates a new list with only the unique numbers. For the given input array {2, 1, 1, 4, 5, 5, 6, 7}, the output will be [2, 4, 6, 7], as all repeated numbers have been removed. The program demonstrates the use of a HashMap to efficiently handle duplicates and create a list of unique elements.
Alternative 1:
This Java program takes an input array of integers, removes any repeated numbers, and creates a new set containing only the unique numbers. It achieves this using a HashSet to efficiently track and eliminate duplicates.
package com.softwaretestingo.interviewprograms; import java.util.HashSet; public class InterviewPrograms34_1 { /* * List a[ ] = [2, 1,1,4,5,5,6,7] * Expected output : [2,4, 6,7] * Numbers which gets repeated we should remove and make output as above I know using HashSet * we get as [2, 1,4,5 , 6,7] But interviewee asked about deleting repeated ones */ public static void main(String[] args) { Integer ar[]= {2,1,1,4,5,5,6,7}; HashSet<Integer> hs= new HashSet<Integer>(); for(int s1:ar) { if(hs.add(s1)==false) { hs.remove(s1); } } System.out.println(hs); } }
Output
[2, 4, 6, 7]
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the input array:
- The input array ar is initialized with the values {2, 1, 1, 4, 5, 5, 6, 7}.
- Create a HashSet to store unique numbers:
- The program creates an empty HashSet<Integer> called hs to store unique numbers.
- Remove repeated numbers using HashSet:
- The program iterates through each element s1 of the input array ar using a for-each loop.
- For each element, it tries to add it to the HashSet using hs.add(s1).
- If s1 is already present in the HashSet, the add method returns false, indicating that s1 is a repeated number. In this case, the program removes s1 from the HashSet using hs.remove(s1).
- Print the modified set:
- After processing all elements, the HashSet hs contains only unique numbers, as duplicates have been eliminated.
- The program prints the modified HashSet hs, which now contains only the unique numbers.
Overall, this program removes any repeated numbers from the input array and creates a new set with only the unique numbers. For the given input array {2, 1, 1, 4, 5, 5, 6, 7}, the output will be [2, 4, 6, 7], as all repeated numbers have been removed. The program demonstrates the use of a HashSet to efficiently handle duplicates and create a set of unique elements.
Alternative Way 2:
This Java program takes an input list of integers, removes any numbers that occur more than once, and creates a new list containing only the unique numbers. It achieves this by using a HashMap to count the occurrences of each number in the input list.
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class InterviewPrograms34_2 { /* * List a[ ] = [2, 1,1,4,5,5,6,7] * Expected output : [2,4, 6,7] * Numbers which gets repeated we should remove and make output as above I know using HashSet * we get as [2, 1,4,5 , 6,7] But interviewee asked about deleting repeated ones */ public static void main(String[] args) { ArrayList<Integer> intList= new ArrayList<>(Arrays.asList(2,1,1,4,5,5,6,7)); HashMap<Integer,Integer> getCount=new HashMap<Integer,Integer>(); for ( int c : intList ) { if (getCount.containsKey(c)) { getCount.put(c, getCount.get(c)+1); } else { getCount.put(c,1); } } List<Integer> newIntList= new ArrayList<Integer>(); for (int c:intList ) { if ( getCount.get(c)<2) { newIntList.add (c); } } System.out.println(newIntList); } }
Output
[2, 4, 6, 7]
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the input list:
- The input list intList is initialized with the values [2, 1, 1, 4, 5, 5, 6, 7].
- Count occurrences of each number using a HashMap:
- The program creates a HashMap<Integer, Integer> called getCount to count the occurrences of each number in the intList.
- It iterates through each element c of the intList.
- For each element, it checks if c is already a key in getCount. If yes, it increments the corresponding count value. If not, it adds c as a new key with a count value of 1.
- Create a new list with unique numbers:
- After counting the occurrences of each number, the program creates a new ArrayList<Integer> called newIntList.
- It iterates through each element c of the intList.
- For each element, it checks if its count in getCount is less than 2 (i.e., it occurs only once). If yes, it adds c to newIntList.
- Print the modified list:
- After processing all elements, newIntList contains only unique numbers, as numbers occurring more than once have been removed.
- The program prints the modified list newIntList, which now contains only the unique numbers.
Overall, this program removes any numbers that occur more than once from the input list and creates a new list with only the unique numbers. For the given input list [2, 1, 1, 4, 5, 5, 6, 7], the output will be [2, 4, 6, 7], as all repeated numbers have been removed. The program demonstrates the use of a HashMap to efficiently handle duplicates and create a list of unique elements.
Input = “GDP in 2016 has fallen from 6.8% to 4.5%”
Output = “GDP in 6102 has fallen from 8.6% to 5.4%”
Reverse Digits Only From a String: This Java program takes an input string and reverses the order of digits within the numbers present in the string. It achieves this by iterating through the input string character by character and using two StringBuffer objects: rev to store the reversed string and number to store the digits of a number temporarily.
Reverse Digits Only From a String
package com.softwaretestingo.interviewprograms; public class InterviewPrograms32 { /* * Input = “GDP in 2016 has fallen from 6.8% to 4.5%” * Output = “GDP in 6102 has fallen from 8.6% to 5.4%” * Only reverse the numbers of a string. */ public static void main(String[] args) { String s="GDP in 2016 has fallen from 6.8% to 4.5%"; StringBuffer rev=new StringBuffer(); StringBuffer number=new StringBuffer(); int length=s.length(); for(int i=0;i<length;i++) { Character c=s.charAt(i); if(c.isDigit(c) || c.equals('.')) { number.append(c); } else if(!number.isEmpty()) { String rev1=""; for(int j=number.length()-1;j>=0;j--) { rev1=rev1+number.charAt(j); } rev.append(rev1+c); number.delete(0, number.length()); } else { rev.append(c); } } System.out.print(rev); } }
Output
GDP in 6102 has fallen from 8.6% to 5.4%
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize variables and process the input string:
- The input string s is initialized with the value “GDP in 2016 has fallen from 6.8% to 4.5%”.
- Two StringBuffer objects, rev and number, are initialized to store the reversed string and digits of a number, respectively.
- An integer variable length is initialized to store the length of the input string.
- Loop through the input string:
- The program iterates through each character of the input string using a for loop.
- Separate numbers and reverse digits:
- For each character, if it is a digit or a dot (decimal point), it is appended to the number StringBuffer.
- If a non-digit character is encountered, it means a number has ended. The program reverses the digits of the number and appends it, along with the non-digit character, to the rev StringBuffer.
- If no number is being processed (i.e., number is empty), the non-digit character is directly appended to the rev StringBuffer.
- Print the reversed string:
- After processing all characters of the input string, the program prints the reversed string (rev).
Overall, this program reverses the order of digits within the numbers present in the input string while leaving other characters unchanged. The output will be “GDP in 6102 has fallen from 8.6% to 5.4%” for the given input string. The program demonstrates basic string manipulation and loop usage to achieve this task.
input :list1–[3,R,M,4,89,f]
OutPut:list2–[3,4,89,M,R,f]
WAP to Move Digits to Left and Characters to Right: This Java program aims to reorder the elements in the input array list1 such that all numeric values are moved to the left side, and all non-numeric values (characters) are moved to the right side, while maintaining their relative order within each group.
Move Digits to Left and Characters to Right
package com.softwaretestingo.interviewprograms; import java.util.Arrays; public class InterviewPrograms23 { /* * input :list1--[3,R,M,4,89,f] * OutPut:list2--[3,4,89,M,R,f] */ public static void main(String[] args) { String[] arr = pushAllCharToRight(new String[] {"3" ,"R", "M" , "4" , "89" , "f"}); System.out.println(Arrays.toString(arr)); } public static String[] pushAllCharToRight(String[] array) { int i= 0 ; int j = array.length-1; while (i < j) { if (Character.isLetter(array[j].charAt(0))) { j--; } try { Integer.parseInt(array[i]); i++; } catch (NumberFormatException e) { String temp = array[j]; array[j--] = array[i]; array[i] = temp; } } return array; } }
Output
[3, 89, 4, M, R, f]
Let’s break down the program step by step for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms23.
- It contains a main method, the entry point of the program, which will be executed first.
- Input Array and Method Invocation:
- String[] arr = pushAllCharToRight(new String[] {“3″ ,”R”, “M” , “4” , “89” , “f”});: This line declares and initializes the input string array arr with the values {“3”, “R”, “M”, “4”, “89”, “f”}. It then calls the method pushAllCharToRight() to process the array and get the result.
- pushAllCharToRight() Method:
- public static String[] pushAllCharToRight(String[] array): This method takes a string array array as input and returns a string array.
- The method uses two pointers, i and j, starting from the beginning and the end of the array, respectively.
- Reordering the Array:
- The method uses a while loop that continues until i is less than j.
- If the element at index j is a letter (non-numeric value), the pointer j moves to the left (decrements).
- If the element at index i is numeric (convertible to an integer), the pointer i moves to the right (increments).
- If the element at index i is not numeric, it means it is a non-numeric value (character). In that case, it swaps the elements at i and j, and both pointers are updated accordingly.
- Printing the Result Array:
- The main method prints the resulting array arr using Arrays.toString() to display the reordered elements:
[3, 4, 89, M, R, f]
In summary, this Java program reorders the elements in the input array list1 such that all numeric values are moved to the left side, and all non-numeric values (characters) are moved to the right side while maintaining their relative order within each group. For the given input array {“3”, “R”, “M”, “4”, “89”, “f”}, the output array will be [3, 4, 89, M, R, f].
Alternative 1:
This Java program aims to reorder the elements in the lst ArrayList such that all numeric values are moved to the left side, and all non-numeric values (characters) are moved to the right side, while maintaining their relative order within each group. The program then sorts the ArrayList containing the elements.
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.Arrays; public class InterviewPrograms23_1 { /* * input :list1--[3,R,M,4,89,f] * OutPut:list2--[3,4,89,M,R,f] */ public static void main(String[] args) { ArrayList lst=new ArrayList(); ArrayList lstSorted=new ArrayList(); lst.add(3); lst.add("R"); lst.add("M"); lst.add(4); lst.add(89); lst.add("f"); String [] stringLst=new String[lst.size()]; for(int i=0;i<lst.size();i++) { if(lst.get(i).getClass().getSimpleName().equalsIgnoreCase("Integer")) { stringLst[i]=Integer.toString((int)lst.get(i)); } else stringLst[i]=(String)lst.get(i); } Arrays.sort(stringLst); for(int b=0;b<stringLst.length;b++) { lstSorted.add(stringLst[b]); } System.out.println("Given List: "+lst); System.out.println("Sorted List: "+lstSorted); } }
Output
Given List: [3, R, M, 4, 89, f] Sorted List: [3, 4, 89, M, R, f]
Let’s break down the program step by step for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms23_1.
- It contains a main method, the entry point of the program, which will be executed first.
- ArrayLists Initialization:
- Two ArrayLists, lst and lstSorted, are created to hold the original elements and the sorted elements, respectively.
- Populating the ArrayList:
- The program adds elements (numeric and non-numeric) to the lst ArrayList.
- Converting to String Array:
- A stringLst array of strings is created with the same size as lst to hold the converted elements.
- A for loop iterates over the lst ArrayList, and for each element, it checks its type using getClass().getSimpleName().
- If the element is of type Integer, it converts it to a string using Integer.toString(). Otherwise, it remains as a string.
- Sorting the String Array:
- The stringLst array is sorted using Arrays.sort().
- Populating the Sorted ArrayList:
- Another for loop iterates over the sorted stringLst array and adds each element to the lstSorted ArrayList.
- Printing the Result ArrayLists:
- Finally, the program prints both the original and sorted ArrayLists to display the reordered elements.
Given List: [3, R, M, 4, 89, f] Sorted List: [3, 4, 89, M, R, f]
In summary, this Java program reorders the elements in the lst ArrayList such that all numeric values are moved to the left side, and all non-numeric values (characters) are moved to the right side while maintaining their relative order within each group. It then sorts the ArrayList with the reordered elements. For the given input ArrayList [3, R, M, 4, 89, f], the output ArrayList will be [3, 4, 89, M, R, f].
Input:{01IND02AUS03ENG}
Output:
{
“01”: IND,
“02”:AUS,
“03”:ENG
}
O/P should be printed in json array with key value pair
WAP to Convert String into JSON Array with key-Value Pairs: This Java program achieves the goal of converting a given input string {01IND02AUS03ENG} into a JSON array with key-value pairs. The program takes the input string, processes it, and produces the output JSON representation.
Convert String into JSON Array with key-Value Pairs
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; import org.json.simple.JSONObject; public class InterviewPrograms22 { /* * Input:{01IND02AUS03ENG} * Output: * { * "01": IND, * "02":AUS, * "03":ENG * } * O/P should be printed in json array with key value pair. * * Download Jar File From Here: https://code.google.com/archive/p/json-simple/downloads * After that Add the Jar File In the Java Project build Path: (right-click on the project, Properties->Libraries and add new JAR.) */ public static void main(String[] args) { String s = "01IND02AUS03ENG"; InterviewPrograms22 solution = new InterviewPrograms22(); solution.getSolution(s); } public void getSolution(String test) { String word[] = test.split("([0-9])+"); String num[] = test.split("([a-zA-z])+"); Map<String, String> hasmMap = new HashMap<String, String>(); for(int i=0; i<num.length; i++) { for(int j=i+1; j<=i+1; j++) { hasmMap.put(num[i], word[j]); } } JSONObject data = new JSONObject(hasmMap); System.out.println(data); } }
Output
{"01":"IND","02":"AUS","03":"ENG"}
Let’s break down the program step by step for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms22.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String and Method Invocation:
- String s = “01IND02AUS03ENG”;: This line declares and initializes the input string s with the value “01IND02AUS03ENG”.
- InterviewPrograms22 solution = new InterviewPrograms22();: An instance of the class InterviewPrograms22 is created to call the method getSolution().
- getSolution() Method:
- public void getSolution(String test): This method takes a string test as input and does not return anything (void).
- It splits the input string into two arrays: word[] to store the alphabetic parts (IND, AUS, ENG) and num[] to store the numeric parts (01, 02, 03).
- Creating a HashMap:
- Map<String, String> hashMap = new HashMap<String, String>();: A HashMap called hashMap is created to store the key-value pairs.
- Populating the HashMap:
- The program uses nested for loops to iterate over the num[] and word[] arrays.
- It maps each numeric element in num[] to its corresponding word element in word[] and puts them as key-value pairs in the hashMap.
- Creating a JSON Object:
- JSONObject data = new JSONObject(hashMap);: A JSONObject called data is created, taking the hashMap as an argument.
- Printing the JSON Object:
- Finally, the program prints the data object, which is the JSON representation of the key-value pairs, resulting in the output:
{"01":"IND","02":"AUS","03":"ENG"}
In summary, this Java program converts a given input string into a JSON representation with key-value pairs. The output JSON object represents the numeric parts as keys and their corresponding alphabetic parts as values. For the given input {01IND02AUS03ENG}, the output JSON will be {“01″:”IND”,”02″:”AUS”,”03″:”ENG”}.
Alternative 1:
This Java program achieves the goal of converting a given input string {01IND02AUS03ENG} into a HashMap with key-value pairs. The program takes the input string, processes it, and produces the output HashMap representation.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; public class InterviewPrograms22_1 { /* * Input:{01IND02AUS03ENG} * Output: * { * "01": IND, * "02":AUS, * "03":ENG * } * O/P should be printed in json array with key value pair. * */ public static void main(String[] args) { String input = "01IND02AUS03ENG"; HashMap <String ,String> map= new HashMap <String,String>( ); String [ ] intArr = input.split("([0-9])+"); String [ ] StrArr = input.split("([a-z]|[A-Z])+"); int iCount = 1 ; for (String b:StrArr) { map.put(b,intArr[iCount]); iCount++; } System.out.println(map); } }
Output
{01=IND, 02=AUS, 03=ENG}
Let’s break down the program step by step for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms22_1.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String and HashMap:
- String input = “01IND02AUS03ENG”;: This line declares and initializes the input string input with the value “01IND02AUS03ENG”.
- HashMap<String, String> map = new HashMap<String, String>();: A HashMap called map is created to store the key-value pairs.
- Splitting the Input String:
- The program uses split() method twice on the input string to separate the numeric parts (intArr) and the alphabetic parts (StrArr) and store them in arrays.
- Populating the HashMap:
- A variable iCount is initialized to 1 to keep track of the index while iterating over StrArr.
- The program uses an enhanced for loop to iterate over StrArr.
- For each alphabetic element (b) in StrArr, it puts the element as a key and the corresponding numeric element (intArr[iCount]) as the value in the map. Then, it increments iCount to get the next numeric element in the next iteration.
- Printing the HashMap:
- Finally, the program prints the map, which is the HashMap representation of the key-value pairs, resulting in the output:
{01=IND, 02=AUS, 03=ENG}
In summary, this Java program converts a given input string into a HashMap representation with key-value pairs. The output HashMap represents the numeric parts as keys and their corresponding alphabetic parts as values. For the given input {01IND02AUS03ENG}, the output HashMap will be {01=IND, 02=AUS, 03=ENG}.
Input int a[]={5,0,4,6,0,7,0}
Output = {0,0,0,5,4,6,7}
Move Zeros Left By Maintaining Order Of Digits: This Java program achieves the goal of moving all zeros in the input array to the beginning while maintaining the order of other numbers. The program takes the input array int a[]={5,0,4,6,0,7,0}, and the output array should be {0,0,0,5,4,6,7}.
Move Zeros Left By Maintaining the Order Of Digits
package com.softwaretestingo.interviewprograms; public class InterviewPrograms21 { /* * Input int a[]={5,0,4,6,0,7,0} * Output = {0,0,0,5,4,6,7} * Goal is to print all zero first and then the rest of other numbers as it is. */ public static void main(String[] args) { int[] array = {5,0,4,6,0,7,0}; int current = array.length - 1; for (int i = array.length - 1; i >= 0; i--) { if (array[i] != 0) { array[current] = array[i]; current--; } } while (current >= 0) { array[current] = 0; current--; } for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } }
Output
0 0 0 5 4 6 7
Let’s break down the program section by section for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms21.
- It contains a main method, the entry point of the program, which will be executed first.
- Input Array:
- int[] array = {5,0,4,6,0,7,0};: This line declares and initializes the input integer array with the values {5,0,4,6,0,7,0}.
- Moving Non-Zero Elements to the End:
- The program uses a for loop to iterate over the input array in reverse order (from the end to the beginning).
- It checks if the current element is not zero (array[i] != 0).
- If it’s not zero, it moves that non-zero element to the current position indicated by the current variable.
- The current variable keeps track of the index in the array where the next non-zero element will be placed.
- Setting Zeros at the Beginning:
- After moving all non-zero elements to their correct positions, the program uses another while loop to set zeros at the beginning of the array for the remaining positions.
- It decrements the current variable and sets the value at that index to zero until it reaches index 0.
- Printing the Resultant Array:
- Finally, the program uses a for loop to iterate over the array and prints each element to the console, resulting in the output {0,0,0,5,4,6,7}.
In summary, this Java program reorders the elements in the input array such that all zeros are moved to the beginning, and the non-zero elements maintain their original order. The output array after executing the program will be {0,0,0,5,4,6,7} for the given input {5,0,4,6,0,7,0}.
Alternative 1:
This Java program achieves the goal of moving all zeros in the input array to the beginning while maintaining the order of other numbers. The program takes the input array int a[]={5,0,4,6,0,7,0}, and the output should be {0,0,0,5,4,6,7}.
package com.softwaretestingo.interviewprograms; import java.util.LinkedList; public class InterviewPrograms21_1 { /* * Input int a[]={5,0,4,6,0,7,0} * Output = {0,0,0,5,4,6,7} * Goal is to print all zero first and then the rest of other numbers as it is. */ public static void main(String[] args) { int z[]= {5,0,4,6,0,7,0}; LinkedList<Integer> zeroFirst = new LinkedList<>(); for(int i:z) { if(i==0) zeroFirst.addFirst(i); else zeroFirst.add(i); } System.out.println(zeroFirst); } }
Output
[0, 0, 0, 5, 4, 6, 7]
Let’s break down the program section by section for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms21_1.
- It contains a main method, the entry point of the program, which will be executed first.
- Input Array:
- int z[]= {5,0,4,6,0,7,0};: This line declares and initializes the input integer array z with the values {5,0,4,6,0,7,0}.
- Creating a LinkedList:
- LinkedList<Integer> zeroFirst = new LinkedList<>();: A LinkedList called zeroFirst is created to store the reordered elements.
- Moving Zeroes to the Beginning:
- The program uses an enhanced for loop to iterate over the input array z.
- If the current element is zero (i==0), it is added to the beginning of the zeroFirst list using addFirst(i).
- If the current element is non-zero, it is added to the end of the zeroFirst list using add(i).
- Printing the Resultant List:
- Finally, the program prints the zeroFirst list, which now contains the elements with all zeros at the beginning and the non-zero elements maintaining their original order.
In summary, this Java program Examples reorders the elements in the input array such that all zeros are moved to the beginning, and the non-zero elements maintain their original order. The output list after executing the program will be [0, 0, 0, 5, 4, 6, 7] for the given input array {5, 0, 4, 6, 0, 7, 0}.
Alternative 2:
This Java program achieves the goal of moving all zeros in the input array to the beginning while maintaining the order of other numbers. The program takes the input array int a[]={5,0,4,6,0,7,0}, and the output should be {0,0,0,5,4,6,7}.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms21_2 { /* * Input int a[]={5,0,4,6,0,7,0} * Output = {0,0,0,5,4,6,7} * Goal is to print all zero first and then the rest of other numbers as it is. */ public static void main(String[] args) { int [] a = {5, 0, 4, 6, 0, 7, 0}; String s = ""; for (int i : a) { if (i == 0) s = i + "," + s; else s = s + i + ","; } for (String i : s.split(",")) System.out.print(i+" "); } }
Output
0 0 0 5 4 6 7
Let’s break down the program section by section for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms21_2.
- It contains a main method, the entry point of the program, which will be executed first.
- Input Array:
- int [] a = {5, 0, 4, 6, 0, 7, 0};: This line declares and initializes the input integer array a with the values {5,0,4,6,0,7,0}.
- Converting Array to String:
- The program creates an empty string s to store the elements of the array in string format.
- Moving Zeroes to the Beginning:
- The program uses an enhanced for loop to iterate over the elements of the input array a.
- If the current element is zero (i == 0), it adds the value and a comma to the beginning of the string s.
- If the current element is non-zero, it appends the value and a comma to the end of the string s.
- Printing the Resultant Array:
- After processing the input array, the program uses another enhanced for loop to iterate over the elements of the split string s (using comma as a delimiter).
- It prints each element followed by a space to the console, resulting in the output {0,0,0,5,4,6,7}.
In summary, this Java program reorders the elements in the input array such that all zeros are moved to the beginning, and the non-zero elements maintain their original order. The output after executing the program will be “0,0,0,5,4,6,7” for the given input array {5, 0, 4, 6, 0, 7, 0}.
Alternative 3:
This Java program achieves the goal of moving all zeros in the input array to the beginning while maintaining the order of other numbers. The program takes the input array int a[]={5,0,4,6,0,7,0}, and the output should be {0,0,0,5,4,6,7}.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms21_3 { /* * Input int a[]={5,0,4,6,0,7,0} * Output = {0,0,0,5,4,6,7} * Goal is to print all zero first and then the rest of other numbers as it is. */ public static void main(String[] args) { int [] givenArray = { 5 , 0 , 4 , 6 , 0 , 7 , 0 }; //reqArray [] = { 0,0,0,5,4,6,7 }; int reqArray [] = new int[givenArray.length]; int reqArrayIndex = 0 ; // to add zeroes in the beginning for (int j=0; j<givenArray.length ; j++ ) { if (givenArray[j]==0) { reqArray[reqArrayIndex]=0; reqArrayIndex++ ; } } // to add digits without changing order for ( int l=0 ; l<givenArray.length; l++ ) { if (givenArray[l]!=0) { reqArray[reqArrayIndex]=givenArray[l]; reqArrayIndex++; } } for ( int arr=0; arr<reqArray.length; arr++ ) { System.out.print(reqArray[arr]+" "); } } }
Output
0 0 0 5 4 6 7
Let’s break down the program section by section for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms21_3.
- It contains a main method, the entry point of the program, which will be executed first.
- Input Array:
- int [] givenArray = { 5 , 0 , 4 , 6 , 0 , 7 , 0 };: This line declares and initializes the input integer array givenArray with the values {5,0,4,6,0,7,0}.
- Resultant Array:
- int reqArray [] = new int[givenArray.length];: A new integer array reqArray is created with the same length as givenArray to store the reordered elements.
- Adding Zeroes to the Beginning:
- The program uses a for loop to iterate over the elements of the givenArray.
- If the current element is zero (givenArray[j]==0), it is added to the reqArray at the current reqArrayIndex, and the reqArrayIndex is incremented.
- Adding Non-Zero Digits:
- Another for loop is used to iterate over the elements of the givenArray.
- If the current element is not zero (givenArray[l]!=0), it is added to the reqArray at the current reqArrayIndex, and the reqArrayIndex is incremented.
- Printing the Resultant Array:
- After processing the input array, the program uses a for loop to iterate over the elements of the reqArray.
- It prints each element followed by a space to the console, resulting in the output {0,0,0,5,4,6,7}.
In summary, this Java program reorders the elements in the input array such that all zeros are moved to the beginning, and the non-zero elements maintain their original order. The output after executing the program will be “0 0 0 5 4 6 7” for the given input array {5, 0, 4, 6, 0, 7, 0}.
Alternative 4:
This Java program achieves the goal of moving all zeros in the input array to the beginning while maintaining the order of other numbers. The program takes the input array int a[]={5,0,4,6,0,7,0}, and the output should be {0,0,0,5,4,6,7}.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms21_4 { /* * Input int a[]={5,0,4,6,0,7,0} * Output = {0,0,0,5,4,6,7} * Goal is to print all zero first and then the rest of other numbers as it is. * WITH OUT BUILT IN FUNCTION */ public static void main(String[] args) { int zeroCount = 0 ; int [ ] arr = { 5 , 0 , 4 , 6 , 0 , 7 , 0 }; for (int i =0 ; i<arr.length ; i++ ) { if (arr[i] == 0) { zeroCount ++ ; } } System.out.println ("Zero count is : " +zeroCount); int arr1 [] = new int[arr.length]; for ( int i=0 ; i<zeroCount; i++) { arr1[i]=0; } int newIndex=0; for (int i=0 ; i<arr.length; i++ ) { if ( arr[i]>0 ) { arr1[zeroCount+newIndex]= arr[i]; newIndex ++ ; } } for ( int i=0 ; i<arr1.length; i++ ) { System.out.print(arr1[i]+","); } } }
Output
Zero count is : 3 0,0,0,5,4,6,7,
Let’s break down the program step by step for Java beginners:
- Class and main() Method:
- The program defines a class called InterviewPrograms21_4.
- It contains a main method, the entry point of the program, which will be executed first.
- Input Array and Zero Count:
- int zeroCount = 0;: Initialize a variable zeroCount to count the number of zeros in the input array.
- int [] arr = { 5 , 0 , 4 , 6 , 0 , 7 , 0 };: This line declares and initializes the input integer array arr with the values {5,0,4,6,0,7,0}.
- Counting Zeros:
- The program uses a for loop to iterate over the elements of the input array arr.
- If the current element is zero (arr[i] == 0), the zeroCount is incremented.
- Creating a Resultant Array:
- A new integer array arr1 is created with the same length as arr to store the reordered elements.
- Adding Zeroes to the Beginning:
- Another for loop is used to iterate zeroCount times to add zeros at the beginning of arr1.
- Adding Non-Zero Digits:
- The program uses a for loop to iterate over the elements of the input array arr again.
- If the current element is greater than zero (arr[i] > 0), it is added to arr1 at the position indicated by zeroCount + newIndex, and newIndex is incremented.
- Printing the Resultant Array:
- After processing the input array, the program uses another for loop to iterate over the elements of the arr1.
- It prints each element followed by a comma to the console, resulting in the output {0,0,0,5,4,6,7}.
In summary, this Java program reorders the elements in the input array such that all zeros are moved to the beginning, and the non-zero elements maintain their original order. The output after executing the program will be “0,0,0,5,4,6,7” for the given input array {5, 0, 4, 6, 0, 7, 0}. The program achieves this without using built-in functions, demonstrating a manual approach to achieve the desired result.
Input 1B3A2D4C
Output BAAADDCCCC
Print Character by its Corresponding Count: This Java program takes an input string “1B3A2D4C” and produces an output string “BAAADDCCCC”. The program interprets the input as a combination of letters and digits, where each letter is followed by its corresponding count of occurrences. It then reconstructs the output string based on this information.
Print the Character by its Corresponding Count
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class InterviewPrograms20 { /* * Input 1B3A2D4C * Output BAAADDCCCC * WALLMART */ public static void main(String[] args) { String s = "1B3A2D4C"; String[] sArray = s.split(""); List<String> intList = new ArrayList<>(); List<String> sList = new ArrayList<>(); for(String temp : sArray) { if(temp.matches("[a-zA-Z]")) { sList.add(temp); } else { intList.add(temp); } } Map<String, Integer> map = new LinkedHashMap<>(); Iterator<String> itr1 = sList.iterator(); Iterator<String> itr2 = intList.iterator(); while(itr1.hasNext() && itr2.hasNext()) { map.put(itr1.next(), Integer.parseInt(itr2.next())); } for(Map.Entry<String, Integer> m : map.entrySet()) { for(int i=0;i<m.getValue();i++) { System.out.print(m.getKey()); } } } }
Output
BAAADDCCCC
Let’s break down the program section by section for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports several classes from the java.util package, including ArrayList, Iterator, LinkedHashMap, List, and Map.
- Class and main() Method:
- The program defines a class called InterviewPrograms20.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String s = “1B3A2D4C”;: This line declares and initializes the input string s with the value “1B3A2D4C”.
- Splitting the Input String:
- String[] sArray = s.split(“”);: The input string s is split into an array of individual characters using the split(“”) method.
- Separating Digits and Letters:
- The program creates two lists: intList to store digits and sList to store letters.
- It uses an enhanced for loop to iterate over each character in sArray.
- If the character is a letter (checked using regex [a-zA-Z]), it is added to sList.
- If the character is a digit, it is added to intList.
- Creating a LinkedHashMap:
- Map<String, Integer> map = new LinkedHashMap<>();: A LinkedHashMap called map is created to store letters as keys and their corresponding counts (as integers) as values.
- Populating the LinkedHashMap:
- The program simultaneously uses two separate iterators (itr1 and itr2) to iterate over sList and intList.
- It pairs each letter with its corresponding count from the input string and puts them into the map.
- Reconstructing the Output String:
- The program uses a for-each loop to iterate over each entry (m) in the map.
- For each entry, it prints the letter m.getKey() as many times as specified by the count m.getValue().
- This reconstruction of letters and counts results in the output string “BAAADDCCCC” based on the input “1B3A2D4C”.
In summary, this Java program takes an input string with letter-count combinations, separates the letters and counts, stores them in a LinkedHashMap, and then reconstructs the output string by repeating each letter according to its corresponding count. The resulting output string is “BAAADDCCCC” for the given input “1B3A2D4C”.
Alternative:
This Java program aims to transform a given input string according to a specific pattern and output the modified string. Let’s break down the program step by step for beginners:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms20_1 { // Interview Questions Asked In Unify technologies // Suppose input string is "c3d4a2" then output should be "cccddddaa" public static void main(String[] args) { String s="c3d4a2"; String ans=""; for (int i = 0; i<=s.length()-1; i++) { String r=String.valueOf(s.charAt(i)); int rep= Integer.valueOf(String.valueOf(s.charAt(i+1))); for (int j =1 ; j<=rep; j++) { ans=ans+r; } i=i+1; } System.out.println("The Inputted Parameter Is: "+s); System.out.print("Expected output Is: "+ans); } }
Output:
The Inputted Parameter Is: c3d4a2 Expected output Is: cccddddaa
Problem Description: The program deals with a scenario where an input string, such as “c3d4a2”, is provided. The task is to expand the string by repeating each character a certain number of times as indicated by the numeric value following the character.
Main Method: The program begins by defining a class named InterviewPrograms20_1 and the main method within it.
String Initialization: A string variable ‘s’ is initialized with the input value “c3d4a2”.
Initialization: An empty string variable ‘ans’ is declared. This variable will store the transformed string as the program progresses.
Outer Loop: The program enters a loop that iterates through the characters of the input string using the variable ‘i’. This loop is responsible for processing each character and its associated numeric value.
Current Character: Inside the outer loop, the program extracts the current character using s.charAt(i) and converts it into a string ‘r’. This will be the character that needs to be repeated.
Repetition Value: The numeric value following the current character is extracted by converting s.charAt(i+1) into an integer ‘rep’. This value indicates how many times the character should be repeated.
Inner Loop: Within the outer loop, there’s an inner loop that iterates ‘rep’ times (the repetition value). In each iteration, the character ‘r’ is added to the ‘ans’ string. This effectively repeats the character ‘rep’ times.
Index Update: After the inner loop completes, the index ‘i’ is incremented by 1 (i=i+1). This is done to skip the numeric value character that has already been processed.
Print Result: Once the loops finish, the program prints the value of the ‘ans’ string, which represents the expanded string according to the given pattern.
In summary, this program takes an input string containing characters followed by numeric values and expands it by repeating each character the specified number of times. It uses nested loops to process each character and its repetition value, then generates the transformed string and displays it as output.
Input string “AAAABBCCCDDDDEEEG”
Output string “A4B2C3D4E3G1”
Count Occurrence of Characters in a String: This Java program takes an input string “AAAABBCCCDDDDEEEG” and generates an output string “A4B2C3D4E3G1”. The program compresses the input string by representing each character and the number of occurrences of that character consecutively.
Count Occurrence of Characters in a String
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; public class InterviewPrograms19 { /* * Input string "AAAABBCCCDDDDEEEG" * Output string "A4B2C3D4E3G1" */ public static void main(String[] args) { String s ="AAAABBCCCDDDDEEEG"; ArrayList<Character> list = new ArrayList<>(); for(int i=0;i<s.length();i++) { int count=1; if(!list.contains(s.charAt(i))) { list.add(s.charAt(i)); for(int j=i+1;j<s.length();j++) { if(s.charAt(i)==s.charAt(j)) { count++; } } System.out.print(s.charAt(i)+""+count); } } } }
Output
A4B2C3D4E3G1
Let’s break down the program step by step for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports the ArrayList class from the java.util package to use dynamic arrays.
- Class and main() Method:
- The program defines a class called InterviewPrograms19.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String s = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string s with the value “AAAABBCCCDDDDEEEG”.
- ArrayList Initialization:
- ArrayList<Character> list = new ArrayList<>();: An ArrayList called list is created to store unique characters encountered in the input string.
- Looping through the Input String:
- for(int i=0; i<s.length(); i++) { … }: The program uses a for loop to iterate over each character of the input string.
- Character Counting:
- int count = 1;: A variable count is initialized to 1 to count the occurrences of the current character.
- Checking for Unique Characters:
- if (!list.contains(s.charAt(i))) { … }: This if condition checks if the current character is not present in the list, which means it’s a new character.
- Adding Unique Characters to the List and Counting Occurrences:
- list.add(s.charAt(i));: If the character is unique, it’s added to the list.
- The program then uses another for loop (nested within the first loop) to find the number of occurrences of this unique character by comparing it with the remaining characters in the string.
- Printing the Compressed Output:
- System.out.print(s.charAt(i) + “” + count);: After counting the occurrences of the current unique character, it’s printed along with its count.
- Output:
- The output of the program will be “A4B2C3D4E3G1”, which represents the compressed version of the input string “AAAABBCCCDDDDEEEG”.
In summary, this Java program takes an input string, compresses it by counting consecutive occurrences of each character, and then prints the compressed version of the string.
Alternative 1:
This Java program achieves the same goal as the previous one, which is to compress an input string “AAAABBCCCDDDDEEEG” into an output string “A4B2C3D4E3G1”. However, it uses a different approach to achieve this compression.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; public class InterviewPrograms19_1 { /* * Input string "AAAABBCCCDDDDEEEG" * Output string "A4B2C3D4E3G1" */ public static void main(String[] args) { String s = "AAAABBCCCDDDDEEEG"; String[] sArray = s.split(""); Map<String, Integer> map = new HashMap<>(); for(String temp : sArray) { if(map.containsKey(temp)) { map.put(temp, map.get(temp)+1); } else { map.put(temp, 1); } } System.out.println(map.toString().replaceAll("\\W","")); } }
Output
A4B2C3D4E3G1
Let’s break down the program section by section for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports the HashMap and Map classes from the java.util package to work with key-value pairs.
- Class and main() Method:
- The program defines a class called InterviewPrograms19_1.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String s = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string s with the value “AAAABBCCCDDDDEEEG”.
- Splitting the Input String:
- String[] sArray = s.split(“”);: The input string s is split into an array of individual characters using the split(“”) method.
- Creating a HashMap:
- Map<String, Integer> map = new HashMap<>();: A HashMap called map is created to store characters as keys and their occurrences as values.
- Looping through the Input Characters:
- for(String temp : sArray) { … }: The program uses an enhanced for loop to iterate over each character in the sArray.
- Counting Character Occurrences:
- if(map.containsKey(temp)) { … }: It checks if the current character (temp) is already present in the map.
- Updating the HashMap:
- If the character is already in the map, its corresponding value (occurrence count) is incremented by one.
- If the character is not present in the map, it’s added to the map with an initial occurrence count of 1.
- Printing the Compressed Output:
- System.out.println(map.toString().replaceAll(“\\W”,””));: After counting occurrences of all characters, the program prints the compressed output.
- map.toString() converts the map to a string representation (e.g., “{A=4, B=2, C=3, D=4, E=3, G=1}”).
- .replaceAll(“\\W”,””) removes all non-word characters (non-alphanumeric characters) from the string, resulting in the desired compressed output “A4B2C3D4E3G1”.
In summary, this Java program compresses the input string by counting the occurrences of each character using a HashMap, and then it prints the compressed output in the format “A4B2C3D4E3G1”.
Alternative 2:
This Java program also achieves the goal of compressing the input string “AAAABBCCCDDDDEEEG” into the output string “A4B2C3D4E3G1”. It uses a HashMap to count the occurrences of each character in the input string and then prints the compressed output.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class InterviewPrograms19_2 { /* * Input string "AAAABBCCCDDDDEEEG" * Output string "A4B2C3D4E3G1" */ public static void main (String [] args) { String str = "AAAABBCCCDDDDEEEG"; occurences (str); } public static void occurences(String str) { int count = 0 ; Map <Character, Integer> hs=new HashMap <Character ,Integer>(); for ( int i = 0 ; i<str.length(); i++) { if ( hs.containsKey(str.charAt(i))) { count =hs.get(str.charAt(i)); count = count+1; hs.put(str.charAt(i),count); } else { hs.put(str.charAt(i), 1); } } Set<Map.Entry <Character, Integer>> s = hs.entrySet(); for (Entry<Character,Integer> s1 : s ) { System.out.print (s1.getKey()+ ""+s1.getValue()); } } }
Output
A4B2C3D4E3G1
Let’s break down the program section by section for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports several classes from the java.util package, including HashMap, Map, Entry, and Set, which are used for handling key-value pairs.
- Class and main() Method:
- The program defines a class called InterviewPrograms19_2.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String str = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string str with the value “AAAABBCCCDDDDEEEG”.
- Calling the occurences() Method:
- occurences(str);: The program calls the occurences() method, passing the input string str to it for processing.
- occurences() Method:
- public static void occurences(String str) { … }: This method takes a string as input and is responsible for counting the occurrences of each character.
- Initializing the HashMap:
- Map<Character, Integer> hs = new HashMap<Character, Integer>();: A HashMap called hs is created to store characters as keys and their occurrences as values.
- Looping through the Input Characters:
- The program uses a for loop to iterate over each character in the input string str.
- Counting Character Occurrences using HashMap:
- If the character is already present in the hs HashMap, the program retrieves its current count, increments it by one, and puts the updated count back into the hs.
- If the character is not present in the hs HashMap, it is added to the hs with an initial count of 1.
- Printing the Compressed Output:
- Set<Map.Entry<Character, Integer>> s = hs.entrySet();: The program gets the entry set of the hs HashMap to iterate over its key-value pairs.
- Looping through HashMap Entries and Printing:
- The program uses an enhanced for loop to iterate over each entry (s1) in the entry set s.
- It then prints the key (character) and value (occurrence count) of each entry, resulting in the compressed output format “A4B2C3D4E3G1”.
In summary, this Java program also compresses the input string by counting the occurrences of each character using a HashMap, and then it prints the compressed output in the format “A4B2C3D4E3G1”.
Input string: “AcBCbDEdea”
Output string:”AaBbCcDdEe”
Sorting Characters Alphabetically Ignoring Case Sensitive: This Java program transforms an input string into a new format following specific rules. The goal of the program is to create a new string in which each character from the input string is repeated exactly twice, once in uppercase and once in lowercase, and they appear in sorted order based on their lowercase representation.
Sorting Characters Alphabetically Ignoring Case Sensitive
package com.softwaretestingo.interviewprograms; import java.util.Set; import java.util.TreeMap; public class InterviewPrograms17 { /* * Input string: "AcBCbDEdea" * Output string:"AaBbCcDdEe" */ public static void main(String[] args) { TreeMap<Character,Integer> map1 = new TreeMap<Character,Integer>(); String S1="AcBCbDEdea"; System.out.println("Given Initial String: "+S1); char[] array = S1.toLowerCase().toCharArray(); for(char c:array) { if(map1.containsKey(c)) { map1.put(c,map1.get(c)+1); } else { map1.put(c,1); } } Set<Character> set=map1.keySet(); System.out.print("The String Gets Transformed to the Below Format: "); for(Character character:set) { if(map1.get(character)==2) { System.out.print(Character.toUpperCase(character)+""+Character.toLowerCase(character)); } } } }
Output:
Given Initial String: AcBCbDEdea The String Gets Transformed to the Below Format: AaBbCcDdEe
Here’s how the program achieves this:
Import Statements: The program imports the necessary classes from the java.util package, specifically Set and TreeMap, to use sets and sorted maps.
main Method: The program defines the main method where the execution starts.
Initialization: A TreeMap named map1 is created with characters as keys and their frequency (number of occurrences) as values. The input string S1 is defined as “AcBCbDEdea”.
Counting Characters: The program converts the input string to lowercase using toLowerCase() and then converts it into a character array. It then iterates through each character in the array and updates the map1 TreeMap to count the occurrences of each character.
Transforming and Printing: After counting the occurrences, the program retrieves the key set from map1, which contains the unique characters in the input string. It then iterates through the characters in the key set. For each character, if its frequency in map1 is 2, it means the character appeared twice, so the program prints the character once in uppercase and once in lowercase.
For the given input string “AcBCbDEdea”, the output will be “AaBbCcDdEe”, which represents the transformed string that fulfills the specified requirements.
Input=”Selenium”
Output:
eleniumS
leniumeS
eniumleS
niumeleS
iumneleS
umineleS
muineleS
Cyclically Shifting the Input String: This Java program generates a set of substrings by cyclically shifting the input string “Selenium” characters to the left. It showcases nested loops and string manipulation to achieve this result.
Cyclically Shifting the Input String
package com.softwaretestingo.interviewprograms; public class InterviewPrograms14 { /* * Input="Selenium" * Output: * eleniumS * leniumeS * eniumleS * niumeleS * iumneleS * umineleS * muineleS */ public static void main(String[] args) { String str= "Selenium"; // char [ ] chs str.toCharArray ( ) ; int len = str.length() , temp = 0 ; String out = ""; for (int k = 0 ; k<len-1; k++) { for ( int i = k + 1 ; i < len ; i ++ ) { out =out + str.charAt(i); } temp= k ; while ( k >= 0 ) { out= out + str.charAt ( k ) ; k -- ; } k=temp; System.out.println ( out ) ; out=""; } } }
Output:
eleniumS leniumeS eniumleS niumeleS iumneleS umineleS muineleS
Explanation section by section:
- The program defines a class named InterviewPrograms14.
- Inside the class, there is a main method, which serves as the entry point for the program.
- The input string is initialized as Selenium.
- Variables len and temp are declared to store the length of the input string and to help in the shifting process, respectively.
- An empty string out is initialized to store the generated substrings.
- The program uses two nested for loops. The outer loop, controlled by the variable k, starts from 0 and goes up to len-1. This outer loop controls the number of substrings generated.
- The first inner loop, controlled by the variable i, starts from k + 1 and goes up to len – 1. This inner loop extracts characters from the input string starting from the position k + 1 and appends them to the out string. This step generates the part of the substring that comes after the character at position k.
- The program then sets temp to k to preserve the value of k for later use.
- The second inner loop is a while loop that executes while k is greater than or equal to 0. This loop extracts characters from the input string starting from the position k and appends them to the out string. This step generates the part of the substring that comes before the character at position k.
- After generating the complete substring, it prints the out string.
- Finally, the out string is reset to an empty string to prepare for the next iteration of the outer loop.
In summary, this program demonstrates how to cyclically shift the characters of a string to generate different substrings. It showcases the use of nested loops and string manipulation to achieve the desired result. The output will be a set of substrings formed by cyclically shifting the characters of “Selenium” to the left.
Alternative 1:
This Java program generates a set of substrings by cyclically shifting the characters of the input string “Selenium” to the left. The program achieves this by manipulating a character array representing the input string and repeatedly shifting the characters to generate the desired substrings.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms14_1 { /* * Input="Selenium" * Output: * eleniumS * leniumeS * eniumleS * niumeleS * iumneleS * umineleS * muineleS */ public static void main(String[] args) { String str = "Selenium"; char [ ] input = str.toCharArray(); int len = input.length ; printArr(input, len); } public static void printArr (char[] input, int len) { for (int i = 0 ; i<input.length ; i++ ) { char temp = input[0]; for ( int j = 1 ; j < len ; j ++ ) { input[j-1]=input[j]; } input[len-1]=temp; len--; System.out.println(input); } } }
Output:
eleniumS leniumeS eniumleS niumeleS iumneleS umineleS muineleS muineleS
Explanation of the program:
- The program defines a class named InterviewPrograms14_1.
- Inside the class, there is a main method, which serves as the entry point for the program.
- The input string is initialized as Selenium.
- The input string is converted into a character array called input.
- The program calls a custom method printArr, passing the input character array and its length len as arguments.
- The printArr method is responsible for generating and printing the substrings.
- Inside the printArr method, a for loop is used to iterate through each character of the input array.
- For each iteration, the first character of the input array is temporarily stored in the variable temp.
- Another for loop is used to shift the characters in the input array to the left.
- Characters from index 1 to len-1 are shifted one position to the left, effectively shifting the first character to the end of the array.
- The character in the last position (index len-1) is then set to the value of temp, completing the left cyclic shift.
- The length len is decremented for the next iteration to ensure that the last character (previously the first one) is omitted in the next shift.
- The input array after each cyclic shift is printed using System.out.println.
In summary, this program demonstrates how to cyclically shift characters of a string by converting it to a character array. It uses nested loops and character manipulation to generate and print a set of substrings. The output will be a series of substrings formed by cyclically shifting the characters of “Selenium” to the left.
Input: tomorrow
Output: t#m##rr###w
Replace a Specific Character with # Increasing Number: This Java program takes an input string “tomorrow” and converts it into a modified version where each occurrence of the letter ‘o’ is replaced with an increasing number of ‘#’ symbols. The number of ‘#’ symbols for each ‘o’ is determined by its position in the original string.
Replace a Specific Character with # Increasing Number
package com.softwaretestingo.interviewprograms; public class InterviewPrograms12 { /* * Input: tomorrow * Output: t#m##rr###w */ public static void main(String[] args) { StringBuilder charactersToAppend = new StringBuilder("#"); String input = "tomorrow"; while (input.contains("o")) { input = input.replaceFirst("o", charactersToAppend.toString()); charactersToAppend.append("#"); } System.out.println(input); } }
Output:
t#m##rr###w
Explanation:
- We start by importing the required package and defining a class named InterviewPrograms12.
- Inside the class, we declare the main method, which serves as the entry point for the program.
- We create a StringBuilder called charactersToAppend initialized with the ‘#’ character. This StringBuilder will be used to store additional ‘#’ symbols as we iterate through the input string.
- The input string “tomorrow” is assigned to the variable input.
- The program enters a while loop that continues as long as the input contains the letter ‘o’.
- Inside the loop, we use the replaceFirst method of the String class to replace the first occurrence of ‘o’ with the contents of the charactersToAppend StringBuilder. Initially, only one ‘#’ is appended, but with each iteration, an additional ‘#’ is appended to the charactersToAppend StringBuilder.
- After the replacement, the loop continues to find the next occurrence of ‘o’ until all ‘o’s are replaced.
- Finally, the modified input string is printed, which will be “t#m##rr###w”.
In summary, this program demonstrates the use of a while loop and the replaceFirst method to manipulate strings, and it shows how to build a modified version of the input string based on the occurrences of a specific character.
Alternative 1:
package com.softwaretestingo.interviewprograms; public class InterviewPrograms12_1 { /* * Input: tomorrow * Output: t#m##rr###w */ public void getSolution(String input) { int count = 0; String output = ""; char ch[] = input.toCharArray(); for(int i=0; i<ch.length; i++) { if(ch[i] == 'o') { count++; for(int j=0; j<count; j++) { output = output+Character.toString(ch[i]); output = output.replace(ch[i], '#'); } } else { output = output+Character.toString(ch[i]); } } System.out.println(output); } public static void main(String[] args) { String s = "tomorrow"; InterviewPrograms12_1 soluSoultionTest = new InterviewPrograms12_1(); soluSoultionTest.getSolution(s); } }
Output:
t#m##rr###w
Alternative 2:
This Java program aims to take an input string and modify it to replace each occurrence of the letter ‘o’ with an increasing number of ‘#’ symbols. It demonstrates an alternative approach to achieving the same result as the previous program using a different logic.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms12_2 { /* * Input: tomorrow * Output: t#m##rr###w */ public static String replaceWithString(String input,char present,String replace ) { int count =0; String s =""; while(input.contains(Character.toString(present))) { int n = input.indexOf(present)>0?(count++):(count=0); if(count == n) break; for(int i= count; i>1; i--) { s+=replace; } input= input.replaceFirst(Character.toString(present),s); } return input; } public static void main(String[] args) { String result=replaceWithString("tomorrow",'o',"#"); System.out.println(result); } }
Output:
t#m##rr###w
Here’s a step-by-step explanation of how the program works:
- The program defines a class named InterviewPrograms12_1.
- Inside the class, there is a method called getSolution, which takes a single parameter – the input string.
- The method initializes a variable count to keep track of the number of occurrences of ‘o’ and an empty string output to store the modified result.
- The input string is converted into a character array ch.
- The program iterates through each character of the input string using a for loop.
- If the current character is ‘o’, it increments the count and enters an inner loop to append the ‘o’ character and then replace it with ‘#’ count number of times in the output string.
- If the current character is not ‘o’, it simply appends the character to the output string.
- After processing all characters, the modified output string is printed as the final result.
In summary, the program showcases an alternate way to modify the input string, replacing ‘o’ characters with an increasing number of ‘#’ symbols based on the number of occurrences. It employs nested loops to achieve the desired result and displays the modified output as “t#m##rr###w” when the input is “tomorrow”.
Input:{A, B, C, D}
Output:{AA, BB, CC, DD}
Print Each Character 2 Times: This Java program aims to generate an output array based on a given input array. The input array is defined as {‘A’, ‘B’, ‘C’, ‘D’}. The desired output is an array where each element is a concatenation of the corresponding elements from the input array.
Print Each Character 2 Times Of Character Array
For example, given the input array {A, B, C, D}, the expected output is {AA, BB, CC, DD}.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms10 { /* * Input:{A, B, C, D} * Output:{AA, BB, CC, DD} */ public static void main(String[] args) { char[] ch = {'A', 'B', 'C', 'D'}; append(ch); } static void append(char ch[]) { char[] ch1=ch.clone(); System.out.println(ch); System.out.println(ch1); char[] result= new char[0]; StringBuilder sb = new StringBuilder(); for(int i=0;i<ch.length;i++) { sb.append(ch[i]); sb.append(ch1[i]); sb.append(' '); result = sb.toString().toCharArray(); } System.out.println(result); } }
Output:
AA BB CC DD
Explanation:
Initialize the input array: We create an array ch containing the characters ‘A’, ‘B’, ‘C’, and ‘D’. This serves as the input for our program.
char[] ch = {'A', 'B', 'C', 'D'};
Call the append method: We pass the input array ch as an argument to the append method for further processing.
append(ch);
Define the append method: This method takes the input array ch
and performs the necessary operations to generate the output array.
static void append(char ch[]) { // method code goes here }
Clone the input array: We create a clone of the input array ch and assign it to the array ch1. This is done to preserve the original input array for future use.
char[] ch1 = ch.clone();
Generate the output array: Using a StringBuilder, we iterate over the input array ch and append the corresponding element from the cloned array ch1 to create a pair. A space separates each pair. The resulting string is then converted to a character array and assigned to the result array. Finally, we print the generated output array result.
char[] result = new char[0]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < ch.length; i++) { sb.append(ch[i]); sb.append(ch1[i]); sb.append(' '); result = sb.toString().toCharArray(); } System.out.println(result);
In summary, this program takes an input array of characters, clones it, and generates an output array by combining each element of the input array with its corresponding element in the cloned array. The resulting pairs are stored in a string, which is then converted into an output array for display.
Alternative Way:
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; public class InterviewPrograms10_1 { /* * Input:{A, B, C, D} * Output:{AA, BB, CC, DD} */ public static void main(String[] args) { String[]arr= {"A","B","C","D"}; ArrayList<String> AL=new ArrayList<>(); for(int i=0;i<arr.length;i++) { String str=arr[i]+arr[i]; AL.add(str); } //System.out.println(arr); System.out.println(AL); } }
Output:
[AA, BB, CC, DD]
Explanation:
- Initialize the input array: We create an array arr containing the strings “A”, “B”, “C”, and “D”. This serves as the input for our program.
- Create an ArrayList: We create an ArrayList named AL to store the generated output.
- Generate the output list: We iterate over the input array arr using a loop. In each iteration, we concatenate the current element of arr with itself to create a new string str. The concatenated string is then added to the ArrayList AL.
for (int i = 0; i < arr.length; i++) { String str = arr[i] + arr[i]; AL.add(str); }
In summary, this program takes an input array of strings, generates an output list by concatenating each element of the input array with itself, and stores the results in an ArrayList. The final output is displayed by printing the ArrayList. The program demonstrates the usage of loops, string concatenation, and ArrayList in Java.
Input: 1234
Output:{1234, 11223344, 111222333444, 1111222233334444}
Increasing Number of Repetitions of Input Number’s Characters: The goal of this program is to generate a specific pattern based on a given input number and store the generated patterns in a list.
The input for this program is the number “1234”. The desired output is a series of patterns where each pattern contains an increasing number of repetitions of the input number’s characters.
For example, when the input number is “1234”, the program generates the following patterns: “1234”, “11223344”, “111222333444”, and “1111222233334444”.
Increasing Number of Repetitions of Input Number’s Characters
To achieve this, the program uses nested loops. The outer loop iterates over the characters of the input number. The middle loop repeats the current character a specific number of times based on the outer loop index. The innermost loop concatenates the repeated character to the finals variable. After each iteration, the generated pattern is added to the list, and the finals variable is reset for the next iteration.
Finally, the program prints the generated patterns stored in the list using the System.out.println() statement.
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.List; public class InterviewPrograms9 { /* * Input: 1234 * Output:{1234, 11223344, 111222333444, 1111222233334444} */ public static void main(String[] args) { String num = "1234"; String finals = ""; char arr[] = num.toCharArray(); List<String> list = new ArrayList<String>(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { for (int k = 0; k < i + 1; k++) { finals = finals + arr[j]; } } list.add(finals); finals = ""; } System.out.println(list); } }
Output:
[1234, 11223344, 111222333444, 1111222233334444]
Explanation:
Initialize the input number: We assign the string value “1234” to the variable num as the input number.
Declare necessary variables: The variable finals will store the generated pattern for each iteration. The arr array is created from the input number to iterate over its characters. The list is an ArrayList that will store the generated patterns.
String finals = ""; char arr[] = num.toCharArray(); List<String> list = new ArrayList<String>();
Generate the patterns: Using nested loops, we generate the patterns. The outer loop iterates over the characters of the input number. The middle loop repeats the current character i + 1 times. The innermost loop concatenates the repeated character to the finals variable. After each iteration, the generated pattern is added to the list, and finals is reset for the next iteration.
for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { for (int k = 0; k < i + 1; k++) { finals = finals + arr[j]; } } list.add(finals); finals = ""; }
Print the result: We print the generated patterns stored in the list.
System.out.println(list);
In summary, this program takes an input number, generates patterns by repeating its characters, and stores the patterns in a list. The output shows a series of patterns where each pattern contains an increasing number of repetitions of the input number’s characters.
Input: s = “egg”, t = “add”
Output: true
Input: s = “foo”, t = “bar”
Output: false
Input: s = “paper”, t = “title”
Output: true
Check Character Sequence Is in Same Order Or Not: The program InterviewPrograms54 aims to determine if two strings, s and t, are isomorphic. Two strings are considered isomorphic if the characters in one string can be replaced with characters in the other string while preserving the order of characters.
Each character in the first string should map to a unique character in the second string, and no two characters can map to the same character. However, a character may map to itself.
Check Character Sequence Is in Same Order Or Not
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class InterviewPrograms54 { /* * Given two strings s and t, determine if they are isomorphic. Two strings s * and t are isomorphic if the characters in s can be replaced to get t. * * All occurrences of a character must be replaced with another character while * preserving the order of characters. No two characters may map to the same * character, but a character may map to itself. * * Example 1: * * Input: s = "egg", t = "add" * Output: true Example 2: * * Input: s = "foo", t = "bar" * Output: false Example 3: * * Input: s = "paper", t = "title" * Output: true */ public static void main(String[] args) { System.out.println(areIsomorphic("egg","add")); } static boolean areIsomorphic(String str1, String str2) { List<Integer> str1ChrSequence=getCharSequence(str1); List<Integer> str2ChrSequence=getCharSequence(str2); return str1ChrSequence.equals(str2ChrSequence); } static List<Integer> getCharSequence(String str) { Map<Character,Integer> resultMap=new LinkedHashMap<>(); int count=1; for(char ch:str.toCharArray()) { if(resultMap.containsKey(ch)) { resultMap.put(ch,resultMap.get(ch)+1); } else { resultMap.put(ch,count); } } List<Integer> resultList=new ArrayList<>(); resultList.addAll(resultMap.values()); return resultList; } }
Output
true
Here’s how the program works:
- The program takes two input strings: str1 and str2. For example, “egg” and “add” are provided as input.
- The program calls the areIsomorphic function with the two input strings as arguments.
- Inside the areIsomorphic function, it calls the getCharSequence function twice, once for each input string. The getCharSequence function calculates the character sequence for each string.
- The getCharSequence function iterates through the characters of the input string and stores their occurrences in a LinkedHashMap. The order of insertion is preserved, and each character’s occurrence count is maintained in the map.
- The function then converts the values of the LinkedHashMap (occurrence counts) into a list and returns it as the character sequence of the input string.
- The areIsomorphic function compares the character sequences of the two input strings obtained from getCharSequence. If the character sequences are equal, it returns true, indicating that the strings are isomorphic; otherwise, it returns false.
- In this specific case, since the input strings are “egg” and “add,” both strings have the same character sequence (1, 2), so the program will output true.
The output represents whether the two input strings are isomorphic or not. In the example provided, since the strings “egg” and “add” can be mapped to each other while preserving the order of characters (e->a, g->d), the output is true.
Enter the String: softwaretestingo
Enter The K Value: 2
After Removing The Characters Having More then 2 Times:- fwaring
Remove Characters That Appear More Than K Times: This Java program takes a string as input and an integer value ‘k’, and then it removes all characters from the string that appear more than ‘k’ times. The program uses a HashMap to count the frequency of each character in the input string and then constructs a new string without the characters that exceed the given frequency threshold ‘k’.
Remove Characters That Appear More Than K Times
package com.softwaretestingo.interviewprograms; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class InterviewPrograms85 { public static String removeChars(String str, int k) { // Using HashMap to count frequencies Map<Character, Integer> freq = new HashMap<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); freq.put(c, freq.getOrDefault(c, 0) + 1); } // create a new empty string StringBuilder res = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); // Append the characters which // appears less than equal to k times if (freq.get(c) < k) { res.append(c); } } return res.toString(); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the String: "); String str=br.readLine(); System.out.println("Enter The K Value: "); int k = Integer.parseInt(br.readLine()); System.out.println("After Removing The Characters Having More then "+k+ " Times:- "+ removeChars(str, k)); } }
Output
Enter the String: softwaretestingo Enter The K Value: 2 After Removing The Characters Having More then 2 Times:- fwaring
Let’s break down the program step by step to understand what it does:
- The program defines a class named InterviewPrograms85.
- Inside the class, there are two methods: removeChars and main.
- The removeChars method takes two parameters: a string str and an integer k. This method will remove characters from the input string str that appear more than ‘k’ times.
- Inside the removeChars method, a HashMap<Character, Integer> named freq is created to store the frequency of each character in the input string. The loop iterates through each character of the input string and updates the frequency in the freq HashMap.
- A StringBuilder named res is initialized. This StringBuilder will be used to construct the new string with characters that appear less than or equal to ‘k’ times.
- Another loop runs through each character of the input string again. For each character, the program checks its frequency in the freq HashMap. If the frequency is less than ‘k’, it means the character appears ‘k’ times or less, so it is appended to the res StringBuilder.
- After both loops finish, the res StringBuilder contains the new string with characters that appear less than or equal to ‘k’ times.
- The removeChars method returns the final result as a string using res.toString().
- In the main method, the program uses a BufferedReader to read the input from the user. The user is prompted to enter a string and an integer ‘k’.
- The program then calls the removeChars method with the input string and ‘k’ and prints the result. It will display the input string after removing all characters that appear more than ‘k’ times.
For example, if the input string is “mississippi” and ‘k’ is 2, the program will remove all characters that appear more than 2 times and output “mp”.
Alternative Way 1:
This Java program takes a string as input and an integer value ‘k’, and then it removes all characters from the string that appear more than ‘k’ times. The program uses an array-based approach with a hash table to count the frequency of each character in the input string. It then modifies the input character array in-place to remove characters exceeding the given frequency threshold ‘k’.
package com.softwaretestingo.interviewprograms; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class InterviewPrograms85_1 { static final int MAX_CHAR = 26; public static void removeChars(char[] charArray, int k) { // Hash table initialised to 0 int hash[]=new int[MAX_CHAR]; for (int i = 0; i <MAX_CHAR; ++i) hash[i]=0; // Increment the frequency of the character int n = (charArray).length; for (int i = 0; i < n; ++i) hash[charArray[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[charArray[i] - 'a'] < k) { charArray[index++] = charArray[i]; } } for (int i = index; i < n; ++i) charArray[i] = ' '; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the String: "); String str=br.readLine(); System.out.println("Enter The K Value: "); int k = Integer.parseInt(br.readLine()); char[] charArray=str.toCharArray(); removeChars(charArray,k); System.out.println("After Removing The Characters Having More then "+k+ " Times:- "+ String.valueOf(charArray)); } }
Output
Enter the String: softwaretestingo Enter The K Value: 2 After Removing The Characters Having More then 2 Times:- fwaring
Let’s break down the program step by step to understand what it does:
- The program defines a class named InterviewPrograms85_1.
- Inside the class, there are two methods: removeChars and main.
- The removeChars method takes two parameters: a character array charArray and an integer k. This method will remove characters from the charArray that appear more than ‘k’ times.
- Inside the removeChars method, an integer array hash of size MAX_CHAR (26 in this case) is created and initialized with 0. The hash array will be used to count the frequency of each character in the input string.
- The method then iterates through each character of the charArray. For each character, it increments the corresponding frequency count in the hash array.
- A variable index is used to keep track of the next index in the reduced string. It is initialized to 0.
- Another loop runs through each character of the charArray again. For each character, the program checks its frequency in the hash array. If the frequency is less than ‘k’, it means the character appears ‘k’ times or less, so it is kept in the reduced string. The character is then copied to the charArray at the next available index (charArray[index]) and index is incremented.
- After both loops finish, the charArray is modified in-place to contain the reduced string with characters that appear less than or equal to ‘k’ times.
- Any remaining characters at indices index and beyond in the charArray are filled with spaces to clean up the unwanted characters that appear more than ‘k’ times.
- In the main method, the program uses a BufferedReader to read the input from the user. The user is prompted to enter a string and an integer ‘k’.
- The program then calls the removeChars method with the input character array and ‘k’ to modify the array in-place.
- Finally, the modified character array is converted back to a string using String.valueOf(charArray), and the program prints the result. It will display the input string after removing all characters that appear more than ‘k’ times.
For example, if the input string is “mississippi” and ‘k’ is 2, the program will modify the charArray in-place to “mpp” and output “After Removing The Characters Having More than 2 Times:- mpp”.
Input: “abcdcbe”
Longest palindrome substring is: bcdcb
Length is: 5
Longest Palindrome Substring: This Java program finds the longest palindrome substring (LPS) from a given input string and prints it along with its length. A palindrome is a string that reads the same forwards and backward. The program employs a nested loop to check all possible substrings and uses a simple technique to verify whether each substring is a palindrome.
Longest Palindrome Substring
package com.softwaretestingo.interviewprograms; public class InterviewPrograms87 { static int findLongSubstr(String str) { // Get length of input String int n = str.length(); // All subStrings of length 1 are palindromes int maxLength = 1, start = 0; // Nested loop to mark start and end index for (int i = 0; i < str.length(); i++) { for (int j = i; j < str.length(); j++) { int flag = 1; // Check palindrome for (int k = 0; k < (j - i + 1) / 2; k++) if (str.charAt(i + k)!= str.charAt(j-k)) flag = 0; // Palindrome if (flag != 0 && (j - i + 1) > maxLength) { start = i; maxLength = j - i + 1; } } } System.out.print("Longest palindrome substring is: "); printSubStr(str, start, start + maxLength - 1); // Return length of LPS return maxLength; } // Function to print a subString str[low..high] static void printSubStr(String str, int low, int high) { for (int i = low; i <= high; ++i) System.out.print(str.charAt(i)); } public static void main(String[] args) { String str = "abcdcbe"; System.out.print("\nLength is: "+ findLongSubstr(str)); } }
Output
Longest palindrome substring is: bcdcb Length is: 5
Let’s break down the program step by step to understand what it does:
- The program defines a class named InterviewPrograms87.
- Inside the class, there are three methods: findLongSubstr, printSubStr, and main.
- The findLongSubstr method takes a string str as input and calculates the longest palindrome substring.
- The method first gets the length of the input string using int n = str.length().
- The maxLength variable is initialized to 1, and the start variable is set to 0. These variables will be used to keep track of the longest palindrome substring and its starting index.
- The method enters a nested loop to check all possible substrings of the input string.
- The outer loop (i loop) runs from 0 to n-1, representing the starting index of the substring.
- The inner loop (j loop) runs from i to n-1, representing the ending index of the substring.
- Inside the nested loops, the program checks whether the current substring is a palindrome.
- To check for a palindrome, the flag variable is set to 1 initially. Then, the program runs another loop (k loop) to compare characters from the start and end of the substring. If any pair of characters does not match, the flag is set to 0, indicating that the substring is not a palindrome.
- If the substring is a palindrome and its length (j – i + 1) is greater than the current maxLength, the start and maxLength variables are updated to store the starting index and length of the longest palindrome substring found so far.
- After the nested loops finish, the method prints the longest palindrome substring using the printSubStr method and returns the length of the LPS.
- The printSubStr method takes a string str and the starting (low) and ending (high) indices of the substring and prints the characters in the substring.
- The main method initializes a string str with the value “abcdcbe”.
- The program calls the findLongSubstr method with the input string str.
- The program then prints the length of the longest palindrome substring.
In summary, the program efficiently finds the longest palindrome substring from a given input string using nested loops and simple character comparisons. The algorithm has a time complexity of O(n^3) due to the nested loops, making it less efficient for larger strings. However, it is a straightforward approach to understand and implement for finding LPS in smaller strings.
Alternative Way 1:
This Java program finds the longest palindrome substring (LPS) from a given input string using a different approach compared to the previous programs. It uses two nested loops to explore all possible substrings and checks whether each substring is a palindrome by comparing characters from both ends of the substring.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms87_1 { static int findLongSubstr(String str) { // Stores Longest Palindrome Substring String longest = ""; int n = str.length(); int j; // To store substring which we think can be a palindrome String subs = ""; // To store reverse of substring we think can be palindrome String subsrev = ""; for (int i = 0; i < n; i++) { j = n - 1; while (i < j) { // Checking whether the character at i and j // are same. // If they are same then that substring can be LPS if (str.charAt(i) == str.charAt(j) && longest.length() < (j - i + 1)) { subs = str.substring(i, j + 1); subsrev = new StringBuilder(subs).reverse().toString(); if (subs.equals(subsrev)) { longest = subs; } } j--; } } // If no longest substring then we will return first // character if (longest.length() == 0) { longest = str.substring(0, 1); } System.out.println( "Longest palindrome substring is: " + longest); // Return length of LPS return longest.length(); } public static void main(String[] args) { String str = "abcdcbe"; System.out.print("\nLength is: "+ findLongSubstr(str)); } }
Output
Longest palindrome substring is: bcdcb Length is: 5
Let’s break down the program step by step to understand what it does:
- The program defines a class named InterviewPrograms87_1.
- Inside the class, there are two methods: findLongSubstr and main.
- The findLongSubstr method takes a string str as input and calculates the longest palindrome substring.
- The method initializes three strings: longest (to store the longest palindrome substring found), subs (to store a potential palindrome substring), and subsrev (to store the reverse of the subs).
- The variable n is set to the length of the input string using int n = str.length().
- The method uses two nested loops to check all possible substrings of the input string.
- The outer loop (i loop) runs from 0 to n-1, representing the starting index of the substring.
- The inner loop (j loop) runs from n-1 to i+1, representing the ending index of the substring. This ensures that i and j are different to avoid considering single-character substrings.
- Inside the nested loops, the program checks whether the substring str.substring(i, j + 1) (denoted by subs) is a palindrome.
- If subs is a palindrome and its length is greater than the current longest.length(), the program updates longest to store the palindrome found.
- The program creates the reverse of subs using subsrev = new StringBuilder(subs).reverse().toString();.
- If subs and subsrev are equal, it means subs is a palindrome, and the program updates longest to store the palindrome found.
- After the nested loops finish, the method prints the longest palindrome substring using System.out.println(“Longest palindrome substring is: ” + longest);.
- The method returns the length of the LPS, which is the length of longest.
- The main method initializes a string str with the value “abcdcbe”.
- The program calls the findLongSubstr method with the input string str.
- The program then prints the length of the longest palindrome substring.
In summary, the program efficiently finds the longest palindrome substring from a given input string using two nested loops and character comparisons. It checks all possible substrings and verifies whether each substring is a palindrome. The algorithm has a time complexity of O(n^3), making it less efficient for larger strings. However, it is a straightforward approach to understand and implement for finding LPS in smaller strings.
Print Pascal’s triangle: We can able to print Pascal’s triangle in various ways. Below we have mentioned various ways:

Print a Pascal’s Triangle Without Using an Array
This Java program prints Pascal’s Triangle based on the number of rows input by the user. Pascal’s Triangle is a triangular array of binomial coefficients, named after the French mathematician Blaise Pascal. The program uses nested loops and basic mathematical calculations to generate and print the triangle.
package com.softwaretestingo.interviewprograms; import java.util.Scanner; public class InterviewPrograms88 { public static void main(String[] args) { int row, i, j, space, num; Scanner in = new Scanner(System.in); System.out.print("Enter value for rows: "); row = in.nextInt(); for(i=0; i<row; i++) { for(space=row; space>i; space--) { System.out.print(" "); } num=1; for(j=0; j<=i; j++) { System.out.print(num+ " "); num = num*(i-j)/(j+1); } System.out.print("\n"); } } }
Output
Enter value for rows: 10 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1
Let’s break down the program step by step to understand what it does:
- The program defines a class named InterviewPrograms88.
- Inside the class, there is a main method that executes the program.
- The main method starts by declaring variables row, i, j, space, and num.
- It uses a Scanner object in to read the user input for the number of rows of Pascal’s Triangle.
- The program asks the user to enter the number of rows with the message Enter value for rows: , and it reads the user input using row = in.nextInt().
- The program then enters a for loop that iterates i from 0 to row-1, representing the row number of Pascal’s Triangle.
- Inside the outer loop, there is a nested for loop that iterates space from row to i+1. The loop is used to print spaces to format the triangle properly.
- After printing the spaces, the variable num is set to 1. This variable is used to print the numbers in the current row of the triangle.
- Another for loop with variable j runs from 0 to i, representing the column number of the current row.
- Inside the inner for loop, the program first prints the current value of num and a space using System.out.print(num+ ” “);.
- The next line of code updates the value of num for the next iteration of the loop. The new value of num is calculated using the formula: num = num * (i – j) / (j + 1);. This formula calculates the binomial coefficient for the current position, which is required to generate Pascal’s Triangle.
- After printing all the numbers in the current row, the program moves to the next line using System.out.print(“\n”);, which starts a new line for the next row.
- The process repeats for all rows, and Pascal’s Triangle is printed on the console.
In summary, this Java program generates Pascal’s Triangle based on the user input for the number of rows. It uses nested loops to iterate through each row and column, calculates the binomial coefficients using the formula, and prints the numbers in the triangle accordingly. Pascal’s Triangle is a fascinating mathematical concept, and this program provides a simple and elegant way to visualize it.
Print a Pascal’s Triangle With Using Array
This Java program prints Pascal’s Triangle using the concept of the binomial coefficient. Pascal’s Triangle is a triangular array of binomial coefficients, named after the French mathematician Blaise Pascal. The program calculates the binomial coefficients for each position in the triangle and then prints the triangle.
package com.softwaretestingo.interviewprograms; import java.util.Scanner; public class InterviewPrograms88_1 { public static void main(String[] args) { int row, i, j,k,l, space; Scanner in = new Scanner(System.in); System.out.print("Enter value for rows: "); row = in.nextInt(); int ncr[][] = new int[row][row]; //First element is always 1 ncr[0][0] = 1; //start from 2nd row i.e from i=1 for(i=1; i<row; i++) { //First element of each row is always 1 ncr[i][0] = 1; for(j=1; j<=i; j++) { ncr[i][j] = ncr[i-1][j-1] + ncr[i-1][j]; } } //Output the array for(i=0; i<row; i++) { //Output the blank space for(k=0; k<row-i; k++) { System.out.print(" "); } for(j=0; j<=i; j++) { System.out.print(ncr[i][j]+" "); } System.out.println(); } } }
Output
Enter value for rows: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Let’s break down the program step by step to understand what it does:
- The program defines a class named InterviewPrograms88_1.
- Inside the class, there is a main method that executes the program.
- The main method starts by declaring variables row, i, j, k, l, and space.
- It uses a Scanner object in to read the user input for the number of rows of Pascal’s Triangle.
- The program asks the user to enter the number of rows with the message Enter value for rows: , and it reads the user input using row = in.nextInt().
- The program then initializes a 2D array ncr with dimensions row × row to store the binomial coefficients.
- The element ncr[0][0] is set to 1 because the first row of Pascal’s Triangle always contains only one element, which is 1.
- The program then enters a nested for loop to calculate the binomial coefficients for the rest of the rows.
- The outer loop runs from 1 to row-1, representing the row number of Pascal’s Triangle.
- Inside the outer loop, the first element of each row ncr[i][0] is set to 1 because the first element of each row is always 1.
- The inner loop (j loop) runs from 1 to i, representing the column number of the current row.
- Inside the inner loop, the program calculates the binomial coefficient for the current position using the formula: ncr[i][j] = ncr[i-1][j-1] + ncr[i-1][j];.
- After calculating all the binomial coefficients, the program enters another set of nested loops to print the Pascal’s Triangle.
- The outer loop runs from 0 to row-1, representing the row number of Pascal’s Triangle.
- Inside the outer loop, the program prints blank spaces (” “) to format the triangle properly. The number of blank spaces is equal to row-i.
- The inner loop (j loop) runs from 0 to i, representing the column number of the current row.
- Inside the inner loop, the program prints the binomial coefficient for the current position in the triangle using System.out.print(ncr[i][j]+” “);.
- After printing all the numbers in the current row, the program moves to the next line using System.out.println();, which starts a new line for the next row.
- The process repeats for all rows, and Pascal’s Triangle is printed on the console.
In summary, this Java program generates Pascal’s Triangle using the concept of the binomial coefficient. It first calculates the binomial coefficients for each position in the triangle and stores them in a 2D array. Then, it prints the triangle by formatting the output with appropriate blank spaces. Pascal’s Triangle is a fascinating mathematical concept, and this program provides an efficient and elegant way to visualize it.
Enter the string: SoftwareTestingo
Enter the Character you want to search: e
e is present at index 7
Search a Letter In a String: Welcome to the world of Java programming, where we embark on an exciting journey of searching for a specific letter within a given string! In this Java Programs Examples, we’ll explore the power of algorithms and string manipulation as we dive into the task of locating a particular letter’s presence in a text. Whether you’re a beginner eager to learn the fundamentals of Java or an experienced coder seeking to sharpen your problem-solving skills, this program caters to all levels.
Throughout this exploration, we’ll unravel the step-by-step process of designing an efficient solution to this search challenge. We’ll delve into Java’s syntax and explore techniques to optimize our code for speed and simplicity. By understanding the logic behind our program, you’ll gain insights into algorithm design, conditional statements, and character handling in Java.
Join us as we learn how to navigate through strings, detect characters, and present the results of our search. From its practical applications in text analysis to enhancing your programming prowess, this Java program is a fantastic opportunity to expand your knowledge and appreciation of the Java language. Let’s get ready to embark on this exciting coding adventure and discover the art of searching a letter in a string!
Search a Letter In a String
package com.softwaretestingo.interviewprograms; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class InterviewPrograms94 { //Write a program for removing white spaces in a String. public static void main(String[] args) throws IOException { String str; char c; // create an object of Scanner BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the string"); str=br.readLine(); System.out.println("Enter the Character you want to search"); c=(char)br.read(); int index = str.indexOf(c); System.out.printf(c +" is present at index %d", index); } }
Output
Enter the string SoftwareTestingo Enter the Character you want to search e e is present at index 7
This Java program is designed to search for a specific character in a given string. Let’s walk through the code step by step:
- Import Statements: The program starts without any import statements, as it doesn’t require any external classes from the Java standard library.
- Class and Method Declaration: The program defines a class named InterviewPrograms94. Inside the class, there is the main method, which serves as the entry point of the program.
- User Input and Declaration: In the main method, the program prompts the user to enter a string using System.out.println(). The user’s input is obtained using a BufferedReader, which reads input from the console. The input string is then stored in the str variable.The program also prompts the user to enter a character they want to search for in the string. The user’s input is obtained using another BufferedReader, and the character is stored in the c variable.
- Searching for the Character: The program uses the indexOf method of the String class to find the first occurrence of the character c in the input string str. The result is stored in the index variable.
- Output: Finally, the program prints the index of the first occurrence of the character c in the input string using System.out.printf().
In summary, this Java program efficiently searches for a specific character within a given string and displays the index of its first occurrence. It demonstrates how to use the indexOf method to find a character in a string and interact with user inputs. Java beginners can learn from this code about handling user input, character manipulation, and performing search operations within a string. Happy coding!
Original String: Hello Interview Is Going On Now
After Converting: hello interview is going on now
Convert Unique Uppercase to Lowercase Letter: The “Uppercase to Lowercase Conversion” Java program addresses the task of converting uppercase letters within a given string into their corresponding lowercase forms. By processing the provided input string, the program produces an output string where all uppercase letters have been transformed to lowercase while preserving the positions and characters of the remaining text.
For instance, when presented with the input string “Hello Interview Is Going On Now,” the java programming language executes the conversion and yields the output string “hello interview is going on now.” This program is particularly useful in scenarios where uniform letter casing is required for consistency and ease of further processing.
Through this program, learners become acquainted with the essentials of string manipulation, character iteration, and conditional transformations in Java programming. This foundational exercise introduces beginners to fundamental concepts used in text processing and prepares them for more complex tasks involving string handling and data transformation.
Convert Unique Uppercase to Lowercase Letter Program
This Java program, InterviewPrograms_100, aims to convert uppercase letters within a given string to their corresponding lowercase forms. It does so by iteratively processing each character in the input string and transforming uppercase characters to lowercase while leaving the rest of the string unchanged.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms_100 { /* * Given a string and return the string after replacing every uppercase letter * with the same lowercase letter. Input : s = "Hello Interview Is Going On Now" * Output : "hello interview is going on now" */ //This Questions Asked in Cigniti technologies public static void main(String[] args) { String s= "Hello Interview Is Going On Now"; char[]c = s.toCharArray(); for(int i=0;i<c.length;++i ) { if(c[i]>=65 && c[i]<=90) { c[i] = (char) (c[i] + 32); } } System.out.println("After Converting: "+String.valueOf(c)); } }
Output:
Original String: Hello Interview Is Going On Now After Converting: hello interview is going on now
Here’s a concise step-by-step explanation suitable for Java beginners:
- Program Objective: The program’s goal is to transform an input string, such as “Hello Interview Is Going On Now”, into an output string where all uppercase letters are converted to lowercase. For example, the input would yield the output “hello interview is going on now”.
- Character Array: The program first converts the input string into a character array named c using the toCharArray() method. This facilitates individual character manipulation.
- Iterative Conversion Loop: The program employs a loop that iterates through each character in the character array c.
- Conditional Transformation: Within the loop, a conditional statement checks whether the current character’s ASCII value falls within the uppercase letter range (between 65 and 90). If true, the character is converted to lowercase using the ASCII conversion logic (c[i] + 32).
- Printing Results: After the loop, the program prints the modified character array as a string using String.valueOf(c).
- Main Method: The main method initializes the program, defines the example input string, and processes it to achieve the desired transformation. The converted string is then printed as the output.
Through this program, beginners learn about character manipulation, ASCII values, and basic iterative processing of strings. It illustrates the process of converting characters between different cases and showcases how simple programming constructs can be used to achieve significant text transformations.
Input: 01230
Output:03210
WAP to Convert 01230 To 03210: This Java program is designed to reverse a given integer represented as a string, add leading zeros if necessary, and print the reversed number. The program demonstrates how to format an integer with leading zeros using String.format, convert an integer to a string, iterate through a string in reverse order, and concatenate characters to form the reversed number.
Convert 01230 To 03210
package com.softwaretestingo.interviewprograms; public class InterviewPrograms15 { /* * Input: 01230 * Output: 03210 */ public static void main(String[] args) { int n = 1230 ; String s = String.format ( "%05d",n); // to get 1230 to 01230 System.out.println ( s ) ; int len = s.length ( ) ; String rev = "" ; for ( int i = len - 1 ; i >= 0 ; i-- ) { rev = rev + s.charAt ( i ) ; } System.out.println ( rev ) ; } }
Output:
01230 03210
Description of the program:
- The program defines a class named InterviewPrograms15.
- Inside the class, there is a main method, which serves as the entry point for the program.
- The input number is initialized as an integer n with the value 1230.
- The program uses String.format to convert the integer n to a string s with leading zeros. The format specifier %05d ensures that the resulting string has a length of 5, padding the number with zeros if necessary. The resulting string will be “01230”.
- The program prints the value of the string s, which will be “01230”.
- The program calculates the length of the string s using the length method and stores it in the integer variable len.
- An empty string rev is initialized to store the reversed number.
- The program uses a for loop to iterate through each character of the string s in reverse order. The loop starts from the last character (index len-1) and goes backward until the first character (index 0).
- Inside the loop, each character is retrieved using s.charAt(i) and appended to the string rev, effectively reversing the order of the digits.
- Finally, the program prints the reversed number stored in the string rev, which will be “03210”.
In summary, this program takes an integer, converts it to a string with leading zeros, and then reverses the order of the digits to generate the output. It showcases the use of String.format to format integers as strings with leading zeros, string manipulation, iteration through strings, and character retrieval to achieve the desired result. The output will be the reversed number “03210” for the input “01230”.
Alternative 1:
This Java program takes an input string “01230” and reverses its characters to produce the output “03210”. The Java program function demonstrates how to convert a string into a character array, iterate through the character array in reverse order, and then concatenate the characters to generate the reversed string.
package com.softwaretestingo.interviewprograms; public class InterviewPrograms15_1 { /* * Input: 01230 * Output: 03210 */ public static void main(String[] args) { String s= "01230"; System.out.println("Input: "+s); String newStr = " " ; char c [ ] =s.toCharArray ( ) ; for ( int i = c.length - 1 ; i >= 0 ; i-- ) { newStr= newStr + c [ i ] ; } System.out.println ("Output"+newStr); } }
Output:
01230 03210
Explanation of the program section by section:
- The program defines a class named InterviewPrograms15_1.
- Inside the class, there is a main method, which serves as the entry point for the program.
- The input string “01230” is initialized as s.
- The program prints the input string with the message “Input: ” using System.out.println.
- An empty string newStr is initialized to store the reversed string.
- The program converts the input string s into a character array c using the toCharArray method of the String class. This step allows easy iteration through the characters.
- The program uses a for loop to iterate through each character of the character array c in reverse order. The loop starts from the last character (index c.length – 1) and goes backward until the first character (index 0).
- Inside the loop, each character is retrieved using c[i], and it is concatenated to the newStr string. This step effectively reverses the order of the characters.
- Finally, the program prints the reversed string stored in the newStr string with the message “Output” using System.out.println. The output will be “Output: 03210”.
In summary, this program takes an input string, converts it into a character array, and then reverses the order of the characters to produce the output string. It showcases string manipulation, character array conversion, iteration through the character array, and string concatenation to achieve the desired result. The output will be “Output: 03210” for the input “01230”.
Input: tomorrow
Output: ooorrtmw
Sort A String According To The Frequency Of Characters: The program InterviewPrograms51 aims to rearrange the characters of a given input string in descending order based on their frequency of occurrence.
Sort A String According To The Frequency Of Characters
To solve this program, we have taken the help of various Java topics like:
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class InterviewPrograms51 { /* * Input: tomorrow * Output: ooorrtmw */ public static void main(String[] args) { String input = "tomorrow"; Map<Character, Integer> map = StringManipulation(input); // sort and print List<Map.Entry<Character, Integer>> toSort = new ArrayList<>(map.entrySet()); toSort.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); for ( Map.Entry<Character, Integer> x : toSort ) { int count = x.getValue(); while ( count > 0 ) { System.out.print ( x.getKey ( ) ) ; count-- ; } } } private static Map<Character, Integer> StringManipulation(String input) { Map<Character, Integer> map=new LinkedHashMap<>(); for(char ch : input.toCharArray()) if(map.containsKey(ch)) map.put(ch, map.get(ch)+1); else map.put(ch, 1); return map; } }
Output
ooorrtmw
Here’s how the program works:
- The input string “tomorrow” is given as the input.
- The program uses the StringManipulation() method to create a map called map, where the keys are characters from the input string, and the values are their corresponding frequencies.
- The StringManipulation() method iterates through each character in the input string. If the character is already present in the map, it increments its count by 1. Otherwise, it adds the character to the map with a count of 1.
- The map now contains the frequencies of each character in the input string.
- The program then creates a list toSort with the entries of the map. This step is done to sort the characters based on their frequencies.
- The list toSort is sorted in descending order of frequencies using Map.Entry.comparingByValue(Comparator.reverseOrder()).
- Finally, the sorted list is iterated, and for each character and its corresponding frequency, the program prints the character count number of times to the console.
In this specific case, the program will output:
ooorrtmw
The output represents the rearranged characters from the input string “tomorrow” in descending order of their frequencies. The character ‘o’ occurs 3 times, ‘r’ occurs 2 times, ‘t’ occurs 1 time, ‘m’ occurs 1 time, and ‘w’ occurs 1 time in the input string.