String
is one of the most widely used Java classes. This article provides some practice questions and answers about String
to help you prepare for an interview.
You can also try the Java String Quiz to test your knowledge of the String
class.
String
class in Java? Is String
a data type?String
is a class in Java and is defined in the java.lang
package. It’s not a primitive data type like int
and long
. The String
class represents character strings. String
is used in almost all Java applications. String
in immutable and final in Java and the JVM uses a string pool to store all the String
objects. You can instantiate a String
object using double quotes and you can overload the +
operator for concatenation.
String
object in Java?You can create a String
object using the new
operator or you can use double quotes to create a String
object. For example:
String str = new String("abc");
String str1 = "abc";
There are several constructors available in the String
class to get a String
from char array
, byte array
, StringBuffer
, and StringBuilder
.
When you create a String
using double quotes, the JVM looks in the String pool to find if any other String
is stored with the same value. If the String
is already stored in the pool, the JVM returns the reference to that String
object. If the new String
is not in the pool, the JVM creates a new String
object with the given value and stores it in the string pool. When you use the new
operator, the JVM creates the String
object but doesn’t store it in the string pool. You can use the intern()
method to store the String
object in String pool or return the reference if there is already a String
with equal value present in the pool.
A string is a palindrome if its value is the same when reversed. For example, aba
is a palindrome string. The String
class doesn’t provide any method to reverse the string but the StringBuffer
and StringBuilder
classes have a reverse()
method that you can use to check whether a string is a palindrome. For example:
private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}
Sometimes, an interviewer might request that you don’t use any other class to check for a palindrome. In that case, you can compare characters in the string from both ends to find out if it’s a palindrome. For example:
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;
}
We can use the replaceAll
method to replace all of the occurrences of a string with another string. The important point to note is that replaceAll()
accepts String
as argument, so you can use the Character
class to create a string and use it to replace all the characters with an empty string.
private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}
String
upper case or lower case in Java?You can use the String
class toUpperCase
and toLowerCase
methods to get the String
object in all upper case or lower case. These methods have a variant that accepts a Locale
argument and use the rules of the given locale to convert the string to upper or lower case.
String subSequence
method?Java 1.4 introduced the CharSequence
interface and the String
class implements this interface, which is why the String
class has the subSequence
method. Internally, the subSequence
method invokes the String substring
method.
Java String
implements the Comparable
interface, which has two variants of the compareTo()
method. The compareTo(String anotherString)
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 passed, it returns a positive integer. It returns zero when both the String
objects have the same value. In this case, the equals(String str)
method also returns true
. The compareToIgnoreCase(String str)
method is similar to the first one, except that it ignores the case. It uses Comparator
with CASE_INSENSITIVE_ORDER
for case insensitive comparison. If the value is zero, then equalsIgnoreCase(String str)
will also return true.
String
to a character array in Java?A String
object is a sequence of characters, so you can’t convert it to a single character. You can use use the charAt
method to get the character at given index or you can use the toCharArray()
method to convert a string to character array. Learn more about converting a string to a character array.
String
to a byte array in Java?You can use the getBytes()
method to convert a String
object to a byte array and you can use the constructor new String(byte[] arr)
to convert a byte array to String
object. Learn more about converting a string to a byte array.
String
in switch case in Java?Java 7 extended the capability of switch case to Strings
; earlier Java versions don’t support this. If you’re 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. Learn more about Java switch case string.
You’ll need to use recursion to find all the permutations of a string. For example, the permutations of AAB
are AAB
, ABA
and BAA
. You also need to use Set
to make sure there are no duplicate values. Learn more about finding all the permutations of a string.
A string can contain palindrome substrings within it. Learn more about how to find the longest palindrome substring in a string.
String
, StringBuffer
, and StringBuilder
in Java?A String
object is immutable and final in Java, so whenever you manipulate a String
object, it creates a new String
object. 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, while StringBuilder
operations are not thread-safe. You should use StringBuffer
in a multi-threaded environment and use StringBuilder
in a single-threaded environment. StringBuilder
performance is faster than StringBuffer
because of no overhead of synchronization.
Learn more about the differences between String
, StringBuffer
and StringBuilder
and benchmarking of StringBuffer and StringBuilder.
String
immutable in Java?String
is immutable in Java because this offers several benefits:
String
is immutable in Java.String
is immutable, it’s safe to use in multi-threading and you don’t need any synchronization.ClassLoader
class.Learn more about why String
is immutable in Java.
You can use split(String regex)
to split the String
into a String
array based on the provided regular expression.
String
for storing passwords in Java?A String
object is immutable in Java and is stored in the string pool. Once it’s created it stays in the pool until garbage collection completes, so even though you’re done with the password it’s available in memory for longer duration. It’s a security risk because anyone having access to memory dump can find the password as clear text. If you use a character array to store password, you can set it to blank once you’re done with it. You can control for how long it’s available in memory and that avoids the security threat.
There are two ways to check if two Strings are equal. You can use the ==
operator or the equals()
method. When you use the ==
operator, it checks for the value of String
as well as the object reference. Often in Java programming you want to check only for the equality of the String
value. In this case, you should use the equals()
method to check if two Strings
are equal. There is another function called equalsIgnoreCase
that you can use to ignore 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("s1 equals s3 ? " + (s1.equals(s3))); //true
The string pool is a pool of String
objects stored in Java heap memory. String
is a special class in Java and you can create a String
object using the new
operator as well as by providing values in double quotes. Learn more about the Java string pool.
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
object that has the same contents as this String
but is guaranteed to be from a pool of unique strings.
String
thread-safe in Java?A String
object is immutable, so you can’t change its value after creation. This makes the String
object thread-safe and so it can be safely used in a multi-threaded environment. Learn more about thread Safety in Java.
String
a popular HashMap
key in Java?Since a String
object 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 the key in a Map since its processing is faster than other HashMap
key objects.
Test yourself by guessing the output of the following Java code snippets.
public class StringTest {
public static void main(String[] args) {
String s1 = new String("digitalocean");
String s2 = new String("DIGITALOCEAN");
System.out.println(s1 = s2);
}
}
DIGITALOCEAN
The output is DIGITALOCEAN
because the code assigns the value of String s2
to String s1
. =
is an assignment operator that assigns the value of y
to x
in the format (x = y)
. ==
is a comparison operator that would check if the reference object is the same for the two strings.
public class Test {
public void foo(String s) {
System.out.println("String");
}
public void foo(StringBuffer sb) {
System.out.println("StringBuffer");
}
public static void main(String[] args) {
new Test().foo(null);
}
}
Test.java:12: error: reference to foo is ambiguous
new Test().foo(null);
^
both method foo(String) in Test and method foo(StringBuffer) in Test match
This code results in a compile time error because both foo
methods have the same name and the call for the foo
method in main
is passing null
. The compiler doesn’t know which method to call. You can also refer to the method X is ambiguous for the type Y error.
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2);
false
The output is false
because the code uses the new
operator to create the String
object, so it’s created in the heap memory and s1
and s2
will have a different reference. If you create the strings using only double quotes, then they will be in the string pool and it will print true
.
String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));
false
The output is false
because s2
is not of type String
. The equals()
method implementation in the String
class has an instanceof
operator to check if the type of passed object is String
and return false if the object is not String
.
String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 == s2);
false
The output is false
. The intern()
method returns the String
object reference from the string pool. However, the code doesn’t assign it back to s2
and there is no change in s2
and sos1
and s2
have a different object reference. If you change the code in line 3 to s2 = s2.intern();
, then the output will be true
.
String
objects are created by the following code?String s1 = new String("Hello");
String s2 = new String("Hello");
The answer is three. The code in line 1 creates a String
object with the value Hello
in the string pool (first object) and then creates a new String
object with the value Hello
in the heap memory (second object). The code in line 2 creates a new String
object with value Hello
in the heap memory (third object) and reuses the Hello
string from the string pool.
In this article you reviewed some Java interview questions specifically about String
.
Recommended Reading:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Can you please explain the statement "Strings are immutable, so we can’t change it’s value in program. " by a sample program
- Ayan
Hi Pankaj, There is always something new to learn in your posts. But I would like to correct one thing in above post. When we create a String using
new
keyword, a whole new reference is being assigned, not from a literal. Up to this its right. But this instance is not added into the String Pool until we call intern(). We can check it out by below example:String s1 = new String("abc"); // new object - not from pool. String s2 = "abc"; // tries to search it from pool. System.out.println(s1 == s2); // returns false that means s1 has not been added to pool.
- Ravi
Nice Material… Keep it up to make us knowledgeable…
- Prosenjit
Thanks for finally talking about > Java String Interview Questions and Answers | JournalDev < Loved it!
- aicotutorial.com
Hi pankaj , your stuff regarding strings in java is really great . it is really helpful in prospective of interviews and gaining some knowledge over java strings … Loved it …Keep up good work buddy!!!
- nandan
really this material is gud. definitely it will help a lot 2 give a good concept in string…
- Trilochan
after readind all your questions i realfeel like am getting real basic and clear from all my doubts. pls increase your collections. i read String and COllection and it helped m e
- nilesh shinde
All your tutorials are great. Helping me in my job jump. Thanks a lot.
- devs
Hi pankaj, Thanks a lot for providing examples and good explanations.if you have stuff about GWT framework(Google Web Toolkit) please post that frame work concepts too.it will be really help to for those who new to this framework
- senthil hari
Please also put some light on the implementation of substring? How substring method can cause memory leaks? How can we avoid these memory leaks in java?
- Ashi