String Handling Interview Questions in Java

List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

String Handling Interview Questions in Java

Question 1.
What is String in Java? The string is a data type?
The string is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. The String class represents character strings. The string is used in almost all Java applications and there are some interesting facts we should know about String. The string is immutable and final in Java and JVM uses String Pool to store all the String objects. Some other interesting thing about String is the way we can instantiate a String object using double quotes and overloading the “+” operator for concatenation.

Question 2.
What are different ways to create String Object?
We can create a String object using a new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in the String class to get String from a char array, byte array, StringBuffer, and StringBuilder.

String str = new String(“abc”); 
String str1 = “abc”;

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with the same value. If found, it just returns the reference to that String object else it creates a new String object with a given value and stores it in the String pool.

When we use a new operator, JVM creates the String object but doesn’t store it in the String Pool. We can use the intern( ) method to store the String object into the String pool or return the reference if there is already a String with equal value present in the pool.

Question 3.
Write a method to check if the input String is Palindrome?
A String is said to be Palindrome if its value is the same when reversed. For example “aba” is a Palindrome String.
String class doesn’t provide any method to reverse the String but StringBuffer and StringBuilder class have a reverse method that we can use to check if String is palindrome or not.

private static boolean is palindrome(string str) {
if (str == null)
     return false;
     StringBuilder strBuilder = new stringBuilder(str);
     strBuilder. reverse( );
     return strBuilder.tostring( ).equals(str);

Sometimes interviewer asks not to use any other class to check this, in that case we can compare characters in the String from both ends to find out if it’s palindrome or not.

private static boolean isPalindromestring(String str) {
if (str == null)
      return false;
      int length = str.length( );
      System.out.println(length / 2);
for (int i = 0; i < length / 2; i++) {

      if (str.charAt(i) != str.charAt(length - i - 1))
      return false;
  return true;

Question 4.
Write a method that will remove the given character from the String?
We can use the replaceAll method to replace all the occurrences of a String with another String. The important point to note is that it accepts String as an argument, so we will use Character class to create String and use it to replace all the characters with empty String.

private static String remove char(string str, char c) {
   if (str == null)
           return null;
       return str.replaceAll(Character.toString(c) "");

Question 5.
How can we make String upper case or lower case?
We can use String class toUpperCase and toLowerCase methods to get the String in all upper case or lower case. These methods have a variant that accepts the Locale argument and uses that locale rules to convert String to upper or lower case.

Question 6.
What is the String subSequence method?
Java 1.4 introduced the CharSequence interface and String implements this interface, this is the only reason for the implementation of the subSequence method in the String class. Internally it invokes the String substring method.

Question 7.
How to compare two Strings in a java program?
Java String implements a Comparable interface and it has two variants of compareTo( ) methods.

compareTo(String another string) method compares the String object with the String argument passed lexicographically. If the String object precedes the argument passed, it returns a negative integer and if the String object follows the argument String passed, it returns a positive integer. It returns zero when both the String have the same value, in this case, the equals(String str) method will also return true.

compareToIgnoreCase(String str): This method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero thenequalsIgnoreCase(String str) will also return true.

Question 8.
How to convert String to char and vice versa?
This is a tricky question because String is a sequence of characters, so we can’t convert it to a single character. We can use the charAt method to get the character at the given index or we can use the toCharArrayOmethod to convert String to a character array. Check this post for a sample program on converting String to character array to String.

Question 9.
How to convert String to byte array and vice versa?
We can use the String get bytes( ) method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

Question 10.
Can we use String in the switch case?
This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier java versions don’t support this. If you are implementing conditional flow for Strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions.

Question 11.
Write a program to print all permutations of String?
This is a tricky question and we need to use recursion to find all the permutations of a String, for example, “AAB” permutations will be “AAB”, “ABA”, and “BAA”. We also need to use Set to make sure there are no duplicate values.

Question 12.
Write a function to find out the longest palindrome in a given string?
A String can contain palindrome strings in it and to find the longest palindrome in a given String is a programming question.

Question 13.
Difference between String, StringBuffer, and StringBuilder?
The string is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource-consuming, so java provides two utility classes for String manipulations — StringBuffer and StringBuilder.

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on the same String, we should use StringBuffer but in a single-threaded environment, we should use StringBuilder.

StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.

Question 14.
Why String is immutable or final in Java
There are several benefits of String because it’s immutable and final.

  • String Pool is possible because String is immutable in java.
  • It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password, etc.
  • Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.
  • Strings are used in java classloader and immutability provides security that the correct class is getting loaded by Classloader.

Question 15.
How to Split String in java?
We can use split(String regex) to split the String into String array based on the provided regular expression.

Question 16.
Why Char array is preferred over String for storing passwords?
The string is immutable in java and stored in the String pool. Once it’s created it stays in the pool until unless garbage is collected, so even though we are done with the password it’s available in memory for a longer duration and there is no way to avoid it. It’s a security risk because anyone having access to a memory dump can find the password as clear text.

If we use a char array to store passwords, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

Question 17.
How do you check if two Strings are equal in Java?
There are two ways to check if two Strings are equal or not — using the “==” operator or using the equals method. When we use the “==” operator, it checks for the value of the String as well as reference but in our programming, most of the time we are checking the equality of String for value only. So we should use the equals method to check if two Strings are equal or not.
There is another function equalsIgnoreCase that we can use to ignore the case.
String s1 = “abc”;
String s2 = “abc”;
String s3= new String(“abc”);
System.out.println(“s1 == s2 ? “+(s1==s2)); //true
System.out.println(“s1== s3 ? “+(s1=s3)); //false
System.out.println(“sl equals s3 ? “+(sl.equals(s3))); //true

Question 18.
What is String Pool?
As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.

Question 19.
What does the String intern( ) method do?
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool, and a reference to this String object is returned.
This method always returns a String that has the same contents as this string but is guaranteed to be from a pool of unique strings.

Question 20.
Does String is thread-safe in Java?
Strings are immutable, so we can’t change their value in the program. Hence it’s thread-safe and can be safely used in a multi-threaded environment.

Question 21.
Why String is a popular HashMap key in Java?
Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for a key in a Map and its processing are fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

Question 22.
What is the Contract between hashcode and equal method?
The Java superclass java. lang. The object has two very important methods defined.

public boolean equals(Object obj) 
public int hashcode( )

It is very important to understand the contract between equals and hashcode. The general contract of hashCode is:
Whenever the hashCode method is invoked on the same object more than once during the execution of the application, the hashCode method consistently returns the same integer value.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java. lang. Object)method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Question 23.
What is a Hash Code collision?
The idea of hashing is to store an element into the array at a position index computed as below.

  • obtain element_hash_code of the element by processing the element’s data and generating an integer value.
  • use a simple mod operation to map into the array’s range: index = hash(element) = abs(element_hash_code % array_capacity)

The hashcode collision occurs when the index calculated by hash function results same for two or more elements.

Question 24.
Why StringBuffer is called mutable?
The String class is considered immutable; so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to the Strings of characters then StringBuffer should be used.

Question 25.
What is the difference between StringBuffer and StringBuilder class?
Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.

Question 26.
Define immutable object?
An immutable object can’t be changed once it is created.

Question 27.
Explain the scenarios to choose between String, StringBuilder, and StringBuffer?

  • If the Object value will not change in a scenario use String Class because a String object is immutable.
  • If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized (means faster).
  • If the Object value may change and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread-safe (synchronized).

Question 28.
Difference between String, StringBuffer, and StringBuilder?

String StringBuffer StringBuilder
The string is an immutable class StringBuffer is a mutable class StringBuilder is a mutable class
The new object is created every time when modified No new object is created, modification is done in the existing one No new object is created, modification is done in the existing one
Syntax-string s1=”hello”; Syntax – StringBuffer sf=new StringBuffer(“hello”); Syntax – StringBuilder sb=new StringBuilder(“hello”);
StringBuffer methods are synchronized. StringBuilder methods are non-synchronized and added in JDK 5.
Use String if you require immutability Use StringBuffer in java if you need mutable + thread – safety. Use string builder in java if you require mutable + without thread safety.