Java String Interview Questions
Java String Interview Questions
String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept. So, we should not ignore this section as it is important. In this section, we are going to enlist some important asked in Java String interview questions.
1) What are the differences between C, C++ strings and Java strings?
In C or C++, strings are not treated as objects. The C or C++ strings are terminated with the null character. However, Java strings are never terminated with the null character. Strings in Java are also treated as objects.
2) How are the strings stored in the memory?
The strings are stored in heap memory. The exact region where the strings are stored depends on their creation. If the strings are created using the new keyword, the strings are stored outside the string pool. If the strings are created using the string literals, the strings are stored inside the string pool.
3) Which one should be preferred, == operator or the equals() method to make a comparison between two string objects?
The equals() method should be preferred over the == operator, as the == operator only compares the references of the string objects, whereas the equals() method compares the content of the string objects.
4) What is the need for StringBuffer and StringBuilder classes when we have already got the String class?
In Java, the String class is always immutable. Therefore, any kind of modification in the objects of the String class leads to the creation of new objects, which lead to performance issue, as the creation of new objects consumes memory as well as time. To avoid the performance issue, the StringBuffer and StringBuilder classes were introduced in Java. Note that StringBuffer and StringBuilder classes create mutable objects.
5) Where the String pool is located in the memory?
The String pool is a portion of memory that is located inside the heap memory. It is used to store string literals.
6) How the substring() method works internally in Java?
The working of the substring() method varies if one moves from the JDK – 6 to JDK – 7. There was a major issue with the substring() method of the JDK – 6 version. It was found that there was a memory leak issue with the substring() method when dealt with the strings of the larger size. As Java strings are an array of characters, the substring() method for JDK – 6, shared the same characters of that string upon which the method is invoked. Consider the following code snippet.
String str = “Hello India”; // no new string object created String subStr = str.substring(0, 4); // Hell
Here, for the variable subStr, no new string is created, and the characters ‘H’, ‘e’, ‘l’, ‘l’ are shared between str and subStr. Thus, one can say both subStr and Str are holding the reference of the string “Hello India”. Now consider the following scenario.
String str = “Hello India”; String subStr = str.substring(0, 4); // Hell str = null; // object for Hello India is collected by garbage collector
After doing str = null, the string object for “Hello India” is not eligible for the garbage collection as subStr is also holding the reference. This leads to a memory leak if the string is of a larger size. For example, if a string is comprising of thousand characters and the substring is sharing only three characters, then the string object of the thousand characters cannot be deleted, as its three characters are shared. Thus, only for 3 characters, it is not correct to hold the memory of 1000 – 3 = 997 characters.
To resolve this issue, the working of the substring() method was modified in the JDK – 7. In JDK – 7, the substring() method does not share the characters. Instead of sharing the characters, a new string is created.
7) Predict the output of the following program with the explanation.
public class ABC { // main method public static void main(String argvs[]) { int j = 7; // \u000d j = 9; System.out.println("The value is : " + j); } }
Output:
The value is : 9
Explanation: At first glance, it seems that the value of j should be 7. However, the value is 9. The reason for the value 9 is the Java compiler. The compiler first parses the Unicode present in the code. Therefore, before any lexical translation \u000d is evaluated. The Unicode moves the following code in the next line. Thus, // \u000d j = 9; gets converted into the following.
// j = 9;
Now, when the lexical translation happens, the value of j gets updated to 9.
8) How many ways are there to create String objects?
There are three ways to create String objects.
1) By using a string literal.
String str = “Hello World”;
2) By passing string in the constructor of the String class.
String str = new String(“Hello Constructor”);
3) Using character array
Character arr[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’}; String str = new String(arr); // Hello World string is generated
9) Is it valid to use string literals in the Switch case?
It depends on the JDK version. From JDK 7, it is valid to use string literals in the Switch case. Before JDK 7, it was not possible to use a string literal in the Switch case.
10) Name the character encoding used in Java 9.
In Java 9, the UTF-8 character encoding is used by default. When JVM starts, System.getProperty(“file.encoding”, “UTF - 8”); gets called. UTF-8 is used as default when the file.encoding attribute is absent. However, this encoding can be changed by the programmer.
11) Why a Java programmer gives priority to the char[] instead of a string while storing a password?
The password of any user is a piece of very sensitive information. Therefore, security is the main concern while storing the password. As String is immutable in Java, therefore when string is used for storing the password, the password remains in the String pool for a long time for serving the purpose of reusability. Thus, there are high chances that it will remain in the memory for a longer period of time, which may lead to a security threat. Also, one cannot change the content of string as it will lead to the creation of a new string.
Using the char[] array, one can explicitly wipe the password content after the validation is complete. In other words, one can manipulate the char[] array data, but not the data present in a string, as strings are immutable in Java.
12) What is StringJoiner in Java?
The java.util package provides the StringJoiner class that is used to generate a sequence of characters or strings. The generated strings are separated by a delimiter. The StringJoiner class also provides the facility to add prefix and suffix to the string. Whatever we can achieve using the StringJoiner class can be achieved using the StringBuilder class using the append() method. However, the StringJoiner class makes the code less verbose. The StringJoiner class is introduced in Java 8 and is a final class.
13) Explain the concept of String intern.
The intern() method ensures that only one copy of a string value is present in the string pool. Therefore, the intern() method puts the string in the string pool. By default, the string literals are created in the string pool as they use the intern() method implicitly. However, to put strings created using the new keyword in the string pool, we have to use the intern() method explicitly.
String st1 = new String("Tutorial & Example"); // outside the string pool String st2 = new String("Tutorial & Example").intern(); // in the string pool String st3 = "Tutorial & Example"; // always in string pool
The intern() method returns the canonical representation of the string. When the intern() method is executed, a check is performed whether the string object is already present in the string pool or not. If it is present, its reference is returned; otherwise, a new string object is generated in the string pool.
14) Why key in a Java HashMap is usually a string?
String is usually used as a key in a Java HashMap because strings are immutable in Java. Thus, when the key of a Java HashMap is hashed, its value never changes in the case of a string, as the manipulation of string leads to the generation of a new string. Therefore, the hashed value can be cached to make the performance of the program better.
15) Explain the string subSequence() method.
The CharSequence interface declares the subSequence() method. As the String class implements the CharSequence interface, it has to define the subSequence() method. The subSequence() method internally calls the subString() method and returns a CharSequence.
16) Why is String final or immutable in Java?
Following are some of the reasons for the String to be final or immutable in Java:
- String literals are always stored in the String pool. Therefore, the String class has to be immutable. Without immutability, the String pool cannot exist.
- The Java classloader uses strings to load classes. The immutability of the strings ensures that the correct class is loaded.
- String immutability provides safety when it is used in the multithreading environment. We do not need to worry about synchronization because of the immutability.
17) Is autoboxing or unboxing possible in Java strings? Why?
No, autoboxing or unboxing is not possible in strings. Autoboxing and unboxing are the features of the wrapper classes. Java recognizes Boolean, Byte, Character, Float, Integer, Long, Short, and Double classes as the wrapper class. Therefore, neither autoboxing nor unboxing is possible in Java strings.
18) String objects are unique from the other objects of the derived types in Java. Why?
The creation of objects in the other derived classes is only possible using the new keyword (barring the wrapper classes). However, the String objects can be created without using the new keyword. One more unique feature about the String objects is that one can concatenate two String objects using the + operator. Such relaxation is not provided to the other derived class.
19) Explain the format() method of the Java String class. How is it different from the printf() method?
The format() method of the Java String class is used to format the string. The printf() method also formats the string. The main difference between the printf() method and the format() method is that the printf() method prints the formatted string, and the format() method returns the formatted string.
20) Observe the following statements and decide which one is better.
// statement - 1 st1.equals("Tutorial & Example"); // where st1 is a string type variable // statement - 2 "Tutorial & Example".equals(st1); // where st1 is a string type variable
In the above two statements, the second statement should be preferred over the first statement. We know that Strings are considered as objects in Java. Therefore, if the st1 is not initialized with any value, then the st1 contains the null value. Thus, the st1.equals(“Tutorial & Example”); gets translated to null.equals(“Tutorial & Example”); which results in the generation of NullPointerException.
The second statement does not face any issue. In case st1 becomes null, “Tutorial & Example”.equals(st1); gets converted into “Tutorial & Example”.equals(null); which does not give an exception and results in the false value. Thus, unlike the first statement, the second statement is not prone to any error or exception.
21) Consider a scenario in which we want to perform multiple string concatenation and modification. In such a case, which class should we use that improves the performance of the code and the code must be thread-safe?
We have three prominent classes in the field of strings. The String class, StringBuilder class, and the StringBuffer class.
The String class cannot be used as it is immutable. Thus, string concatenation or modification leads to the generation of new strings, which hampers the performance of the program. Hence, the String class cannot be used.
The StringBuffer class is mutable. Hence, one can perform the string concatenation of modification easily, without the creation of any new objects. Thus, the performance is improved. However, the StringBuffer class does not facilitate thread safety. Hence, the StringBuffer class also cannot be used in the given scenario.
The StringBuilder class is mutable. Hence, any manipulation operation does not generate a new object. Thus, this class also improves performance. The StringBuilder class provides the thread-safe facility. Therefore, the StringBuilder class is the most appropriate class that should be used in this scenario.
22) Explain how many objects are created when the below-mentioned two statements are executed simultaneously?
String st1 = new String("Tutorial & Example"); // statement - 1 String st2 = "Tutorial & example"; // statement - 2
It seems that only two objects are created: one for first statement, and another for second statement. However, the total number of objects created is three: two for first statement, and one for second statement. First, the object for the string literal "Tutorial & Example" is created in the string pool, then another object is created outside the string pool in the heap memory, as we have used a new keyword.
For the second statement, a string literal is used. Therefore, JVM (Java Virtual Machine) checks whether the literal is present in the string pool or not. It is found that the string literal is not present in the pool. It is because Java is a case-sensitive language, and example and Example words are treated differently. Hence, an object is created for the second statement also.
23) What is the fastest way to copy a String array?
The arraycopy( ) method can be used to copy quickly an array of any type from one place to another. It is much faster than the equivalent loop written out longhand in Java. Here is an example of two arrays being copied by the arraycopy( ) method. First, a is copied to b. Next, all of a’s elements are shifted down by one. Then, b is shifted up by one.
static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
static byte b[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 };
24) Is there any difference between == operator and equals() method?
The == operator checks for equality of reference variables and returns true if both point to the same object in memory.
The equals() method is a method that compares two Strings based on their content and returns true if they're equal.
25) Are Strings thread-safe?
In Java, every immutable object is thread-safe. Hence, String is also thread-safe. Java provides the StringBuffer class that is thread-safe while the StringBuilder class is not thread-safe because it is mutable and does not use the synchronized keyword.
26) How to count the number of vowels present in a string using recursion?
FileName: StringVowels.java
public class StringVowels { // Method to check for the vowels Boolean isVowel(char c) { // for small letters if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return true; } // for capital letters if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') { return true; } return false; } public int countVowels(String s1, int i, int size) { // handling base case if(i >= size) { return 0; } // getting character from the string char ch = s1.charAt(i); if(isVowel(ch)) { // vowel found! // increment the count by 1 and recursively // check for the rest of the string return 1 + countVowels(s1, i + 1, size); } // vowel not found! // do not increment the count by 1 and recursively // check for the rest of the string return countVowels(s1, i + 1, size); } // main method public static void main(String argvs[]) { // instantiating the class StringVowels StringVowels svObj = new StringVowels(); // input string String s1 = "Keep"; // calculating the size of the input string int size = s1.length(); // invoking the method countVowels() // storing the result int cntVowel = svObj.countVowels(s1, 0, size); // displaying the result System.out.println("String " + s1 + " has " + cntVowel + " vowels."); // another input string s1 = "Apple"; size = s1.length(); cntVowel = svObj.countVowels(s1, 0, size); System.out.println("String " + s1 + " has " + cntVowel + " vowels."); } }
Output:
String Keep has 2 vowels. String Apple has 2 vowels.
27) How to count the number of words present in a string?
FileName: StringWords.java
public class StringWords { // Method to count words of the string str public int countWords(String str) { // to store total // count of words int count = 0; // size of the string str int size = str.length(); for(int i = 0; i < size; i++) { // current character char ch = str.charAt(i); if(i > 0) { // previous character char prv = str.charAt(i - 1); // if the previous character // is a blank space and the current // character is not blank, a beginning of // new word is started. if(prv == ' ' && ch != ' ') { count = count + 1; } } if(i == 0) { // handling the scenario when there is no space on the // left side of the first word of the string if(ch != ' ') { count = count + 1; } } } return count; } // main method public static void main(String argvs[]) { // instantiating the class StringWords StringWords swObj = new StringWords(); // input string String s1 = "New Delhi the captial city of the country India."; // invoking the method countWords() // storing the result int cntWords = swObj.countWords(s1); char ch = '"'; // displaying the result System.out.println("The string " + ch + s1 + ch + " has " + cntWords + " words."); // another input string s1 = " Hello To Every One . "; cntWords = swObj.countWords(s1); System.out.println("The string " + ch + s1 + ch + " has " + cntWords + " words."); } }
Output:
The string "New Delhi the captial city of the country India." has 9 words. The string " Hello To Every One. " has 5 words.
28) Write a program in Java to find the percentage of lowercase, uppercase, digits, and other characters from the given string.
FileName: StringCharPercentage.java
public class StringCharPercentage { // A method to find the percentage of uppercase letters public int upperCaseCount(String str) { // calculating size of the string int size = str.length(); int count = 0; for(int i = 0; i < size; i++) { char c = str.charAt(i); if(Character.isUpperCase(c)) { count = count + 1; } } return count; } // A method to find the percentage of lowercase letters public int lowerCaseCount(String str) { // calculating size of the string int size = str.length(); int count = 0; for(int i = 0; i < size; i++) { char c = str.charAt(i); if(Character.isLowerCase(c)) { count = count + 1; } } return count; } // A method to find the percentage of digits letters public int digitCount(String str) { // calculating size of the string int size = str.length(); int count = 0; for(int i = 0; i < size; i++) { char c = str.charAt(i); if(Character.isDigit(c)) { count = count + 1; } } return count; } // A method to find the percentage of digits letters public void findPercentage(String str) { // length of the string is the // total number of characters present // in the string int totalChars = str.length(); // invoking upperCaseCount() method int countUpperCase = upperCaseCount(str); // invoking lowerCaseCount() method int countLowerCase = lowerCaseCount(str); // invoking digitCount() method int countDigit = digitCount(str); // other characters are all the characters that // are not uppercase or lowercase or digits int otherChars = totalChars - (countUpperCase + countLowerCase + countDigit); // calculating percentanges for each type of letters double percentUpperCase = (countUpperCase * 100) / totalChars; double percentLowerCase = (countLowerCase * 100) / totalChars; double percentDigit = (countDigit * 100) / totalChars; double percentOtherChars = (otherChars * 100) / totalChars; char ch = '"'; // displaying the results System.out.println("In the string " + ch + str + ch); System.out.println("Percentage of uppercase letters are: " + percentUpperCase); System.out.println("Percentage of lowercase letters are: " + percentLowerCase); System.out.println("Percentage of digits are: " + percentDigit); System.out.println("Percentage of other characters are: " + percentOtherChars); } // main method public static void main(String argvs[]) { // input string String s = "New Delhi is the capital city of the country India."; // creating an object of the class StringCharPercentage StringCharPercentage scObj = new StringCharPercentage(); // invoking the method findPercentage() scObj.findPercentage(s); System.out.println(); // new line s = "My $$ Passion 00 is %^ to play Cricket."; scObj.findPercentage(s); } }
Output:
In the string "New Delhi is the capital city of the country India." Percentage of uppercase letters are: 5.0 Percentage of lowercase letters are: 74.0 Percentage of digits are: 0.0 Percentage of other characters are: 19.0 In the string "My $$ Passion 00 is %^ to play Cricket." Percentage of uppercase letters are: 7.0 Percentage of lowercase letters are: 53.0 Percentage of digits are: 5.0 Percentage of other characters are: 33.0
29) Write a program in Java to find the permutation of the given string.
Permutation of the string can be achieved by the technique of backtracking. The following program shows the same.
FileName: StringPermute.java
public class StringPermute { // method for generate perumuatation of string str public void permute(char charArr[], int i, int size) { // handling base case if(i >= size) { // converting char array to str String str = String.valueOf(charArr); // printing the string System.out.println(str); return; } for(int j = i; j < size; j++) { // swap the characters char ch1 = charArr[i]; charArr[i] = charArr[j]; charArr[j] = ch1; // recursively find the permutation permute(charArr, i + 1, size); // swapping again to maintain the // previous order, which is called backtracking ch1 = charArr[i]; charArr[i] = charArr[j]; charArr[j] = ch1; } } // main method public static void main(String argvs[]) { // input string String str = "abc"; // calculating size of the input string int size = str.length(); // converting the string into char array char chrArr[] = str.toCharArray(); char ch = '"'; System.out.println("Permutations of the string " + ch + str + ch + " are: \n "); // creating an object of the StringPermute class StringPermute spObj = new StringPermute(); // invoking the method permute() spObj.permute(chrArr, 0, size); } }
Output:
Permutations of the string "abc" are: abc acb bac bca cba cab
30) Write a program in Java to find the minimum number of characters that must be added at the beginning of the given string to make it a palindrome.
It is one of the tricky questions that is frequently asked in interviews. The approach is to find the largest palindromic substring by removing the characters, one by one, from the end. The number of characters deleted is our answer. Let’s observe the following program for a better understanding.
FileName: StringPalindrome.java
public class StringPalindrome { // A method to check whether the string is a // palindrome or not public boolean isLargestPalindrome(String str) { int size = str.length(); for (int j = 0, i = size - 1; j <= i; j++, i--) { if (str.charAt(j) != str.charAt(i)) { return false; } } return true; } // main method public static void main(String[] args) { // input string String str = "BBBABABAA"; // for storing the number // of characters that has been deleted int count = 0; // to indicate when the largest palindrome is found boolean flag = false; // calculating the size of the input string int size = str.length(); // creating an object of the StringPalindrome class StringPalindrome spObj = new StringPalindrome(); while (size > 0) { // invoking the method isLargestPalindrome() // and storing the result boolean isPalin = spObj.isLargestPalindrome(str); if (isPalin) { // largest palindrome string found! // no need to proceed further flag = true; break; } else { // control reaching here means // one more character has to be deleted // hence, count needs to be incremented by 1 count = count + 1; // eliminate the last character of the string str = str.substring(0, size - 1); // updating the size size = str.length(); } } // displaying the number of // characters to be inserted at // the front end if (flag) { System.out.print("The number of characters to be inserted" + " to make the string palindrome are: " + count); } } }
Output:
The number of characters to be inserted to make the string palindrome are: 6