1. What are the different ways to create string objects?
3.2.
2. Difference between String, StringBuffer, and StringBuilder in java
3.3.
3. Why is string made immutable in JAVA?
3.4.
4. How to compare two strings in java?
3.5.
5. How can you remove all the white spaces in a string?
3.6.
Java
3.7.
6. Explain String pool in Java?
3.8.
7. How many objects are created in the following code snippet?
3.9.
8. How many objects are created in the following code snippet?
3.10.
9. Difference between string in C and string in java.
3.11.
10. What does the string intern() method do?
3.12.
11. How can you split the string in java?
3.13.
12. Write a program to remove a given character from a string.
3.14.
13. Why string is not used for storing the passwords rather a char array is preferred for the same?
3.15.
14. Which object is popular as the HashMap key and why?
3.16.
15. How will you create an immutable class in java?
4.
Java String Interview Questions for Experienced
4.1.
16. Explain Character Encoding. What is the difference between UTF-8 and UTF-16?
4.2.
17. How does the substring() method fix memory leakage?
4.3.
18. Write a program to check whether the two given strings are anagrams.
4.4.
19. Write a program to print all permutations of String in Java.
4.5.
20. Write a program to swap two string variables without using a third variable in Java.
4.6.
Java
4.7.
21. What is StringTokenizer in Java?
4.8.
22. What is the String.format() method, and how is it different from concatenation?
4.9.
23. Explain the concept of string interning in Java. How can you manually intern a string?
4.10.
24. How does String immutability benefit Java?
4.11.
25. What is the significance of the String.intern() method, and how can it impact memory usage?
4.12.
26. How does the String.join() method work, and when is it used?
4.13.
27. How does Java implement the String.split() method internally? What are its limitations?
4.14.
28. How does the replace() method differ from replaceAll()?
4.15.
29. How does string deduplication work in Java, and when was it introduced?
4.16.
30. How does the CompactString feature in recent Java versions impact string memory usage?
5.
String Programming Questions
5.1.
31. Write a program in Java to reverse the order of words in a string without using the reverse() method.
5.2.
32. Suppose there is a code in which a lot of string modification and string concatenation is going on. Which class among StringBuffer, String, and StringBuilder, will improve the performance of the code, keeping thread-safety of the code in mind?
5.3.
33.Why is Java provided with String constant pool as we can store the objects in heap memory?
5.4.
34. How can a Java string be converted into a byte array?
5.5.
35.Write a code in Java to prove that String objects are immutable.
5.6.
36. What will be the output of the following code?
5.7.
37. What is the difference between s1.equals("book") and "book" .equals(s1) where s1 represents the object of a string?
5.8.
38. What will be the output of the following code?
5.9.
39. What will be the output of the following code?
6.
Java String MCQs
6.1.
1. Which of the following is true about Java strings?
6.2.
2. What is the output of the following code?
6.3.
3. Which method is used to compare the actual content of two strings?
6.4.
4. What is the default value of a String variable in Java?
6.5.
5. Which of the following methods can convert a String to a StringBuilder?
6.6.
6. What does the substring(int beginIndex, int endIndex) method return?
6.7.
7. Which method would you use to check if a string is empty?
6.8.
8. What will the following code return?
6.9.
9. Which of the following is used to convert a string to lowercase?
Java is the most popular programming language among developers. Even after new programming languages are developing, JAVA seems to get more widespread year on year. One of the reasons behind this is its platform independence. Programs can run on different computers as long as the Java runtime environment is installed.
This is the reason why JAVA is a favorite among interviewers. Sometimes, interviewers focus mainly on String Data Structure. But string interview questions are in itself so vast that you won't be able to focus on other concepts.
With the little time you had while preparing for your interviews, you can go through the string interview questions covered in this blog which can help you in your upcoming interviews.
The blog covers Intermediate and Advanced level string programming questions in java with answers so that you can have a clearer understanding.
What is String in Java?
A string in Java is a group of characters that is an instance of an object belonging to the java.lang class. The string class in Java is used to produce and edit strings. A string cannot have its value modified after it has been generated. In Java, strings are quite unique. Programmers can employ strings in accordance with the needs of their projects because they support a wide range of additional functionalities.
Now let's look at the most asked Java String Interview questions:
1. What are the different ways to create string objects?
String objects can be created in two ways:
Using the 'new' operator.
Using double-quotes.
Several constructors are also available in the String class to create strings from a char array, byte array, StringBuilder, and StringBuffer.
String S = new String("coding ninjas"); // using new operator.
String S = "coding ninjas"; // using double quotes.
When the String is created with the double quotes, JVM searches it for in the string pool; if the same value is found, it returns the reference to that String else creates a new object with the new value provided.
In the other case, if the String is created with the 'new' operator, then JVM creates a new object but not in the string pool. If we want to create the object in the string pool, we can use the intern() method.
2. Difference between String, StringBuffer, and StringBuilder in java
There are three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder.
String
StringBuffer
StringBuilder
String Pool serves as the storage area.
Heap Memory serves as the storage area.
Heap memory serves as the storage area.
Strings are Immutable
They are mutable
They are mutable
Strings are generally not used in the case of a threaded environment.
StringBuffer is suitable for multiple threads
StringBuilder is suitable for an environment with single threads
It is quite slow to work with a string
Speed of a StringBuffer is more than String and less than StringBuilder
StringBuilder is the fastest in performing operations.
3. Why is string made immutable in JAVA?
Immutable means unmodifiable or unchangeable.
Security is the major reason why strings in Java are made to be immutable. Strings in Java can be used to access data sources like files, databases, or even objects found across networks. Even sometimes, strings store passwords and usernames, which can't be modified once created.
4. How to compare two strings in java?
We can compare two strings using the equals() method. Another method is to use the '==' operator but try to avoid this method to compare two strings.
The reason behind this 'equals()' method compares the values of the two strings, whereas the '==' operator compares the reference in the memory.
5. How can you remove all the white spaces in a string?
Removal of white spaces in the String is termed as 'Squeezing.' Trimming from the left, right, and trimming the white spaces together combined in 'Squeezing.'
The Java Virtual Machine (JVM) stores string literals in the string pool to reduce memory use. In order to ensure that strings with the same content correspond to the same memory address and to minimise memory overhead, identical string literals are stored only once. This increases efficiency.
7. How many objects are created in the following code snippet?
Two objects are created in the above code snippet.
s1 String is created in the string constant pool as it is created by string literals.
s2 String is created in heap memory as it is created by the 'new' operator. No new object will be created in the string constant pool as it is already created by s1.
8.How many objects are created in the following code snippet?
String s1 = new String ("coding ninjas");
String s2 = new String ("coding ninjas");
Three objects will be created.
For string s1, two objects will be created, one in heap memory and the other in String constant pool.
For string s2, only one object will be created in heap memory, but no new object will be created in the string constant pool as the object with the same value is already present in the string constant pool.
9. Difference between string in C and string in java.
C string is a null-terminated character array whereas String in Java is an object.
String objects in java allow us to call various methods like substring(), toLowerCase(), length().
10. What does the string intern() method do?
When the intern method is invoked, if the String constant pool already contains a string equal to the String object as determined by the equals(Object) method, the String from the pool is returned.
Otherwise, the String object is added to the pool, and a reference to the String object is returned.
The task of the intern() method is to put String (which is passed to the intern method) into the string constant pool.
11. How can you split the string in java?
split() method of java.lang.String is used to split a comma-separated String. We can also use StringTokenizer to split the comma-separated String, but the split() method is easier and better to use as it returns an array of strings that we can further manipulate in the code.
12. Write a program to remove a given character from a string.
We can use the replaceAll() method to replace all the string occurrences in the given String. But here, a character is given as an argument. So, first, we have to convert this character into a string; then, by using the replaceAll() method, we can remove all the occurrences of the given character in the required String.
private static String removeChar(String S, char ch)
{
if (S == null)
{
return null;
}
return str.replaceAll(Character.toString(ch), "");
}
13. Why string is not used for storing the passwords rather a char array is preferred for the same?
String is immutable in Java and stored in the string constant pool. Once the string object is created, it is stored in the pool unless garbage is collected.
In the case of passwords, if String is used, it will be available in the memory for a longer duration. It will be a security risk as anyone with access to the memory dump can access the password.
On the other hand, if we use a char array for storing the passwords, we can set it to blank once we are done creating it. So we can control for how long the password will be available in the memory. That's why a char array is preferred for storing the passwords rather than String.
14. Which object is popular as the HashMap key and why?
String is the popular HashMap key. This is because String is immutable in Java. So, the hashcode of the String is cached every time it is created and doesn't need to be calculated again. This makes the processing faster than other HashMap keys.
15. How will you create an immutable class in java?
You can create an immutable class in Java by implementing the following points:
First, make the class as final such that the class cannot be further inherited.
Then, make all the data members private such that they will not be accessible from outside the class.
Do not provide setter methods for the variables.
Deep copy of objects should be performed in the getter methods.
Java String Interview Questions for Experienced
16. Explain Character Encoding. What is the difference between UTF-8 and UTF-16?
Encoding is the way to convert the data from one form to another.
Character encoding refers to the method when a character is represented in bytes.
UTF-8 uses 1 byte or 8 bits of memory to store the character, whereas UTF-16 uses 2 bytes or 16 bits of memory to store the character.
17. How does the substring() method fix memory leakage?
Substring shares the same character array as the String. If the original String is too large, it will lead to a memory leak, and sometimes it will not be retained.
Then, the original String will be retained by the substring as the size of the substring is smaller than the original String. It will further result in the prevention of large arrays being garbage collected.
18. Write a program to check whether the two given strings are anagrams.
Two strings are said to be anagrams if the two strings contain the same set of characters, but the order can be different.
For example: "coding" and "dincog" are anagrams. "ninjas" and "jasnni" are anagrams.
There are two approaches to solve this problem:
Approach 1: This approach involves sorting both the strings lexicographically and then comparing both strings. This approach will cost O(N * log(N) + M * log(M)) time where 'M' and 'N' represent the length of two strings.
Approach 2: This approach involves storing the frequencies of each character of the two strings and then comparing the occurrence of the characters in the two strings. This approach will cost O(N + M) time and O(26) space where 'N' and 'M' represent the length of the two strings.
For the code and algorithm, you can refer to the link - Anagrams.
19. Write a program to print all permutations of String in Java.
Let's say a given string is "abc" so all possible permutations of this string will be "abc", "acb", "bac", "bca", "cab", "cba". So in this question, we have to generate all the permutations of the characters in the given String.
There are two approaches to solve this problem:
Approach 1: This approach follows backtracking. In this, a character is made to be fixed at a position, and permutations of the rest of the characters will be computed. This approach will cost O(N! * log(N!)) time and O(N * N!) space.
Approach 2: This approach is way more optimized than Approach 1. In this approach, the first permutation will be the String sorted in increasing order, and the last permutation will be the String sorted in decreasing order. This approach will cost O(N * N!) time and O(N * N!) space.
20. Write a program to swap two string variables without using a third variable in Java.
Suppose we have two strings, String a = "Coding" and String b = "Ninjas." After swapping, the result should be a = "Ninjas" and b = "Coding."
For this we first concatenate string b to string a, So a = “CodingNinjas”. Now we will store the substring starting from index 0 and of length = a.length() - b.length() in string b. Now b = “Coding”.
Now store the substring from index = b.length() till the end of the String a in String a. After this, String a = "Ninjas."
You can refer to the below code snippet for the logic.
Java
Java
public class Solution { public static void main(String args[]) { String a = "Coding"; String b = "Ninjas"; System.out.println("Before swap: " + a + b); a = a + b; b = a.substring(0, a.length() - b.length()); a = a.substring(b.length()); System.out.println("After swap : " + a + b); } }
You can also try this code with Online Java Compiler
Before swap: CodingNinjas
After swap: NinjasCoding
Must Read: String Args in Java
21. What is StringTokenizer in Java?
To break the String into tokens, Java.util.StringTokenizer is used. StringTokenizer doesn't provide the facility to differentiate identifiers, quoted strings, and numbers like the StreamTokenizer class.
There are six useful methods of the StreamTokenizer class:
String nextToken() - This will return the next token from the StringTokenizer cobject.
Object nextElement() - This method is same as nextToken() but it will return an object.
boolean hasMoreTokens() - This method checks if there are more tokens available or not.
int countTokens() - This method returns the total number of tokens
String nextToken(String delim) - This method returns the next token based on the delimiter.
Boolean hasMoreElements() - This method is same as hasMoreTokens().
22. What is the String.format() method, and how is it different from concatenation?
String.format() allows formatted string creation using placeholders, similar to printf() in C. It's more flexible than concatenation because it supports data formatting (e.g., number padding, date formatting).
Example:
String result = String.format("The price is %.2f", 45.678);
// Output: The price is 45.68
It's preferred over concatenation when complex formatting is required.
23. Explain the concept of string interning in Java. How can you manually intern a string?
String interning is a method of storing only one copy of each distinct string value in memory. In Java, when you create a string literal, it's automatically interned. The String class maintains a pool of interned String objects.
This can save memory and allow for faster comparisons using == instead of .equals().
24. How does String immutability benefit Java?
String immutability in Java improves security, thread safety, and performance. Since strings cannot be changed, they can be cached, shared, and safely used across multiple threads without synchronization. It also ensures that the string's hashCode doesn't change, making strings a good choice for hash-based data structures like HashMap.
25. What is the significance of the String.intern() method, and how can it impact memory usage?
String.intern() adds the string to the string pool if it's not already there, or returns the canonical representation if it exists. This can save memory when you have many duplicate strings, as only one instance is stored in the pool.
However, overuse of intern() can lead to increased memory usage in the PermGen space (Java 7 and earlier) or the Metaspace (Java 8+), so it should be used judiciously.
26. How does the String.join() method work, and when is it used?
The String.join() method, introduced in Java 8, concatenates multiple strings or elements of a collection into a single string with a specified delimiter. It is used when you want to combine multiple values with a separator.
Example:
String result = String.join("-", "Java", "RxJS", "Angular");
// Output: Java-RxJS-Angular
27. How does Java implement the String.split() method internally? What are its limitations?
Internally, String.split() uses regular expressions to split the string. It creates a Pattern object from the given regex and then uses a Matcher to find matches.
Limitations include:
Performance overhead for complex regex patterns
Trailing empty strings are discarded by default
It returns the whole string if the delimiter is not found
For simple splits, using StringTokenizer or manual splitting might be more efficient.
28. How does the replace() method differ from replaceAll()?
replace(): Replaces all occurrences of a character or substring without using regular expressions.
replaceAll(): Replaces all occurrences of substrings that match a given regular expression.
Use replace() when you don't need regex capabilities for better performance.
29. How does string deduplication work in Java, and when was it introduced?
String deduplication was introduced in Java 8 Update 20 as part of G1 garbage collector optimizations. It aims to automatically identify and remove duplicate String objects from memory.
When enabled, the JVM periodically scans the heap for String objects that have identical character arrays. If found, it updates one String to point to the other's character array, allowing the duplicate to be garbage collected.
This feature is particularly useful for applications that maintain a large number of String objects with duplicate values.
30. How does the CompactString feature in recent Java versions impact string memory usage?
CompactString is a feature introduced in Java 9 to optimize the internal representation of String objects. It uses a byte[] instead of a char[] to store the string data when possible.
For strings that contain only Latin-1 characters (which can be represented in a single byte), this reduces the memory footprint by about 50%. The JVM automatically chooses the most efficient representation.
This feature is transparent to developers and doesn't require any code changes to benefit from it.
31. Write a program in Java to reverse the order of words in a string without using the reverse() method.
In this question, you will be given a string of space-separated words like "hey there hope you are having a good time." You have to reverse the order of words in the given String like "time good a having are you hope there hey."
The approach is to use an array to store the words of the String. Now traverse the array in the reverse direction and append the words again in the given String.
This approach will cost O(N) time and O(N) space, where 'N' denotes the length of the given String.
32. Suppose there is a code in which a lot of string modification and string concatenation is going on. Which class among StringBuffer, String, and StringBuilder, will improve the performance of the code, keeping thread-safety of the code in mind?
If we use the String class, because of its immutable nature, it will create a new object after every modification in the String, which will badly affect the performance of the code.
The StringBuilder class is not thread-safe because StringBuilder is not synchronized.
So, in this scenario, StringBuffer will give better performance.
33.Why is Java provided with String constant pool as we can store the objects in heap memory?
String constant pool provides the facility of reusability of the existing string objects. When a new string object is created using the string literals, then JVM first checks in the pool if this String already exists or not. If it exists, then it will reference the existing String rather than creating a new object. This will help in the speeding up of the application and also helps in saving the memory as no two objects will have the same content.
34. How can a Java string be converted into a byte array?
The getBytes() function of the string in Java allows you to choose the character encoding and converts a string into a byte array. Here's an example:
String text = "Hello, world!";
byte[] byteArray = text.getBytes("UTF-8"); // Convert to byte array using UTF-8 encoding
In this instance, the string is transformed into a byte array using the UTF-8 character encoding using the getBytes() method. Depending on your needs, you can substitute "UTF-8" with other recognised character encodings like "UTF-16". Remember that selecting a particular encoding is crucial to ensuring precise character-to-byte translation.
35.Write a code in Java to prove that String objects are immutable.
Generate two string objects using string literals, say s1 = "codingninjas" and s2 = "codingninjas." As string objects generated with string literals are stored in the string constant pool, any two objects can't have the same values. Therefore, both s1 and s2 will be pointing to the same object.
Then s1==s2 will return true.
Let’s just modify s1 by concatenating “article” as s1 = s1 + “article”. After this s2 = "codingninjasarticle". This statement will concatenate "article" to the object which s1 is pointing to and reassigns reference of that object back to s1.
Now, s1==s2 will give false output as s1 and s2 are now pointing to different objects in the pool as when we modified s1, a new object is created in the pool, and its reference is assigned to s1.
For clarification, refer to the below code snippet.
36. What will be the output of the following code?
public class Demo
{
public static void main(String[] args)
{
System.out.println('c' + 'o' + 'd' + 'e');
}
}
The output of the above code will be 411. The reason is the print statement has character literals in single quotes, so instead of concatenation, the corresponding ASCII value of each character is added, and the result is displayed as 411.
37. What is the difference between s1.equals("book") and "book" .equals(s1) where s1 represents the object of a string?
If the s1 value is "book", then both statements will return true. The difference arises when s1 will be a null value. In that case, s1.equals("book") will throw the null pointer exception, and on the other hand "book" .equals(s1) will return false.
38. What will be the output of the following code?
public class StringTest
{
public static void main(String[] args)
{
String s1 = new String("coding");
String s2 = new String("CODING");
System.out.println(s1 = s2);
}
}
The output of this code will be CODING because s2 will be assigned to s1. The confusion arises between '==' and '=' operators. That's why this question is a simple yet tricky one. You can learn more about Java code compiler here.
39.What will be the output of the following code?
String s1 = "coding";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));
The output of this code will be false as s2 is not of a type string.
Java String MCQs
1. Which of the following is true about Java strings?
The first type uses double quotes to construct string literals. The second type, produced by the new keyword, is string objects. Last but not least, Java 1.5 introduced the StringBuilder class for effective management of mutable character sequences known as string buffers.
What is the main purpose of strings in Java?
Strings in Java are mostly used to represent a group of characters. Java programming makes considerable use of string for text processing and data manipulation. They are an effective tool for Java developer because they are immutable, simple, and provide a wide range of methods for working with string.
How to solve a string problem in Java?
To solve a string problem in Java, you can utilize a variety of built-in methods like charAt(), substring(), or regular expressions. Alternatively, custom algorithms can be created for specific tasks like palindrome checks, pattern matching, or string manipulation.
Why strings are immutable in Java?
Strings are immutable in Java for several reasons. Immutability enhances security by preventing unauthorized modification of sensitive data. It also improves performance by enabling caching and optimization. Furthermore, it ensures thread safety, making strings safe to share across multiple threads in a concurrent environment. This immutability simplifies memory management and guarantees that once a string is created, its value remains unchanged.
Conclusion
This article discussed the String programming Interview Questions of Java from the intermediate to advanced level. You can practice the same String programming Interview Questions for Python as well. Once you are done with this, you can check out our Interview Preparation Course to level up your programming journey and get placed at your dream company.