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:
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:
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:
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.
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.
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.
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.
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.
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
.
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
.
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?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
String str = "abc"; str = "xyz"; // here the value of Object str is not changed, a new String literal "xyz" is created and str is now holding reference to this new String.
I would suggest you to go through this post to know the properties of a immutable class and how you can write your own immutable class. Immutable Classes in Java- Pankaj
String s1=new String(“Hello”) above code How many objects will create?
- siddu
Hi, Thank you for providing the insight on this topic! My question here is what will happen to String “abc” stored in pool memory, meaning how long will exist and when & how the same will be removed from memory? Similarly what happens to object stored outside of constant pool memory?
- Arun
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
Thanks Ravi, yes you are right. Corrected the post.
- Pankaj
Pankaj, I think you were right before. when we create string with String s1 = new String(“abc”) then two objects are created. One is created on heap and second on constant pool(created only if it is not there in the pool). Since we are using new operator to create string so s1 always refers to the object created on the heap. When we create string with String s2 = “abc” then s2 will refer to object created in the constant pool. No object will be created on the heap. Since s1 and s2 are referring to different objects s1 == s2 will return false. If we want s1 to refer object created on the pool then use s1.intern().
- Amit Malik
Hi I’ve a query!! please correct me if I’m wrong. String s = new String(“Hello”); When above code is executed two objects will be created. One in heap another in SCP(String Constant Pool) So what is the need to use intern() explicitly.? Or when do we use intern() exactly?? by above discussion i got that object will not be added to SCP but its created.!! then where it is created.?
- deepak
I have the exactly same question
- Rhicha
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
Thanks Nandan for kind words. It’s these appreciations that helps me keep going.
- Pankaj
really this material is gud. definitely it will help a lot 2 give a good concept in string…
- Trilochan
Thanks for liking it.
- Pankaj
sir pls clearly explain the java in string concept
- tamil
I have already wrote a lot about String class in java, String is like other classes in java with some additional features because of it’s heavy usage. Read these posts for better understanding: https://www.journaldev.com/802/why-string-is-immutable-or-final-in-java https://www.journaldev.com/797/what-is-java-string-pool
- Pankaj
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
Thanks Nilesh, it really feels good that my articles are helping and cleared your doubts.
- Pankaj
its really good and useful…try to post some typical and tricky programs on strings which will be helpful for interviews and thanks…
- dinesh
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
excellent post !!! could you discuss programming questions related to strings such as reverse a stringand other string operations… which algorithm will be best and its time complexity… thanks
- kiki
Hi Pankaj, I liked you post because the coding question you put in it. We can get the theory knowledge from any web site, but questions like coding based we can’t get from other site. Keep up good job and keep concentrate on coding related question. I really like one ans. i.e Write a method that will remove given character from the String? I know this method, but you used in a different manner. Expecting more like this from you. I will be in touch with you after this. I met this site first time.
- ADITYA VALLURU
Very helpful, just wanted to say that I appreciate the clarity with which the answers are presented.
- Gary
Hi , in answer of ‘What are different ways to create String Object?’ you have said when we use new operator with string .it will create one object…but in scjp 6 book author is saying there will be 2 objects , one in string pool and second is in heap. see this link also ‘https://www.coderanch.com/t/245707/java-programmer-SCJP/certification/String-object-created’ (https://www.coderanch.com/t/245707/java-programmer-SCJP/certification/String-object-created’) … please elaborate this string concept
- saurabh moghe
String is not final by default since you have mentioned “String immutable and final in java”?
- Harikrishna
public void testFinally(){ System.out.println(setOne().toString()); } protected String setOne(){ String s1=new String(); try{ s1.concat(“Cool”); return s1=s1.concat(“Return”); }finally{ s1=null; /* ;) */ } } When s1 string concatenates with cool it has content as “cool”. In next statement it points it to same reference s1.so the output should be “returncool”.Why its “return”.
- Ruchi Gupta
Hi Pankaj, I have one doubt. I want to know if we execute the below statements then how many objects and references will be created on each line 1, 2 and 3. 1.) String s1 = “abc”; 2.) String s2 = “abc”; 3.) String s3= new String(“abc”); Thanks, Ishan
- Ishan Aggarwal
can you expalin about thread in real time?
- sudhakar
Hi, I need a solution for this Consider String str1 = “hari”; String str2 = “malar”; now find the same characters in both the string and delete the repeated characters So, the output must be str1 = hi str2 = mla
- Sanjana
Hi pankaj, I have a question in string permutation? for example: Input: sarita key :ri the out put should be :sarita, sarIta, saRita, saRIta
- Sarita