Java String Interview Questions and Answers for 2024

String is the most widely used data type in many programming languages. If you are preparing for interviews, you must know string programming questions in java. In this article, we will see the most frequently asked java string interview questions. In this blog, we will also see string programs in java for interviews which will prepare you for interviews and you will have a better chance of cracking Java interviews.

  • 4.7 Rating
  • 60 Question(s)
  • 25 Mins of Read
  • 8479 Reader(s)

Beginner

String in general is a sequence of characters. For example, “upgrad” is a string which contains a sequence of characters ‘u’, ‘p’, ‘g’, ‘r’, ‘a’, and ‘d’. We use double quotes to represent a string in Java. For example, 

String str = “string programming interview questions in java”; 

Here, we defined string variable named str and the variable value is initialized as “string programming interview questions in java” 

In Java, String is an immutable object meaning once string object is created its value cannot be modified, it has lot of useful functions and it is present in java.lang package and we can import String in any class as below: 

import java.lang.String; 

String can be created in two different ways: 

  • Using String Literal – String objects created using string literal are stored in string constant pool. 
  • Using New Operator – String objects created using new operator are stored in heap memory. 

When we create a String using string literal, JVM looks into String pool to find if any existing String already created with the same value. If JVM finds similar string already exists in String pool, it does not create new String instead it points new String literal (or reference new literal) to existing string, in string pool, else if it does not find already existing string, it creates a new string in string pool and points new literal to it. 

When string is created using new operator it is not stored in string pool, instead it is created in Java Heap memory.  

  • String str1 = “Upgrad”;  //String literal 
  • String str2 = new String(“Upgrad”);//using new operator

This is a frequently asked question in Java string interview questions.  

An immutable class in Java is a class whose state of an object cannot be changed once it's created. Immutable objects are thread-safe and it is preferred to use an immutable object in a multithreaded environment. All the wrapper classes in Java are immutable, for example, Integer, Long, Short, Byte, Boolean, Float, and Double.

In Java, the string class is also immutable. We can make any custom class immutable by following certain rules. Immutable objects are final that means every time you want to change the state of an object you need to create a new object instead, as you cannot modify the state of immutable objects.

A mutable class in Java is a class whose objects are mutable meaning their state can be changed after they are created. If the state of an object can be changed or mutated after it has been created, it is called mutable object in java. In Java programming language String class is immutable, however Java.util.Date, StringBuffer and StringBuilder are mutable classes. 

We need to be very cautious using mutable objects in multithreading as they might produce unexpected results. In single-threaded programs it is recommended to use mutable objects like StringBuilder as they have better performance. In multi-threaded programs it is recommended to use String objects as they are immutable.

Expect to come across this popular question in String interview questions.  

This is another important string related interview question in java that you should know about. As we know immutable class is a class whose state cannot be modified once it is created. We need to follow certain steps to make the class immutable, as explained below: 

  • All the fields of a class should be declared final and private. 
  • Provide only getter methods to access the fields of class, no setter methods are to be provided. 
  • Restrict inheritance. Class must be declared as final so that child classes cannot be created. 
  • Provide public parameterized constructor to initialize all the values of fields at the time of object construction. 
  • Do not allow methods to modify any object. 
  • Do not allow this reference to escape during object creation, such as anonymous inner classes. 
  • If a mutable object is passed to the parameterized constructor, the immutable class should make a defensive copy of the mutable object before storing its references. 

Example:

public class StringProgram { 
 
    public static void main(String[args) { 
        ImmutableClass object = new ImmutableClass(1"upgrad"); 
        System.out.println("id: "+object.getId()); 
        System.out.println("name: "+object.getName()); 
    } 
} 
 
final class ImmutableClass { 
 
    private final int id; 
    private final String name; 
 
    public ImmutableClass(int idString name){ 
        this.id = id; 
        this.name = name; 
    } 
 
    public int getId() { 
        return id; 
    } 
 
    public String getName() { 
        return name; 
    } 
}  

Output: 

id: 1 
name: upgrad 

In Java programming language Strings are not a primitive data type. The primitive data types specify the size and type of variable, and has no additional methods. In Java primitive data types are byte, short, int, long, float, double, boolean, and char.

In Java programming language, string are objects. The String class is technically not a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. 

A must-know for anyone heading into a Java string interview, this question is frequently asked in String programs in Java for interview.  

String is immutable in Java, meaning once created, its value cannot be modified. 

For example, consider below; 

String str = "upgrad"; 
System.out.println(str.hashCode()); 
str += "courses"; 
System.out.println(str.hashCode()); 

In above code when we concatenate Str with another string “courses” JVM creates new string object in string pool as “upgradcourses” and points str to new object. Above code prints different hashcode for same str object which proves that JVM create new objects after concatenating String objects.

StringBuilder is fast and consumes less memory than a string while performing concatenations. Because StringBuilder is mutable we can append any number of string objects to the same StringBuilder object as its state is mutable. StringBuilder has the setLength() method, which can change the StringBuilder object to the specified length. However, String is immutable, its length is fixed.

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized, while StringBuilder operations are not thread-safe. We should use StringBuffer in a multi-threaded environment and use StringBuilderin a single-threaded environment. StringBuilder performance is faster than StringBuffer because of no overhead of synchronization.  

It is important to know the differences in String, StringBuilder, and StringBuffer interview questions in Java while preparing for interviews. 

A String can be used when immutability is required, or concatenation operation is not required. StringBuilder is mutable object which means we can modify StringBuilder object value. A StringBuilder can be used when a mutable string is needed without the performance overhead of constructing lots of strings along the way. 

If you are working in single threaded program, you can use StringBulder in multithreaded program String is preferred. String is also preferred as “key” in hashmap due to its immutability.

Both StringBuilder and StringBuffer objects are mutable which means their objects can be modified once created, the difference between StringBuilder and StringBuffer comes in terms of thread-safe. StringBuilder is not thread-safe, however, all methods of StringBuffer are thread-safe and defined with the “synchronized” keyword. If we are working in multithreaded environment, we should use StringBuffer else use StringBuilder.

It's no surprise that this one pops up often in String coding questions in Java.  

A string constant pool is a special place in the heap memory, which stores values of all the strings defined in the program. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.

On standard assignment of a value to a string variable, the variable is allocated in stack, while the value is stored in the heap in the string constant pool.

For example, when we create Strings as below it only creates one string object in the string constant pool and points both str1 and str2 to the same String “Hello”. 

String str1 = "Hello"; 
String str2 = "Hello"; 

A common question in String questions in Java, don't miss this one.  

a.  Comparing String using == operator:

Double equals operator is used to compare two objects. It compares references of two objects, if given objects “references” points to the same object, then it returns true else will return false. 

Example: 

String str1 = “upgrad”; 
String str2 = “upgrad”; 

As above two strings are created in String pool and both str1 and str2 points to same string  str1 == str2 returns true; 

However, consider below example: 

String str1 = new String(“upgrad”); 
String str2 = “upgrad”; 
String str1 = new String("upgrad"); 
String str2 = "upgrad"; 
System.out.println(str1 == str2); 

It will print false, as they are pointing to two different objects one in Java heap and another in string pool. 

b. Comparing String using equals function: 

String equals function compare two strings based on content of the string. If all the contents of given two strings are same, then it returns true. 

Example: 

String str1 = new String(“upgrad”); 

String str2 = “upgrad”; 

String str1 = new String("upgrad"); 
String str2 = "upgrad"; 
System.out.println(str1.equals(str2)); 

str1.equals(str2) will return true as both string contents are the same.

String equals function compares content of two strings and returns true (Boolean) only if two strings have same contents. If first verify if given two strings have the same reference if not it compares content of strings.

compareTo() function compares the two given strings lexicographically. Lexicographically means alphabetical order for example if number are to be treated as strings, then “4” is greater than “10”. 

compareTo function returns 0 if first string is equal to second string; a value less than 0 if first string is lexicographically less than second string argument; and a value greater than 0 if first string is lexicographically greater than second string argument. 

public class StringProgram { 
    public static void main(String[] args) { 
    String str1 = "upgrad"; 
    String str2 = new String("upgrad"); 
    System.out.println(str1.equals(str2)); 
 
    String str3 = "4"; 
    String str4 = "10"; 
    System.out.println(str3.compareTo(str4)); 
}} 

Output: 

true 
3 

A pool of strings, initially empty, is maintained privately by the class String. 

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.

Consider below example where we initialized two strings str1 using string literal and str2 using new keyword. When we compare these two strings using == operator it returns false as these two strings are created in different locations as shown in image, however, when we call str2.intern() it points str2 into existing string from string pool which str1 is pointing to. Hence after calling intern() method when we compare str1 and str2 string using == operator, it returns true.

Example: 

public class StringProgram { 
    public static void main(String[args) { 
        String str1 = "upgrad"; 
        String str2 = new String("upgrad"); 
        System.out.println(str1 == str2); 
        str2 = str2.intern(); 
        System.out.println(str1 == str2); 
    } 
}  

Output: 

false 
true 

Below are most widely used methods of String class: 

concat() 
length() 
replace() 
substring() 
toString() 
trim() 
toUpperCase() 
toLowerCase() 
equals() 
equalsIgnoreCase() 
charAt() 
isEmpty() 
toCharArray() 

toString() function is used to convert any object into string format. If we don’t override toString() function in our custom class then it will print object reference instead of printing attributes of a class. Even Object class has toString() method implemented.

To see use of toString() function please see below example:

public class StringProgram { 
 
    public static void main(String[args) { 
        Example object = new Example(); 
        object.setId(1); 
        object.setName("upgrad"); 
        System.out.println(object.toString()); 
    } 
} 
 
class Example { 
    private int id; 
    private String name; 
 
    public int getId() { 
        return id; 
    } 
 
    public void setId(int id) { 
        this.id = id; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name; 
    } 
 
    @Override 
    public String toString() { 
        return "Example{+ 
                "id=" id + 
                ", name='" name '\'+ 
                '}'; 
    } 
}  

Output: 

Example {id=1, name='upgrad'} 

Intermediate

One of the most frequently posed Java string programs for interview, be ready for it.  

Before Java 6 it was not possible to use string in switch case, however, from Java 7 or higher versions we can now use string in switch case statements. Java switch case String make code more readable by removing the multiple if-else chained conditions. 

Java switch case String is case sensitive, it uses equals() method to compare the passed value. 

Example: 

public class StringProgram { 
    public static void main(String[args) { 
        printMonth("Jan"); 
    } 
 
    static void printMonth(String month) { 
        switch (month) { 
            case "Jan": 
                System.out.println("January"); 
                break; 
            case "Feb": 
                System.out.println("February"); 
                break; 
            default: 
                System.out.println("Invalid Month"); 
        } 
    } 
} 

String split() function splits or breaks the given string based on the matches of the given regular expression. It returns array of string[] with string values which are split. 

We need to provide a regular expression which is the condition on which you want to break or split the given string. 

Let us see an example: 

public class StringProgram { 
    public static void main(String[] args) { 
        String str = "java string manipulation interview questions "; 
        String[] strings = str.split(" "); 
        for (int i = 0i < strings.lengthi++) { 
            System.out.println(strings[i]+" "); 
        } 
    } 
}  

Output: 

java  
string  
manipulation  
interview  
Questions 

A staple in questions on string in Java, be prepared to answer this one.  

Both statements compare string but there is an important difference in the above object comparison. In first statement str.equals(“upgrad”) if str is “upgrad” it will return true, and if str is null it will throw NullPointerException, whereas in the second statement “upgrad”.equals(str) if str is null it will return false.

Let us see an example: 

public class StringProgram { 
    public static void main(String[args) { 
        String str = "upgrad"; 
        System.out.println("upgrad".equals(str)); 
        System.out.println(str.equals("upgrad")); 
    } 
}  

Above two statements will print true. 

However, consider below example: 

public class StringProgram { 
    public static void main(String[args) { 
        String str = null; 
        System.out.println("upgrad".equals(str)); 
        System.out.println(str.equals("upgrad")); 
    } 
}  

In above case, first statement will return false whereas second statement will throw NullPointerException. This is one of tricky string related interview questions in java.  

+ operator is the only overloaded operator. You can use it for both adding two numbers as well as for string concatenation purposes. 

If you are using the Java version 1.5 or above, string concatenation internally uses the append() method of the StringBuilder. And for versions lower than 1.5, it uses the append() method of the StringBuffer class. 

Example: 

public class StringProgram { 
 
    public static void main(String[] args) { 
 
        String str1 = "java string "; 
        String str2 = "manipulation interview questions "; 
        String str3 = str1 + str2; 
        System.out.println(str3); 
    } 
} 

Output 

java string manipulation interview questions 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str1 = "upgrad"; 
        String str2 = "upgrad"; 
        String str3 = "upgrad"; 
    } 
}  

As String initialized using string literals are stored in string pool, any number of string variables having same string value will point to one same string in string pool. In above code only one string object is created in string constant pool.  

public class StringProgram { 
 
    public static void main(String[args) { 
        String str1 = new String("upgrad"); 
        String str2 = new String("upgrad"); 
        String str3 = "upgrad"; 
        String str4 = "upgrad"; 
    } 
} 

Above code will create three objects, two in heap area and one in the string constant pool. Because two string objects are created using new operator. The other two string str3 and str4 are created using string literal and have the same value, only one string object is created in string pool.  

This question is a regular feature in string interview program in Java, be ready to tackle it.  

To convert a string into stringbuilder, we can use constructor parameter of stringbuilder. We can pass string value to constructor of StringBuilder class to convert StringBuilder object. To convert stringbuilder to string we can use toString() method of string class. 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str1 = "string logical interview"; 
        String str2 = "questions in java"; 
        StringBuilder sb = new StringBuilder(); 
        sb.append(str1); 
        sb.append(" "+str2); 
        System.out.println(sb.toString()); 
    } 
}  

Output: 

string logical interview questions in java 

String class provide number of methods to replace character in string at different positions for example replaceFirst(), replace(), replaceAll(). An example can be seen below:

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "JAVA string programs examples with OUTPUT"; 
        System.out.println("String after removing 'a' : "+str.replace("a""")); 
        System.out.println("String after removing First 'a' : "+str.replaceFirst("e""")); 
        System.out.println("String after replacing all small letters : "+str.replaceAll("([a-z])""")); 
    } 
} 

Output: 

  • String after removing 'a' : JAVA string progrms exmples with OUTPUT 
  • String after removing First 'a' : JAVA string programs xamples with OUTPUT 
  • String after replacing all small letters : JAVA     OUTPUT 

This is a frequently asked question in Java string interview questions.  

Consider below program: 

public class StringProgram { 
    
   public static void main(String[] args) { 
        String str1 = "upgrad"; 
        String str2 = str1; 
        System.out.println(str1 == str2);     --- 1 
 
        str1 = str1 + "new"; 
        System.out.println(str1 == str2);      --- 2 
 
        StringBuilder sb1 = new StringBuilder("upgrad"); 
        StringBuilder sb2 = sb1;      -- 3 
        System.out.println(sb1 == sb2); 
        sb1.append("new"); 
        System.out.println(sb1 == sb2);    -- 4 
    } 
} 

Output: 

true 
false 
true 
true
  • In above program we initialized two string objects str1 and str2 using string literal.  
  • Initially both str1 and str2 points to same string object “upgrad” when we compare these two strings using == operator it returns true. 
  • We then modify string str1 by adding “new” string using + operator, this means str1 now becomes “upgradnew”. If Strings were mutable this modification should also reflect in str2, however, after this modification when we compare again str1 and str2 using == operator it returns false. This proves that string are immutable as str1 is modified with new string “upgardnew” and str2 still points to “upgrad” 
  • As we know StringBuilder are mutable objects, we perform the same operation on StringBuilder and initialze two objects as sb1 and sb2 both pointing to “upgrad”. 
  • Comparing sb1 and sb2 using == operator returns true. 
  • Now we append string “new” to sb1 stringbuilder object and compare again sb1 with sb2 using == operator, it returns true. This means due to the mutability property of stringbuilder change in sb1 reflected in sb2. 

To swap two strings without using third variable, we can make use of concatenation. 

  • First append str2 to str1.  
  • Substring str1 from 0 until length of str1 – str2.  assign it to str2 
  • Substring str1 from str2.length() until end of string, assign it to str1. 
public class StringProgram { 
 
    public static void main(String[] args) { 
        String str1 = "knowledge"; 
        String str2 = "hut"; 
 
        System.out.println("Before swapping"); 
        System.out.println("str1 = " + str1); 
        System.out.println("str2 = " + str2); 
 
        str1 = str1 + str2; 
        str2 = str1.substring(0(str1.length() - str2.length())); 
        str1 = str1.substring(str2.length()); 
 
        System.out.println("After swapping"); 
        System.out.println("str1 = " + str1); 
        System.out.println("str2 = " + str2); 
    } 
} 

Output: 

Before swapping 
str1 = knowledge 
str2 = hut 
After swapping 
str1 = hut 
str2 = knowledge 

Expect to come across this popular question in string questions in Java.  

A String object essentially is a sequence of characters. String class has a method called toCharArray() which converts given string into array of characters. There is also a function called charAt(index) which returns a character from a String for a given index. 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "upgrad"; 
        char[charArray = str.toCharArray(); 
        System.out.println(charArray.length); 
 
        for (int i = 0i < charArray.lengthi++) { 
            System.out.print(charArray[i]+" "); 
        } 
    } 
}  

Output: 

u p g r a d

A must-know for anyone heading into a Java string interview, this question is frequently asked in string interview questions.

To convert string into Integer (Int), Integer class has function called valueOf(String s) and parseInt(String s). These functions will throw NumberFormatException if given string is not numeric. 

To convert Integer into String, String class has function called valueOf(Integer i) and .toString(). 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "1234"; 
 
        //convert string to integer 
        Integer intVar1 = Integer.parseInt(str); 
        Integer intVar2 = Integer.valueOf(str); 
 
        //convert integer to string 
        String str1 = intVar1.toString(); 
        String str2 = String.valueOf(intVar2); 
 
        System.out.println(intVar1); 
        System.out.println(intVar1); 
         
        str = "upgrad"; 
        try{ 
            Integer val = Integer.valueOf(str); 
        }catch (Exception e){ 
            e.printStackTrace(); 
        } 
    } 
}  

Output: 

1234 
1234 
1234 
1234 
java.lang.NumberFormatException: For input string: "upgrad"  

The string class provides three overloaded function to convert string into byte array as mentioned below: 

  • getByte() - Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. 
  • getByte(String charsetName) - Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. This function throws UnSupportedEncodingException in case charsetName is invalid. 
  • getByte(Charset charset) - Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

Example: 

public class StringProgram { 
 
    public static void main(String[argsthrows UnsupportedEncodingException { 
        String str = "upgrad"; 
 
        System.out.println(str.getBytes()); 
        System.out.println(str.getBytes("ISO-8859-1")); 
        System.out.println(str.getBytes(StandardCharsets.UTF_8)); 
    } 
}  

Output: 

[B@626b2d4a 
[B@5e265ba4 
[B@36aa7bc2

String has many overloaded constructors to convert byte array into string object. 

This is very useful when you read file into byte array and then convert it into string object or when you have large objects to be returned as response to REST APIs we can send byte array and later convert it into string using different overloaded constructors of string class. 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "upgrad"; 
        byte[] bytes = str.getBytes(); 
        System.out.println(new String(bytes)); 
    } 
}  

Output: 

“upgrad”

It's no surprise that this one pops up often in string questions in Java.  

Substring is another important function of string class in Java. It is used to fetch subset of string object by providing index values. It has two overloaded functions as below: 

  • substring(int beginIndex) - Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. 
  • substring(int beginIndex, int endIndex) – Returns a string that is a substring of this string. The substring begins at the specified {beginIndex} and extends to the character at index {endIndex – 1}. 

Example:

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "upgrad knowledgehut"; 
        System.out.println(str.substring(7)); 
        System.out.println(str.substring(06)); 
    } 
}  

Output: 

Knowledgehut 
Upgrad 

In Java String.format() function has two overloaded implementations. This function formats returns a formatted string using the specified format string and arguments. You can specify the locale in String.format() method, if no locale is provided it uses Locale.getDefault() locale object.] 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "java string programs examples with output"; 
        String formatted = String.format("topic is - %s"str); 
        System.out.println(formatted); 
    } 
}  

Output:  

topic is - java string programs examples with output 

String class has implicit functions to convert given string into all lower case and all upper case. 

.toLowerCase() - Converts all of the characters in this String to lower case using the rules of the default locale. This is equivalent to calling toLowerCase(Locale.getDefault() 

.toUpperCase() - Converts all of the characters in this String to upper case using the rules of the given Locale. Case mapping is based on the Unicode Standard version specified by the Character class. 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        String title = "UpGrad"; 
        System.out.println(title.toLowerCase()); 
        System.out.println(title.toUpperCase()); 
    } 
}  

Output: 

upgrad 
UPGRAD 

StringJoiner is a new class added in Java 8. StringJoiner is used to construct a sequence of characters separated by delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. 

Example: 

public class StringProgram { 
 
    public static void main(String[args) { 
        StringJoiner strJoiner = new StringJoiner(",""[""]"); 
        strJoiner.add("upgrad"); 
        strJoiner.add("knowledge"); 
        strJoiner.add("hut"); 
        System.out.println(strJoiner); 
    } 
}  

Output: 

[upgrad,knowledge,hut] 

A StringJoiner can also be usedto create formatted output from a Stream using Collectors.joining(CharSequence).  

Example: 

public class StringProgram { 
 
    public static void main(String[] args) { 
        List<Integer> numbers = Arrays.asList(1234); 
        String commaSeparatedNumbers = numbers.stream() 
                .map(i -> i.toString()) 
                .collect(Collectors.joining(", ")); 
 
        System.out.println(commaSeparatedNumbers); 
   } 
} 

Output: 

1, 2, 3, 4 

A common question in string coding questions in Java, don't miss this one.  

A string class provides function called isEmpty() to check if the given string is empty or not. isEmpty() function basically checks length of string, if string length is 0 it means string is empty if string length is greater than zero, it returns false.

Example:

public class StringProgram { 
 
    public static void main(String[args) { 
        String str1 = ""; 
        System.out.println(str1.isEmpty()); 
         
        String str2 = " "; 
        System.out.println(str2.isEmpty()); 
    } 
}  

Output: 

true 
false 

This is a frequently asked question in Java string interview questions.  

String class internally uses a character array to store the characters. String has function called .length() which returns the length of this string. The length is equal to the number of Unicode code units in the string. 

Example:

public class StringProgram { 
    public static void main(String[args) { 
        String str = "core java string interview questions"; 
        System.out.println(str.length()); 
   } 
}

Output:  

36 

Advanced

Expect to come across this popular question in string questions in Java.  

In Java String objects are immutable for multiple reasons: 

  • Immutable Strings are thread safe; it is safe to use String in multithreaded environment without Synchronizing. 
  • As String values can’t be changed once created, hackers won’t be able to change its values for example, username, password etc. 
  • Immutable makes it easy to use String constant pool, if Strings were mutable then we won’t be able to make use of String constant pool. 
  • Strings are used in Java class loaders; immutability provides assurance that the correct class is loaded by the Java ClassLoader class.

A must-know for anyone heading into a Java string interview, this question is frequently asked in string interview questions.  

A map is a collection in Java that stores key value pairs. The keys of this must not be null and each key should be unique and point to only one value. It is represented by the Map interface of java.util package. There are various classes that provide implementation to this interface. 

While storing data in a hashmap a hashcode of key is calculated, and its value is stored at the position represented by the hashcode. Similarly, while fetching the data from the hashmap, the hashcode is again calculated on provided key, and the value in the position represented by the code is returned. So, whether you are adding an object or retrieving an object from hashmap you need to calculate its hashcode.

As strings are immutable, the advantage is that, its hashcode always remains same. As string hashcode remains same hashcode  value is cached, and no need to calculate the hashcode again while retrieving objects from hashmap.  

It's no surprise that this one pops up often in string questions in Java.  

Since Strings are immutable, if you store the password as plain text, it will be available in memory until the Garbage collector clears it. Since String is used in the String pool for reusability there is a pretty high chance that it will remain in memory for a long duration, which poses a security threat.

Anyone who has access to memory dump can find the password in clear text and that is another reason you should always use an encryptedpassword instead of plain text. Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce new String. As array data can be easily wiped off by overwriting array values with something different. And array even after printed by mistakenly in code will not real the content that it stored instead prints object reference.

It will print false. Because str1 and sb objects are of different types. If you look at the equals method implementation in the String class, you will find a check using instance of operator to check if the type of passed object is String? If not, then return false.

It will print true. As intern() method will return the String object reference from the string pool since we assign it back to str2 hence both str1 and str2 are having the same reference. It means that str1 and str2 references point to the same object.

StringTokenizer class is used to break a string into tokens. It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens.

public class StringProgram { 
 
    public static void main(String[args) { 
        StringTokenizer st = new StringTokenizer("string handling interview questions in java"," "); 
        while (st.hasMoreTokens()) { 
            System.out.print(st.nextToken()+" "); 
        } 
    } 
}  

Output: 

string handling interview questions in java 

Any character that we type using keyboard, the character encoding maps characters you typed to specific bytes in computer memory in binary format. In order to display the text, it reads the bytes back into characters using character encoding.

There are many character sets and character encodings available in the world. UTF-8 and UTF-16 are examples of character encoding. It describes how characters are mapped to bytes. UTF stands for Unicode Transformation Format. UTF-8 uses a minimum of one byte to represent a character while UTF-16 uses a minimum of two bytes to represent a character. 

Text blocks are introduced from Java 15 to declare the multi-line string literals without much difficulty. Text blocks are enclosed within “”” (three double quote marks). Text blocks are treated as string objects. It helps in making code more readable when you have large strings initialized in programs. 

public class StringProgram { 
 
    public static void main(String[] args) { 
        String str = """ 
                        java string 
                        program interview  
                       questions and answers 
                     """; 
        System.out.println(str); 
    } 
} 

Output: 

java string 
program interview 
questions and answers 

isBlank(), lines(), repeat(), strip(), stripLeading() and stripTrailing() are the new methods introduced to String class after Java 11. 

Example:  

public class StringProgram { 
 
    public static void main(String[] args) { 
        String str1 = """ 
                        java string 
                        program interview  
                       questions and answers 
                     """; 
        String str2 = "  upgrad  "; 
 
        System.out.println("isBlank():: "+str1.isBlank()); 
        System.out.println("********"); 
        System.out.println("lines()"); 
        str1.lines().forEach(s -> System.out.println(s)); 
        System.out.println("********"); 
 
        System.out.println("repeat():: "+str2.repeat(2)); 
        System.out.println("stripLeading():: "+str2.stripLeading()); 
        System.out.println("stripTrailing():: "+str2.stripTrailing()); 
    } 
} 

Output 

isBlank():: false 
******** 
lines() 
   java string 
   program interview 
   questions and answers 
******** 
repeat()::   upgrad    upgrad   
stripLeading():: upgrad   
stripTrailing()::   upgrad 

Iterate the string in for loop. It throws StringIndexOutOfBoundsException when we reach end of string. The below example gives more details:

public class StringProgram { 
 
    public static void main(String[args) { 
        System.out.println(StringProgram.length("string handling interview questions in java")); 
    } 
 
    static int length(String s) { 
        int i=0count=0; 
        try { 
            for(i=0,count=0;0<=i;i++,count++) 
                s.charAt(i); 
        catch(StringIndexOutOfBoundsException e) { 
//            e.printStackTrace(); 
        } 
        return count; 
    } 
}  

Output: 

43 

A common question in Java string interview questions, don't miss this one.  

To reverse given string, convert the string into a character array and iterate character array from end to start. Read each character in reverse order and append it to new StringBuilder object. At the end convert StringBuilder object into String using toString() function and return result.

public class ReverseString { 
 
    public static void main(String[args) { 
        String str = "string related interview questions in java"; 
 
        System.out.println(reverseString(str)); 
    } 
 
    private static String reverseString(String str) { 
 
        char[] chars = str.toCharArray(); 
        StringBuilder result = new StringBuilder(); 
        for (int i = chars.length 1i >= 0i--) { 
            result.append(chars[i]); 
        } 
        return result.toString(); 
    } 
}  

Output: 

avaj ni snoitseuq weivretni detaler gnirts

There are multiple ways you can reverse words in string. One of the approaches is to split the string using string’s split() function on space, which returns array of string. Now you can read the array from end to start and append words in reverse order. 

  • Time complexity of program: O(N)  
  • Auxiliary Space Complexity: O(N) 
public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "string coding interview questions in java"; 
 
        System.out.println(reverseWords(str)); 
    } 
 
    private static String reverseWords(String str) { 
 
        String[stringArray = str.split(" "); 
        StringBuilder sb = new StringBuilder(); 
        for (int i = stringArray.length ; i >= 0i--) { 
            sb.append(stringArray[i]).append(" "); 
        } 
 
        String result = sb.toString(); 
        return result.substring(0result.length() - 1); 
    } 
}  

Output: 

java in questions interview coding string 

One of the most frequently posed string coding questions in Java, be ready for it.  

To check whether given string is palindrome or not, use two pointers one at the start and another at the end of string, compare each character and increase and decrease indices respectively comparing each character. Compare until start pointer meets end pointer at the middle of string.  If any of the character does not match then string is not a palindrome. 

  • Time complexity of program: O(N)  
  • Auxiliary Space Complexity: O(N)
public class StringProgram { 
 
    public static void main(String[args) { 
        String str1 = "UpGraDargpu"; 
        String str2 = "upgrad"; 
 
        System.out.println(checkPalindrome(str1)); 
        System.out.println(checkPalindrome(str2)); 
    } 
 
    private static boolean checkPalindrome(String input) { 
        String str = input.toLowerCase(); 
        boolean isPalindrome = true; 
        for (int i = 0j = str.length()-1i < ji++j--) { 
            if(str.charAt(i) != str.charAt(j)){ 
                isPalindrome = false; 
                break; 
            } 
        } 
        return isPalindrome; 
    } 
}  

Output: 

true 
false 

A staple in string programming interview questions in Java, be prepared to answer this one.  

A string is called anagram if it contains same set of characters but in a different order for example “silent” and “listen” are anagram as both contain exact same characters although they are in different order. 

Follow below steps to check if given two strings are anagram or not: 

  1. Convert both strings into lowercase. 
  2. Check if both strings have same length or not, if not return false; 
  3. Initialize HashMap<Character, Integer> with key as character and value as count of character. 
  4. Iterate through first string and add count = 1 for each character. 
  5. Then iterate through second string and do minus one from HashMap for existing characters in HashMap. If character in second string does not exists in HashMap it means strings are not anagram and return false. 
  6. Finally iterate through keys set of HashMap and check if all character count is zero or not, if not then strings are not anagram. Else Given strings are anagram. 
public class StringProgram { 
 
    public static void main(String[args) { 
        String str1 = "listen"; 
        String str2 = "silent"; 
 
        System.out.println(checkAnagram(str1str2)); 
    } 
 
    private static boolean checkAnagram(String str1String str2) { 
 
        str1 = str1.toLowerCase(); 
        str2 = str2.toLowerCase(); 
 
        //if number of characters are different return false 
        if(str1.length() != str2.length()) { 
            return false; 
        } 
 
        // Create a HashMap to store character as Key and count of character as Value. 
        Map<CharacterInteger> map = new HashMap<>(); 
        // Loop over all character of first String and put in HashMap 
        for (int i = 0i < str1.length()i++) { 
            // Check if HashMap already contain current character  
            if (map.containsKey(str1.charAt(i))) { 
                // If contains increase count by 1 for that character 
                map.put(str1.charAt(i)map.get(str1.charAt(i)) + 1); 
            } 
            else { 
                // else put that character in HashMap and set count to 1  
                map.put(str1.charAt(i)1); 
            } 
        } 
        // Now loop over second String 
        for (int i = 0i < str2.length()i++) { 
            // Check if current character already exists in HashMap 
            if (map.containsKey(str2.charAt(i))) { 
                // If yes reduce the count of that character by 1 to indicate that current character has been already counted 
                // idea here is to check if in last count of all characters is zero which means all characters  
                // in String str1 are present in String str2. 
                map.put(str2.charAt(i), 
                        map.get(str2.charAt(i)) - 1); 
            } 
            else // if current character does not exists in HashMap return false 
                return false; 
            } 
        } 
        // Extract all keys of HashMap 
        Set<Character> keys = map.keySet(); 
        // Loop over all keys and check if all keys are 0. 
        // If so it means it is anagram. 
        for (Character key : keys) { 
            if (map.get(key) !0) { 
                return false; 
            } 
        } 
        // Returning True as all keys are zero 
        return true; 
    } 
}  

Output: 

true 

To check if string is numeric or not, we can use parseDouble() method of Double class to convert string to double number. If it doesn’t throw NumberFormatException it means given string is numeric else if it throws NumberFormatException that means the given string is non-numeric.

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "9999.99"; 
        boolean isNumeric = true; 
 
        try { 
            Double num = Double.parseDouble(str); 
        catch (NumberFormatException e) { 
            isNumeric = false; 
        } 
 
        if (isNumeric) 
            System.out.println(str + " is a number"); 
        else 
            System.out.println(str + " is not a number"); 
    } 
}  

Output: 

9999.99 is a number 

We can easily count occurrence of given character in a string using java 8 count() operator. We create a stream of characters from given string using str.chars() function. After that add a filter function to filter out only given character from string. At the end call count() function (Java stream’s terminal operator) which will return count of given character.

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "Java"; 
        System.out.println(countCharacter(str'a')); 
    } 
 
    private static long countCharacter(String str, char chr) { 
        return str.chars().filter(ch -> (char)ch == chr).count(); 
    } 
}  

Output: 

2 

This question is a regular feature in string interview questions, be ready to tackle it.  

We need to count how many times each character occurs in a given string, for example, aabccdddd should return below output: 

  • a occur: 2 time(s) 
  • b occur: 1 time(s) 
  • c occur: 2 time(s) 
  • d occur: 4 time(s) 

To count number of occurrences of each character in a string we can use Map data structure. Map store data in key-value pair. In the program below, we have used LinkedHashMap (which helps maintain the order of elements). Key in our case is a character and the value is count of each character.

Read each character of string using .charAt() function. Add character to map, before adding check if character already exists in map if not just add the character with count = 1, else if character already exists get count of that character from map and add one. 

At the end we will have a map with each character and its corresponding count from given string. 

public class StringProgram { 
 
    public static void main(String[args) { 
        String str = "xxyyzzz"; 
        countCharacter(str); 
    } 
 
    private static void countCharacter(String str) { 
 
        Map<CharacterInteger> map = new LinkedHashMap<>(); 
        for (int i = 0i < str.length()i++) { 
            char key = str.charAt(i); 
            if(map.containsKey(key)) { 
                map.put(keymap.get(key)+1); 
            else { 
                map.put(key1); 
            } 
        } 
 
        for (Character ch : map.keySet()) { 
            System.out.print(ch+" occur: " +map.get(ch) + " time(s)\n"); 
        } 
    } 
}  

Output: 

x occur: 2 time(s) 
y occur: 2 time(s) 
z occur: 3 time(s)

We can use java.util.Random class to generate random string from set of characters A-Z and numbers 0-9 . First, we initialize a String with all characters and numbers. Then use the Random class to get a random character from the initialized String and append that random character to a new String. Do this in for loop until the size of the Random string (16 characters).

public class StringProgram { 
 
    public static void main(String[args) { 
        System.out.println(generateRandomString(16)); 
    } 
 
    private static String generateRandomString(int size) { 
        String characterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 
        StringBuilder sb = new StringBuilder(); 
        Random rnd = new Random(); 
        while (sb.length() < size) // length of the random string. 
            int index = (int) (rnd.nextFloat() * characterSet.length()); 
            sb.append(characterSet.charAt(index)); 
        } 
        return sb.toString(); 
    } 
}  

Output: 

CHR111AEKN9599QK 

To find first unique character in string, convert the string into character array. Initialize character array of 256 size. Increase count of each character from string into character array, then iterate character array and find first character with count = 1. 

For example: 

If string str = “java string interview questions java” we want to find first unique (non-repeating) character from string. In above string character ‘g’ is first unique character whose index is 10. (All characters before ‘g’ appear more than once). 

public class StringProgram { 
 
    static final int NO_OF_CHARS 256; 
    static char count[] = new char[NO_OF_CHARS]; 
 
    public static void main(String[args) { 
        System.out.println(firstNonRepeating("java string interview questions java")); 
    } 
 
 
    /* calculate count of characters in the passed string */ 
    static void getCharCountArray(String str) { 
        for (int i = 0i < str.length()i++) 
            count[str.charAt(i)]++; 
    } 
 
    /* The method returns index of first unique character in a string. If all characters are 
       repeating then returns -1 */ 
    static int firstNonRepeating(String str) { 
        getCharCountArray(str); 
        int index = -1i; 
 
        for (i = 0i < str.length()i++) { 
            if (count[str.charAt(i)] == 1) { 
                index = i; 
                break; 
            } 
        } 
        return index; 
    } 
}  

Output: 

10

You can sort string by converting it into character array, then sort character array using Arrays.sort() function. Then convert character array back into string using string’s valueOf() function. 

As we are using sort function from Arrays java.util class, it uses quick sort algorithm internally to sort given array.

Time Complexity: O(N log(N)) 

public class StringProgram { 
 
    static final int NO_OF_CHARS 256; 
    static char count[] = new char[NO_OF_CHARS]; 
 
    public static void main(String[args) { 
        System.out.println(sortString("knowledgehut")); 
    } 
 
    private static String sortString(String str) { 
        char []arr = str.toCharArray(); 
        Arrays.sort(arr); 
        return String.valueOf(arr); 
    } 
}  

Output: 

deeghklnotuw 

We can use recursion to print all permutation of a string. Follow below steps to print permutations of a string: 

  • Create a function with first argument as original string and second argument that stores the permutation (initially second string is empty). 
  • If length of first string is 0, print the permutation. 
  • Else run a loop from 0 to length of string 
    • Take str.charAt(i), to be part of permutation 
    • Remove this character from the current string and append it to the end of the permutation. 
    • Call the recursive function with the current string which does not contain  

str.charAt(i) and the current permutation. 

public class StringProgram { 
 
    static final int NO_OF_CHARS 256; 
    static char count[] = new char[NO_OF_CHARS]; 
 
    public static void main(String[args) { 
        printPermutation("abc"""); 
    } 
 
    private static void printPermutation(String strString result) { 
 
        // If string is empty 
        if (str.length() == 0) { 
            System.out.print(result + " "); 
            return; 
        } 
 
        for (int i = 0i < str.length()i++) { 
            char ch = str.charAt(i); 
            String subString = str.substring(0i) + str.substring(i + 1); 
            printPermutation(subStringresult + ch); 
        } 
    } 
}  

Output: 

abc acb bac bca cab cba 

This is a frequently asked question in Java string interview questions.  

We can use Stack data structure. A Stack data structure stores the elements in Last In First Out (LIFO) order as oppose to Queue which stores elements in First In First Out (FIFO) order.

To solve this problem, add open parenthesis onto stack and verify corresponding closing parenthesis from string by poping elements from stack.

public class StringProgram { 
 
    public static void main(String[args) { 
        System.out.println(isBalancedParenthesis("[[{(())}]]")); 
    } 
 
    public static boolean isBalancedParenthesis(String input) { 
        if ((input.length() % 2) == 1return false; 
        else { 
            Stack<Character> s = new Stack<>(); 
            for (char bracket : input.toCharArray()) 
                switch (bracket) { 
                    case '{'s.push('}'); break; 
                    case '('s.push(')'); break; 
                    case '['s.push(']'); break; 
                    default : 
                        if (s.isEmpty() || bracket !s.peek()) return false;} 
                        s.pop(); 
                } 
            return s.isEmpty(); 
        } 
    } 
}  

Output:

true

Iterate string until end of string using length() function. Check each character from string using .charAt() function and check if its uppercase, lowercase, special character or numeric and increase respective count.

public class StringProgram { 
 
    public static void main(String[args) { 
        countCharacters("UpgradKnowledge#Hut@2023"); 
    } 
     
    public static void countCharacters(String str) { 
        int upper = 0lower = 0number = 0special = 0; 
 
        for(int i = 0i < str.length()i++) { 
            char ch = str.charAt(i); 
            if (ch >= 'A' && ch <= 'Z') 
                upper++; 
            else if (ch >= 'a' && ch <= 'z') 
                lower++; 
            else if (ch >= '0' && ch <= '9') 
                number++; 
            else 
                special++; 
        } 
 
        System.out.println("Upper case letters : " + upper); 
        System.out.println("Lower case letters : " + lower); 
        System.out.println("Special characters : " + special); 
        System.out.println("Numbers : " + number); 
    } 
}  

Output: 

  • Upper case letters : 3 
  • Lower case letters : 15 
  • Special characters : 2 
  • Numbers : 4 

To remove spaces from a string we can use replaceAll() function of string class and use regex to replace space. 

public class StringProgram { 
 
    public static void main(String[args) { 
        System.out.println(removeSpace(Upgrad   Knowledge  Hut    ")); 
    } 
 
    public static String removeSpace(String str) { 
        str = str.replaceAll("\\s",""); 
        return str; 
    } 
}   

Output: 

UpgradKnowledgeHut

Given an array of words and a string, we need to count all words that are present in given string.  

Examples: 

Input : words[] = { "upgrad", "question", “answer”, “courses”, “knowledge”} 

            str = "upgrad has very good training courses for students to prepare for java string program interview questions and answers" 

Output :  4 

Two words "upgrad", “question”, “answer” and "courses" is present in str. 

In this program we need to check (count) how many times the words present in array exists in given string str. 

We can make use of String’s contains() function to do this. Simply iterate through each word from array and check if word contains() in given string. If it exists increase count by one. 

Finally count will have number of times words from array exists in given string. 

public class StringProgram { 
 
    public static void main(String[args) { 
 
        String str = "upgrad has very good training courses for students to prepare for java string program interview questions and answers"; 
        String[] words = { "upgrad""question""answer""courses"}; 
 
        System.out.println(countWords(strwords)); 
    } 
     
    public static int countWords(String strString[] words) { 
        int count = 0; 
        // iterating words 
        for (int i = 0i < words.lengthi++) { 
            // checking if word is present in the string or not 
            if (str.contains(words[i])) { 
                // if present then it increments the count value 
                count = count + 1; 
            } 
        } 
        return count; 
    } 
}  

Output: 

4