Explore topic-wise InterviewSolutions in Current Affairs.

This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.

1.

What is the output of the below program?

Answer»

public class StringTest {public STATIC void main(STRING[] args) { String str1 = new String("interviewbit"); String str2 = new String("INTERVIEWBIT"); System.out.println(str1 = str2);}}

This program prints "INTERVIEWBIT" since str2 String is assigned to str1 String. The comparison operator “==” should not be confused with the assignment operator “=”.

Conclusion

Here's everything you need to know about Java String interview questions and answers. To summarize, there are many specifics RELATED to String that every Java programmer needs to be familiar with and these String questions will not just help you prepare better for Java interviews, but will also open a new door to learning more about String. 

The more familiar you are with these frequently asked interview questions, the greater your chances of getting hired.

Hopefully, we were ABLE to answer any questions or concerns you had. Wishing you luck in your future endeavours. 

Recommended Interview Preparation Resources
  • Java Projects With Source Code
  • Java MCQ With Answers
  • Java Interview Questions for 5 years Experience
  • Technical Interview Questions
  • Coding Interview Questions
  • InterviewBit Blog
  • DSA
2.

What will be the output of the below program?

Answer»

String str1 = "scaler"; //Line1String STR2 = new String("scaler"); //Line2str2.intern(); //Line 3System.out.println(str1 == str2);

The output of the above program is false. We know that when the intern() method is executed or invoked on a string object, then it checks whether the String pool already has a same string value (scaler) or not, and if it is available, then the reference to the that string from the string constant pool is returned. In the above EXAMPLE, the intern method is invoked on str2. However, since we didn't assign it back to str2, str2 REMAINS UNCHANGED and therefore, both str1 and str2 have different references. If we change the code in line 3 to str2 = str2.intern(), then the output will be true.

3.

Write a program to check whether the given input string is a palindrome.

Answer»

When a string is the same when read right to LEFT or left to right, it is called a palindrome. To assess whether a string is a palindrome or not, we first reverse the string and then compare the reversed string with the original ONE. Below is a JAVA program that will check if a string is a palindrome.

public class PalindromeChecker { public STATIC VOID main (String[] args)  { String str1 = "rotator"; String revstr = reverseString(str1); //revstr=reverse string if (str1.equals(revstr))  { System.out.println("The string" + str1 + " is a Palindrome String."); }  else  { System.out.println("The string" + str1 + " is not a Palindrome String."); } } // a method for reversing a string public static String reverseString(String str2)  { String revstr = ""; for (int i = str2.length() - 1; i >= 0; i--)  { revstr += str2.charAt(i); } return revstr; }}

Output:

The string rotator is a Palindrome String.

As shown in the above example, we have a string "Rotator" stored in string object "str1" and another string object "revstr" to store the reverse of str1. To check whether two strings are equal or not, we have used the equals() method. 

4.

How can we remove a specific character from a String?

Answer»

There are several ways to remove a character from a string, such as REMOVING the character at the beginning of the string, the end of the string, or at a specific position. It is possible to remove a specific character from a string using the replace() method. You can also use remove() with different VARIATIONS like replaceFirst(), replaceAll(), etc. Below is a JAVA program that uses replace(), replaceFirst(), and replaceAll() methods to remove characters from a String.

public CLASS RemoveCharacter{ public static void main(String args[]) { String str = "Scaler by InterviewBit"; //remove the specified character. System.out.println("String after removing 'e' = "+str.replace("e", "")); //remove the FIRST occurrence of the specified character. System.out.println("String after removing First 'e' = "+str.replaceFirst("e", "")); //remove all occurrences of the specified character. System.out.println("String after replacing all small letters = "+str.replaceAll("([A-Z])", "")); }}

Output:

String after removing 'e' = Scalr by IntrviwBitString after removing First 'e' = Scalr by InterviewBitString after replacing all small letters = caler by nterviewit
5.

In what way should two strings be compared to determine whether they are anagrams?

Answer»

If two strings contain the same characters but in a different ORDER, they can be said to be anagrams. Consider dusty and study. In this case, dusty's characters can be formed into a study, or study's characters can be formed into dusty. Below is a java program to check if two strings are anagrams or not.

import java.util.Arrays;public class CheckAngagram { public static void main(String[] args) { String str1 = "BORED"; String str2 = "Robed"; //Convert strings to lowercase str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); // Check to see if the lengths are the same if(str1.length() == str2.length()) { // convert strings into char array char[] str1charArray = str1.toCharArray(); char[] str2charArray = str2.toCharArray(); // sort the char array Arrays.sort(str1charArray); Arrays.sort(str2charArray); // if the SORTED char arrays are same or IDENTICAL // then the strings are anagram boolean result = Arrays.equals(str1charArray, str2charArray); if(result) { System.out.println(str1 + " and " + str2 + " are anagrams of each other."); } else { System.out.println(str1 + " and " + str2 + " are not anagrams of each other."); } } else { System.out.println(str1 + " and " + str2 + " are not anagrams of each other."); } }}

Output:

bored and robed are anagrams of each other.

In the above program, there are two strings i.e., str1 and str2. Here, we are comparing str1 and str2 to determine if they are anagrams. The strings are first converted to lowercase since Java is case-sensitive and B and b are two different characters in Java. Here,

  • str1.toCharArray(): Convert or transform the string into a char array.
  • Arrays.sort(): It sorts the char arrays.
  • Arrays.equals(): Checks or verifies if sorted char arrays are EQUAL.

In the case where sorted arrays are equal, the strings are anagrams.

6.

Is it possible to count the number of times a given character appears in a String?

Answer»

The charAt() method of the String class can be USED to find out the number of times a specified character appears in a string. Below is a Java program to check the occurrences of a specified character in a string.

public class CkeckforOccurences{ public static void main(String[] args) { String str= "InterviewBit"; char ch = 'e'; //character to look for occurrences is e INT COUNT = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { count++; } } System.out.println("The character '" + ch + "' appears " + count + " times in the given string '" + str + "'."); }}

OUTPUT

The character 'e' appears 2 times in the given string 'InterviewBit'.

As you can see, the above program checks how many times the character ch OCCURS in the string str. Whenever we encounter the character ch in the string, we increase the count by one. Finally, we print the total character count at the end.

7.

How to convert an Array to String in Java?

Answer»

An array can be CONVERTED to a string in four different ways such as Arrays.toString() method, String.Join() method, StringBuilder.append() method, and Collectors.joining() method. Here, we will see an example of the Array.toString() method. Arrays.toString() returns a string representation of the array contents. The string represents the array's elements as a list, enclosed in square brackets ("[]"). The characters ", " (a comma) FOLLOWED by a space are used to separate adjacent elements. It returns “null” if the array is null.

import java.util.Arrays;PUBLIC class ArrayToString { public static void main(String[] args) { String[] strArray = { "Scaler", "by", "InterviewBit"}; String str1 = ConvertArraytoString(strArray); System.out.println("An array converted to a string: " + str1); } // Using the Arrays.toString() method public static String ConvertArraytoString(String[] strArray) { return Arrays.toString(strArray); }}

Output:

An array converted to a string: [Scaler, by, InterviewBit]
8.

How to reverse a string in Java?

Answer»

There are different ways to reverse a STRING in Java-like using CharAt() method, StringBuilder/StringBuffer Class, Reverse Iteration, ETC. The reverse() method is AVAILABLE in both the StringBuilder and StringBuffer classes and is commonly used to reverse a string. The reverse () method simply reverses the order of the characters. Below is a Java program to reverse a string using the StringBuilder class.

public class ReverseString{ // function to reverse a string using StringBuilder public static String revstr(String str) { return new StringBuilder(str).reverse().toString(); } public static VOID main(String[] args) { String str= "Scaler by InterviewBit"; str= revstr(str); System.out.println("Result after reversing a string is: "+ str); }}

Output:

Result after reversing a string is: tiBweivretnI YB relacS
9.

Write a program to calculate the total number of characters in the String?

Answer»

To FIND the total count of characters in a specified STRING, we can use the for loop, while loop, or do while loop. Below is a Java program to calculate the total number of characters in a string using for loop.

public class TotatCharacters{ public static void main(String[] args) { String str = "Scaler by InterviewBit"; int count = 0; System.out.println("Input String: "+str); //Count total characters in the given string except space for(int i = 0; i < str.length(); i++) { if(str.charAt(i) != ' ') count++; } //Display total number of characters in the given string System.out.println("The total number of characters in the given string: " + count); } }

Output:

Input String: Scaler by InterviewBitThe total number of characters in the given string: 20
10.

How to print all permutations of string in Java?

Answer»

The TERM "permutation of the string" refers to all of the conceivable new strings that can be created by swapping the positions of the given string's characters. For example, the string CAT has a total of 6 permutations i.e., [CAT, CTA, ACT, ATC, TCA, TAC]. Below is a JAVA program to print all permutations of a given string.

public class InterviewBit { // Function to display all permutations of the string str static void printallPermutns(String str, String str2) { // check if string is empty or NULL if (str.length() == 0) { System.out.print(str2 + " "); return; } for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String str3 = str.substring(0, i) + str.substring(i + 1); // Recursive CALL printallPermutns(str3, str2 + ch); } } // Driver CODE public static void main(String[] args) { String s = "cat"; printallPermutns(s, ""); }}

Output: 

cat cta act atc tca tac
Previous Next