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
There will be two objects created one is in heap and one is in constant pool. Ques… how and Why … How Everything that is inserted within the " " (double quote) is a string and JVM forces to allocate the memory in the Constantpool… ok fine. And we also know the new Keyword that is used to allocate the memory in the Heap. And as the SCJP standard in case of string making the object with new keyword is certainly memory lose. example: String s=new String(“Deepak”);//line 1 String s1=“Deepak”; the reference Id of “Deepak” object will be assigned to s1.because It is already in the pool.//see line1 Question Arise: What kind of Memory is used by the ConstantPool…Heap or other…
- Deepak Chauhan
String s=new String(“Deepak”); when u have create a String object by using new keword than every time create new object in heap; but by using literal String than check in the memory but here there are two object is created one is heap , and second in pool; public class java { public static void main(String arr[]) { String s=new String(“Deepak”); String s1=“Deepak”; String s2=new String(“Deepak”); System.out.println(s==s2); System.out.println(s==s1); } } output is false false that is solution
- Paramjeet Singh
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
Thats what is mentioned here…
- Pankaj
please explain why intern() is needed if the object will be created in both constant pool and heap when we use new operator.
- deepak
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
Thanks Aditya, please look into other posts too. I am sure you find a lot of good stuffs. :)
- Pankaj
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
String is a final class and immutable too.
- Pankaj
not satisfied…see the code class StringFinal{ public static void main(String args[]){ //String s1 = new String(“hi”); String s1 = “hello”; s1 = “hi”; System.out.println(s1); } } it will print hi,not hello
- Rajesh
You need to understand that s1 is reference only to object. First it’s referring to “hello” and then “hi”, hence the output. I would suggest you to read about immutability.
- Pankaj
lol…pankaj is saying String class is declared final in JDK source code dumbo… final class String {} in JDK
- Anshul
whatever Pankaj said that is True. String s1 = “hello”; --> new object created System.out.println(s1.toUpperCase()); -->In String class we have methods like toUpper() and toLower() you are trying to make Uppercase to s1. this will result “HELLO” but this will not store in s1. System.out.println(s1) -->results hello only s1 = s1.toUpperCase System.out.println(s1) ---->results HELLO s1 = “hi”; —> here you are not changing object. you are changing object reference.
- Hareesh
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
The point to remember is that String is immutable, so in
s1.concat(“Cool”);
line, a new String is created but since you didn’t assigned it, it’s lost. s1 value is still “”.s1=s1.concat(“Return”);
: here you are assigning after concat, so s1 is “return” now, hence the output.- Pankaj
String is Immutable ,whenever we are adding anything using concat method it points new ref after concatination if string not modified then it point same ref ,1st time u r not assigned any variable so it will create other obj and second time your storing in again s1 so it returns return only,but this process not applicable for Adding string using "+ " operator.
- rose
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
1. “abc” in String Pool and s1 reference in the stack memory. 2. s2 reference created in stack memory, referring to the same string object “abc” in the pool. 3. s3 reference created and new String object with value “abc” in the heap memory. So total 2 string objects and 3 references.
- Pankaj
Hi Pankaj Thanks for these wonderful questions I have a doubt that if we can create objects through String literals than why do we use creating string objects through new keyword as it is not memory efficient way. Is it possible to completely remove the feature of creating String objects through new keyword…Please Explain
- vallabhi
Since String is an Object and we can use new operator to instantiate it. It’s not possible to remove this option.
- Pankaj
Strings created in pool are not garbage collected. Please correct me Pankaj if i am wrong.
- Ruchi Gupta
If the references were defined as instance variables, they are created in the heap memory.
- Anoop
Only two objects will be created … one objects for String s1 = “abc” and another for new String(“abc”)
- aditya
Hello Ishan, String x = “abc”; // It creates 1 String object and 1 reference variable. //“abc” will go to pool memory and x will refer to it. String y = new String(“xyz”); //It creates 2 objects and one reference variable. //In this case, because we used the new keyword, java will create a new String object in the normal (non-pool) memory, one object in the pool memory(for storing “xyz”), and y will refer to it. 1.) String s1 = “abc”; -> 1 object and 1 refercene 2.) String s2 = “abc”; -> 0 object and 1 reference 3.) String s3= new String(“abc”); -> 2 objects and 1 reference. So the correct answer to your question would be 3 objects and 3 reference. Regards Dhruba
- Dhruba Jyoti Talukdar
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
hi I have one small doubt which data type is used to check whether the given string student is present or absent
- arun
hi… How to print program source code as output in java language…?
- amar
How to Print source code as output in java??
- amar
I need program: write a java program to give the spaces b/w words Ex: i/o : ramisagoodboy o/p : ram is a good boy
- ram
use trim() method when need spaces
- siddharth
sorry use append(" "); method
- siddharth
search in GOOGLE with below words: how to trim a string in java
- Hareesh
Hi Pankaj, Very useful work… keep it up…
- Lukman
I have two Strings str1=“ABC”,str2=“BC” ,then output will come op1=A, op2=null, and next string are change str1=“B” str2= “BANGALORE”, then op1=“ANGALORE” op2=null, how can write write the program please could you explian ?
- srikanth
What is the logic for this, what are you trying to achieve here? If you have logic, create an algorithm for that and then writing code is the easy part.
- Pankaj
Dear sir, I have one basic question. Why java supports both features of string string creation. String str=“abc”; String strObj=new String(“abc”); str=“abc” is better than new String(). So why Java supports new String();
- maitrey
I am also having the same question. Recently interviewer asked this to me that what is the significance of string object creation with new keyword. If you have any thoughts then please add it
- Chetan
In case of instance of string in constant string pool while in second case two instance will be created one will be stored constant string pool while other in heap (as commonly object reference are stored in case of using new keyword). so String str=“abc” is memeory efficient compared to String strObj=new String(“abc”);
- ashish
Only designer of Java can give you more specific and correct answer we can only make few assumption on that (1) if someone want to create new string each and ever time so they can use new keyword.etc
- Ashutosh
one more point is on why to create string using new keyword, you can use different constructors to create a string. For example: creating string by char array creating string for specific encoding etc.
- Ashutosh
Amazing work Pankaj… keep up the good work…I have been a regular visitor of your site and posts.
- irfan
Very helpful… thanks pankaj:)
- Senthil Narayanan
deep approach in string…its really helpful
- shank’s
Hey Pankaj… Where is comparison operator in Question 1 for which U R saying that don’t confuse with that?
- ARVIND AGGARWAL
hi I have one small doubt which data type is used to check whether the given string student is present or absent
- arun
hi… How to print program source code as output in java language…?
- amar
How to Print source code as output in java??
- amar
I need program: write a java program to give the spaces b/w words Ex: i/o : ramisagoodboy o/p : ram is a good boy
- ram
use trim() method when need spaces
- siddharth
search in GOOGLE with below words: how to trim a string in java
- Hareesh
Hi Pankaj, Very useful work… keep it up…
- Lukman
I have two Strings str1=“ABC”,str2=“BC” ,then output will come op1=A, op2=null, and next string are change str1=“B” str2= “BANGALORE”, then op1=“ANGALORE” op2=null, how can write write the program please could you explian ?
- srikanth
What is the logic for this, what are you trying to achieve here? If you have logic, create an algorithm for that and then writing code is the easy part.
- Pankaj
Dear sir, I have one basic question. Why java supports both features of string string creation. String str=“abc”; String strObj=new String(“abc”); str=“abc” is better than new String(). So why Java supports new String();
- maitrey
I am also having the same question. Recently interviewer asked this to me that what is the significance of string object creation with new keyword. If you have any thoughts then please add it
- Chetan
Only designer of Java can give you more specific and correct answer we can only make few assumption on that (1) if someone want to create new string each and ever time so they can use new keyword.etc
- Ashutosh
Amazing work Pankaj… keep up the good work…I have been a regular visitor of your site and posts.
- irfan
Very helpful… thanks pankaj:)
- Senthil Narayanan
deep approach in string…its really helpful
- shank’s
Hey Pankaj… Where is comparison operator in Question 1 for which U R saying that don’t confuse with that?
- ARVIND AGGARWAL
Pankaj, you said like char array is more preferable than String to store password but if you go with the security concern String immutability is big advantage to store such sensitive information like Username,password. Looks conflicting to me.
- Walter Frobin Ekka
Strings are stored in String Pool as plain text and have longer life, anybody having access to memory dump can find it. In favor of this, getPassword() method of JPasswordField returns a char[] and deprecated getText() method which returns password in clear text stating security reason.
- Pankaj
It is tremendously written thanks for such great explanation … Keep writing we will hope for more and more concept
- Ravi
Thanks Ravi, we are determined to write best articles. You should also subscribe to our newsletter where we send exclusive tips and free eBooks.
- Pankaj
Hii pankaj, Your articles are super,first i tq u to ur thinking like to make it all useful info into one place.
- mani_v
String str2 = new String(“abc”); String str1 = “abc”; System.out.println("value = " + str1.equals(str2)); The above program returns value true, can you explain why?
- Sundara Baskaran
Equals() method always compares contents of the strings.
- dilli
because equals method in String class is overridden.
- Amit
Hi Pankaj, I am very use to go through with your tutorials they are excellent and simple to understand, but while reading above string interview questions I saw that “when you create string using new keyword it would create 2 object one in pool and another one in heap(if the same string was not exist in pool)”. So can you please explain how exactly it works internally , I checked across on internet but unluckily didn’t find any satisfactory answer or logic? I hope you will reply. Thanks- Your’s Reader .
- Ashutosh
When new keyword is used, it will just create in the heap and not in String pool. You will have to use intern() method to move it to Pool.
- Pankaj
How many String objects got created in below code snippet? 1. String s1 = new String(“Hello”); 2. String s2 = new String(“Hello”); Answer is 3. First – line 1, “Hello” object in the string pool. Second – line 1, new String with value “Hello” in the heap memory. Third – line 2, new String with value “Hello” in the heap memory. Here “Hello” string from string pool is reused. Here, how the “Hello” will be created in String Pool since we have not used either double quote String s1 = “Hello” or s1 = s1.intern() method, then how it will be created in Pool as you explained. If I am not wrong, you might have missed any one of the above way of creation. Please explain me…
- Vijay
whenever you write any string in double quotes it automatically creates an object of string in string pool.
- Puneet Srivastava
Difference between String, StringBuffer and StringBuilder? Ans : So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder. Hi please correct this answer it makes lots of confusion. it must be like below Ans : So when multiple threads are working on same String, we should use StringBuilder but in single threaded environment we should use StringBuffer.
- Ajay Dwivedi
The given answer is correct. StringBuffer is thread safe, not StringBuilder.
- Pankaj
How many object will create? String str1 = new String(“abc”); String str2 = new String(“xyz”);
- Jigar
4 objects First – line 1, “abc” object in the string pool. Second – line 1, new String with value “abc” in the heap memory. Third – line 2, new String with value “xyz” in the heap memory. Fourth - line 2, “xyz” object in the string pool Here since the value of string is different for both str1 and str2 hence “abc”,“xyz” string from string pool is not reused.
- Ankita
Hi Pankaj, In different ways to create string you have said: "When we use new operator, JVM creates the String object but DON’T store it into the String Pool. " And in string programming question: String s1 = new String(“Hello”); String s2 = new String(“Hello”); Athough string s1 is creating using new operator, you are saying Hello will be saved in String pool. Isn’t both statements are contradictory. Kindly let me know if I am missing something here. Thanks, Gaurav
- GAURAV PANT
“Hello” in the String constructor argument will be created first in the Pool, since it’s a string literal. Then s1 will be created in the heap.
- Pankaj
total 3 objects created new keyword creates objects in heap area------------------2 objects in string constant pool same content so it create ---------- 1 object -------------------------------------------------------------------------------- total 3 objects created
- arun
Stringbuffer sb=new Stringbuffer(“ab”); Stringbuffer sb1=new Stringbuffer(“ab”); syso(sb==sb1); O/P ?
- Srinivas
False
- Ujjwal
false
- siva ranjan
false because == operator works on reference comparison . It means if one object is referred by two reference variable then it will return true . but here there are two objects are created in heap memory so it returns false.
- anshu
Could you please add some details about hashcode() and equals operator in String class
- Abhi
My program is::: package interviews; public class InternMethod { public static void main(String[] args) { String str1=“java”; String str2=str1.intern(); String str3=new String(str1.intern()); System.out.println(“hash1=”+str1.hashCode()); System.out.println(“hash2=”+str2.hashCode()); System.out.println(“hash3=”+str3.hashCode()); System.out.println(“str1==str2==>>”+(str1==str2)); System.out.println(“str1==str3==>>”+(str1==str3)); } } ============================================output===> hash1=3254818 hash2=3254818 hash3=3254818 str1==str2==>>true str1==str3==>>false ================================= Can anyone explain how == returns false even though s1 and s3 having same hashcode?
- shailesh
Hi, I have one doubts for below code. String str = “test”; str = str+“test2”; str = str+“test3”; str = str + ''test4"; str = str + “test5”; Now many objects will be created and how many objects will be available for garbage collection? Can you please explain this?
- Vimal
hi pankaj, can u please explain the following doubt… String have two methods for creating one is literal,another way is new keyword ,if literal is the way which is memory efficient ,then why we also using ‘new’ ,please explain the scenarios where we can use them and main differentiating point to use them.
- Sunitha Kristipati
Hi Pankaj, can u please look on the following, String s1=new String(“sun”); String s=“sun”; System.out.println(s1.hashCode()); System.out.println(s.hashCode()); System.out.println(s1==s); O/P: -1856818256 -1856818256 false. here 1st i am creating s1 with new keyword .so as you said , its creates object in heap memory and in pool,next i created using literal which will creates object only in pool. As the s1 and s are present in the pool so they are having same hashcode, but when i am comparing them why its giving false.???
- Sunitha Kristipati
Hi Pankaji, thanks for the tutorial, is very good. I have doubts about last exercise: How many String objects got created in below code snippet? String s1 = new String(“Hello”); String s2 = new String(“Hello”); You say that the object created will be 3. I would answered 2, as new operator creates new object in the heap memory (not in the string pool) regardless of wheter there is same string stored in the string pool. Why you say 3? Thanks in advice.
- Szanowne
sir i have doubt string objects are created in 4 ways 1. literal method -----------------> String s1=“arun” 2. new operator -----------------> String s2=new String(“arun”); 3. satic factory method---------->String s3=.String.valueOf(“arun”); 4.instance factory method------> String s4=s1.concat(s2); it is correct or not
- arun
good
- Ketki Gawande
doesn’t your question 3 and 6 have ambiguity?? String s =new (“Hello”); object is created and also stored in string pool as per q6. String s2 =new (“Hello”); object is created and reference of s is passed . when checked with if (s==s2) ,shouldn’t it return true? but your q 3 says it as false. 2 different objects are created in heap. please clarify
- jayashree
When we create a string object by using new keyword… 2 objects created one in heap… and another in SCP. Please confirm and reply back thank you.
- Sidagouda Patil
Im totally confused. in one article you write "When we use new operator, JVM creates the String object but don’t store it into the String Pool. " in another “String str = new String(“Cat”); In above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool. If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will be created.” So which one is right ?
- Sever
Hi Pankaj, I read all the comments and got more confused. Can you please explain the pointers below. In “What are different ways to create String Object?” you answered: When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool. and then in last 6th question “How many String objects got created in below code snippet?” you answered. String s1 = new String(“Hello”); String s2 = new String(“Hello”); Answer is 3. First - line 1, “Hello” object in the string pool. Second - line 1, new String with value “Hello” in the heap memory. Third - line 2, new String with value “Hello” in the heap memory. Here “Hello” string from string pool is reused. So will it store the object in String pool or not. I hope this will clear things to all
- Mayank Tyagi
for interview point of view String is a most important topic. thank you to share this knowlge.
- Anurag Singh
Awesome collection of question keeps it Up Good work.
- bhupendra patidar
String s1=new String(“abc”).intern(); String s2=“abc”; How many objects will be created here ?
- gundamaiah
It feels good after go thru these Q&A. Thanks bro.
- Packiaraj Thusianthan
How many objects is created in following code? String a1=“hello”; String a2=“hello”; String a3=new String(“hello”);
- pintu
Question 6 answer will be 2 instead of 3. We can test it whether new String(“Hello”) creates Hello object in string pool or not. String s = new String(“Hello”); //only creates in Heap Memory not in String Pool System.out.println(s==“Hello”); //prints False
- Vedant Kumar
'As the name suggests, String Pool is a pool of Strings stored in Java heap memory. ', is it correct on the following page? https://www.journaldev.com/1321/java-string-interview-questions-and-answers
- Fake
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println(“\nThe longest palindrom of the input is \n” + getLongestPalindrom(scanner.nextLine())); scanner.close(); } private static String getLongestPalindrom(String input) { String longestPalindrom = “”; for(int i= 0;i<input.length()-longestPalindrom.length();i++) { String substring = input.substring(i); boolean isSubStringPalindrom = false; for(int j=0;j longestPalindrom.length())) { longestPalindrom = substring; } } return longestPalindrom; }
- Charli