0% found this document useful (0 votes)
1K views51 pages

Java String Interview Questions and Answers - JournalDev

The document discusses Java String interview questions and answers. It provides 22 questions about Strings in Java including what a String is, how to create Strings, checking for palindromes, comparing Strings, converting between Strings and other types, and String pooling. The document aims to help readers gain complete knowledge of Strings and be prepared to answer related interview questions.

Uploaded by

Har Sha Chavali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
1K views51 pages

Java String Interview Questions and Answers - JournalDev

The document discusses Java String interview questions and answers. It provides 22 questions about Strings in Java including what a String is, how to create Strings, checking for palindromes, comparing Strings, converting between Strings and other types, and String pooling. The document aims to help readers gain complete knowledge of Strings and be prepared to answer related interview questions.

Uploaded by

Har Sha Chavali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 51

11/22/2019 Java String Interview Questions and Answers - JournalDev

Java Tutorial #Index Posts #Interview Questions Resources


Java String Interview Questions and Filed Under: Interview Questions

Answers
Pankaj - 186 Comments
Home » Interview Questions » Java String Interview Questions and Answers

AD
String is one of the most widely used Java Class.
Here I am listing some important Java String
Interview Questions and Answers.

This will be very helpful to get complete


knowledge of String and tackle any questions
asked related to String in an interview.

Quizzes are fun, aren’t they! I recently


published the Java String quiz of 21
questions. It has been taken by thousands
of Java enthusiasts with an average score of
42.55%. You should take that and try to beat
the average score and get your name into
the leaderboard.

Here is the link that opens in a new tab:


Java String Quiz

Java String Interview Questions

1. What is String in Java? String is a data type?


2. What are di erent ways to create String
Object?
3. Write a method to check if input String is
Palindrome?
4. Write a method that will remove given
character from the String?
5. How can we make String upper case or lower
case?
6. What is String subSequence method?
7. How to compare two Strings in java program?
8. How to convert String to char and vice versa?
9. How to convert String to byte array and vice
versa?
10. Can we use String in switch case?
11. Write a program to print all permutations of
String?
12. Write a function to nd out longest palindrome
in a given string?
13. Di erence between String, StringBu er and
StringBuilder?
14. Why String is immutable or nal in Java
15. How to Split String in java?
16. Why Char array is preferred over String for
storing password?
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 1/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

17. How do you check if two Strings are equal in


Java?
18. What is String Pool?
19. What does String intern() method do?
20. Does String is thread-safe in Java?
21. Why String is popular HashMap key in Java?
22. String Programming Questions

What is String in Java? String is a


data type?

String is a Class in java and de ned in java.lang


package. It’s not a primitive data type like int and
long. String class represents character Strings.
String is used in almost all the Java applications
and there are some interesting facts we should
know about String. String in immutable and nal
in Java and JVM uses String Pool to store all the
String objects.
Some other interesting things about String is the
way we can instantiate a String object using
double quotes and overloading of “+” operator for
concatenation.

What are di erent ways to create


String Object?

We can create String object using new operator


like any normal java class or we can use double
quotes to create a String object. There are several
constructors available in String class to get String
from char array, byte array, StringBu er and
StringBuilder.

String str = new String("abc");


String str1 = "abc";

When we create a String using double quotes,


JVM looks in the String pool to nd if any other
String is stored with the same value. If found, it
just returns the reference to that String object
else it creates a new String object with given
value and stores it in the String pool.
When we use the 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.

Write a method to check if input


String is Palindrome?

A String is said to be Palindrome if it’s value is


same when reversed. For example “aba” is a
Palindrome String.
String class doesn’t provide any method to
reverse the String but StringBuffer and
StringBuilder class has reverse method that Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 2/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

we can use to check if String is palindrome or


not.

private static boolean isPalindrome(St


if (str == null)
return false;
StringBuilder strBuilder = new Str
strBuilder.reverse();
return strBuilder.toString().equal
}

Sometimes interviewer asks not to use any other


class to check this, in that case, we can compare
characters in the String from both ends to nd
out if it’s palindrome or not.

private static boolean isPalindromeStr


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.charA
return false;
}
return true;
}

Write a method that will remove


given character from the String?

We can use replaceAll method to replace all


the occurance of a String with another String. The
important point to note is that it accepts String as
argument, so we will use Character class to
create String and use it to replace all the
characters with empty String.

private static String removeChar(Strin


if (str == null)
return null;
return str.replaceAll(Character.to
}

How can we make String upper


case or lower case?

We can use String class toUpperCase and


toLowerCase methods to get the String in all
upper case or lower case. These methods have a
variant that accepts Locale argument and use
that locale rules to convert String to upper or
lower case.

What is String subSequence


method?
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 3/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Java 1.4 introduced CharSequence interface and


String implements this interface, this is the only
reason for the implementation of subSequence
method in String class. Internally it invokes the
String substring method.
Check this post for String subSequence example.

How to compare two Strings in


java program?

Java String implements Comparable interface


and it has two variants of compareTo() methods.

compareTo(String anotherString) method


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

compareToIgnoreCase(String str): This method is


similar to the rst one, except that it ignores the
case. It uses String CASE_INSENSITIVE_ORDER
Comparator for case insensitive comparison. If
the value is zero then equalsIgnoreCase(String
str) will also return true.
Check this post for String compareTo example.

How to convert String to char and


vice versa?

This is a tricky question because String is a


sequence of characters, so we can’t convert it to
a single character. We can use use charAt
method to get the character at given index or we
can use toCharArray() method to convert
String to character array.
Check this post for sample program on
converting String to character array to String.

How to convert String to byte


array and vice versa?

We can use String getBytes() method to


convert String to byte array and we can use
String constructor new String(byte[] arr) to
convert byte array to String.
Check this post for String to byte array example.

Can we use String in switch case?

This is a tricky question used to check your


knowledge of current Java developments. Java 7
extended the capability of switch case to use
Strings also, earlier Java versions don’t support
this.
If you are implementing conditional ow for Previous Next 
Strings, you can use if-else conditions and you
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 4/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

can use switch case if you are using Java 7 or


higher versions.

Check this post for Java Switch Case String


example.

Write a program to print all


permutations of String?

This is a tricky question and we need to use


recursion to nd all the permutations of a String,
for example “AAB” permutations will be “AAB”,
“ABA” and “BAA”.
We also need to use Set to make sure there are
no duplicate values.
Check this post for complete program to nd all
permutations of String.

Write a function to nd out


longest palindrome in a given
string?

A String can contain palindrome strings in it and


to nd longest palindrome in given String is a
programming question.
Check this post for complete program to nd
longest palindrome in a String.

Di erence between String,


StringBu er and StringBuilder?

The string is immutable and nal in Java, so


whenever we do String manipulation, it creates a
new String. String manipulations are resource
consuming, so java provides two utility classes
for String manipulations – StringBu er and
StringBuilder.
StringBu er and StringBuilder are mutable
classes. StringBu er operations are thread-safe
and synchronized where StringBuilder operations
are not thread-safe. So in a multi-threaded
environment, we should use StringBu er but in
the single-threaded environment, we should use
StringBuilder.
StringBuilder performance is fast than
StringBu er because of no overhead of
synchronization.

Check this post for extensive details about String


vs StringBu er vs StringBuilder.
Read this post for benchmarking of StringBu er
vs StringBuilder.

Why String is immutable or nal


in Java

There are several bene ts of String because it’s


immutable and nal.

String Pool is possible because String is


immutable in java. Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 5/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

It increases security because any hacker can’t


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

Check this post to get more details why String is


immutable in java.

How to Split String in java?

We can use split(String regex) to split the


String into String array based on the provided
regular expression.
Learn more at java String split.

Why Char array is preferred over


String for storing password?

String is immutable in Java and stored in String


pool. Once it’s created it stays in the pool until
unless garbage collected, so even though we are
done with password it’s available in memory for
longer duration and there is no way to avoid it. It’s
a security risk because anyone having access to
memory dump can nd the password as clear
text.
If we use a char array to store password, we can
set it to blank once we are done with it. So we
can control for how long it’s available in memory
that avoids the security threat with String.

How do you check if two Strings


are equal in Java?

There are two ways to check if two Strings are


equal or not – using “==” operator or using
equals method. When we use “==” operator, it
checks for the value of String as well as the
reference but in our programming, most of the
time we are checking equality of String for value
only. So we should use the equals method to
check if two Strings are equal or not.
There is another function equalsIgnoreCase
that we can use to ignore case.

String s1 = "abc";
String s2 = "abc";
String s3= new String("abc");
System.out.println("s1 == s2 ? "+(
System.out.println("s1 == s3 ? "+(
System.out.println("s1 equals s3 ?

What is String Pool?


Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 6/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

As the name suggests, String Pool is a pool of


Strings stored in Java heap memory. We know
that String is a special class in Java and we can
create String object using new operator as well
as providing values in double quotes.
Check this post for more details about String
Pool.

What does String intern() method


do?

When the intern method is invoked, if the pool


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

Does String is thread-safe in


Java?

Strings are immutable, so we can’t change it’s


value in program. Hence it’s thread-safe and can
be safely used in multi-threaded environment.
Check this post for Thread Safety in Java.

Why String is popular HashMap


key in Java?

Since String is immutable, its hashcode is cached


at the time of creation and it doesn’t need to be
calculated again. This makes it a great candidate
for the key in a Map and it’s processing is fast
than other HashMap key objects. This is why
String is mostly used Object as HashMap keys.

String Programming Questions

1. What is the output of below program?

package com.journaldev.strings;

public class StringTest {

public static void main(String[


String s1 = new String(
String s2 = new String(
System.out.println(s1 =
}

It’s a simple yet tricky program, it will print


“PANKAJ” because we are assigning s2 String
to s1. Don’t get confused with == comparison
operator.

2. What is the output of below program? Previous Next 


https://www.journaldev.com/1321/java-string-interview-questions-and-answers 7/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

package com.journaldev.strings;

public class Test {

public void foo(String s) {


System.out.println("String");
}

public void foo(StringBuffer s


System.out.println("StringBuffe
}

public static void main(String


new Test().foo(null);
}

The above program will not compile with error


as “The method foo(String) is ambiguous for
the type Test”. For complete clari cation read
Understanding the method X is ambiguous for
the type Y error.

3. What is the output of below code snippet?

String s1 = new String("abc");


String s2 = new String("abc");
System.out.println(s1 == s2);

It will print false because we are using new


operator to create String, so it will be created
in the heap memory and both s1, s2 will have
di erent reference. If we create them using
double quotes, then they will be part of string
pool and it will print true.

4. What will be output of below code snippet?

String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);
System.out.println(s1.equals(s2));

It will print false because s2 is not of type


String. If you will look at the equals method
implementation in the String class, you will
nd a check using instanceof operator to
check if the type of passed object is String? If
not, then return false.

5. What will be the output of below program?

String s1 = "abc";
String s2 = new String("abc");
s2.intern();
System.out.println(s1 ==s2);

It’s a tricky question and output will be false.


We know that intern() method will return the
String object reference from the string pool,
but since we didn’t assigned it back to s2,
there is no change in s2 and hence both s1
and s2 are having di erent reference. If we
change the code in line 3 to s2 =
s2.intern(); then output will be true. Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 8/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

6. How many String objects got created in below


code snippet?

String s1 = new String("Hello");


String s2 = new String("Hello");

The 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.

I hope that the questions listed here will help you


in Java interviews, please let me know if I have
missed anything.

Further Reading

1. Java Programming Questions


2. String Programs in Java
3. Core Java Interview Questions
4. Java Interview Questions

How to generate XSD from


Java Class

PREV

Composition in Java Example

NEXT

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 9/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Pankaj

I love Open
Source
technologies Follow Author
and writing
about my
experience
about them
is my
passion.

Comments

Ram says: July 30, 2019 at 11:33 pm

Hi Sir,
Thanks for advance.
My question is to you what is the need
of intern() method.As of now my
understanding while creating instance
to String using new operator it will be
in String pool and heap memory as of
your 6 question answer And when we
create instance for string using double
quote automatically store into string
constant pool. Could you please clarify
on the same
Reply

Pankaj says: July 31, 2019 at 5:25 am

Read this tutorial:


https://www.javastring.net/java/stri
ng/java-string-intern-method-
example
Reply

prem kiran says: June 19, 2019 at 5:18 pm

This is some great work! Thanks for


sharing.
Reply

Tushar Desarda says:


January 11, 2019 at 6:49 pm

StringBu er is thread safe. Two threads


can not call methods of StringBu er
simultaneously but in di rence you
mentioned opposite StringBuilder is
used for multi threaded application not
StringBu er
Reply

Srividya says: October 23, 2018 at 6:52 pm

Hi Pankaj,
Good collection on Strings. Appreciate
your e orts. I have only one doubt on
String pool. Your statements regarding
the below question is contradictory.
What are di erent ways to create String
Object?
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 10/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

String str = new String(“abc”);


String str1 = “abc”;
When we create a String using double
quotes, JVM looks in the String pool to
nd if any other String is stored with
same value. If found, it just returns the
reference to that String object else it
creates a new String object with given
value and stores it in the String pool.
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.
you said that when we use new
operator JVM creates string object but
not stored in String pool. Need to use
intern() to store in stringpool.
for question 6 you are saying that using
new operator it will also create in string
pool.
6) How many String objects got created
in below code snippet?
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.
First – line 1, “Hello” object in the string
pool. (we are not using intern() here
then how it is stored in stringpool.
Which one is true? Please do explain.
Thanks in advance.
Reply

Pankaj says:October 23, 2018 at 10:16 pm

I see your confusion here.


Whenever a string is created using
double quotes, it gets created in
the string pool. So when we say
String s1 = new
String(“Hello”); , one string is
created in the string pool rst,
then passed as an argument to the
new operator and a new string
object is created in the heap area.
So there are two string objects
created here, but the one created
in the string pool is not referenced
by any variable and is applicable
for garbage collection.
Earlier statement about string
created using new operator in the
heap area is also true because the Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 11/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

string reference you are getting is


present in the heap area.
Reply

kps says: April 12, 2019 at 3:25 am

So you mean to say, when we


create String using new
operator (String s1 = new
String(“Hello”)) one object is
created in heap memory and
one object is created in
constant pool as well and the
one which is created in pool
will not have any reference
and it is applicable for
garbage collection(so it
means this object is of no
use? and if there is already
one object created in pool
using String s = “Hello” so
how come one more object
will be created in pool with
this statement String s1 =
new String(“Hello”) why it will
not use the same reference
here). can you explain me
once again.
Reply

Leonid Talalaev says:


October 8, 2018 at 12:56 am

Method removeChar will not work if c is


special reg exp character (e.g. ‘.’, ‘[‘).
String.replaceAll takes regexp as rst
parameter. You need to use
String.replace instead of
String.replaceAll.
Reply

suryateja garapati says:


October 3, 2018 at 6:27 am

sir please explain about trim() function


in strings
Reply

Dharmendra Kumar says:


October 16, 2018 at 9:48 pm

Hii surya
trim() function is method of spring
which eliminate spaces before the
string and spaces a er string
for example:
str1=” sumit”;//here is a space
before String
str1.trim();
System.out.println(str1);// output
will be “sumit” Here is no space
before string
Reply

satya says:
October 15, 2019 at 1:44 am

Hi Dharmendra,
the above example, you
didn’t assigned again to str1 Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 12/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

object.
str1=” sumit”;//here is a
space before String
str1=str1.trim();
System.out.println(str1);//
output will be “sumit” Here is
no space before string
Reply

Charli says: September 7, 2018 at 12:23 pm

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;
}
Reply

Fake says: July 10, 2018 at 11:47 pm

‘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
Reply

Vedant Kumar says: April 17, 2018 at 8:47 pm

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
Reply

Pankaj says: April 17, 2018 at 9:36 pm

The argument in String


constructor is rst created in Pool,
you missed to count this one.
Reply
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 13/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

ShubhamAugust
says:31, 2018 at 10:43 pm

Hello Pankaj Sir,


Please improve your java
concepts and then post the
blogs. Please dont post
wrong concepts here. For
Question 6, there will be only
2 objects created in memory
(heap area). Strings are kept
in string pools only when it’s
created as a literals like
below:
String s = “Hello”;//It will go
to String pool and it will be
unique
String s1= new
String(“Hello”); //new
operator means everytime
new object will be create din
heap memory, not in string
pool.
Thanks
Shubham
Reply

Pankaj says:
September 1, 2018 at 9:41 am

Ha ha ha, did you even


read the question? What
you have posted in the
comment is totally
di erent. Please clear
your concepts before
posting such a harsh
comment.
Reply

pintu says: March 12, 2018 at 12:18 pm

How many objects is created in


following code?
String a1=”hello”;
String a2=”hello”;
String a3=new String(“hello”);
Reply

Pankaj says: March 13, 2018 at 12:14 am

Two, rst a1 in string pool, then a3


in heap.
Reply

sachin September
says: 21, 2018 at 8:06 am

case : 1
String a1=”hello”;
String a2=”hello”;
String a3=new String(“hello”);
as per pankaj’s comment: 2
objects will be created ( rst
a1 in string pool, then a3 in
heap.)
so according to the above
result,if we consider below Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 14/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

problem then
String s1 = new
String(“Hello”); //1 object
creation in heap due to new
String s2 = new
String(“Hello”); //2nd object
in heap due to new
total 2 object must be
created .
question to pankaj , as per
your above comments, why
“hello” should be in string
constant pool(as it already
allocated via heap segment &
will cause 2 times memory
allocation.
please reply ..
Reply

pintu says: March 13, 2018 at 9:22 pm

thanks ,
Reply

SAI SUNDEEP says:


June 8, 2018 at 8:49 am

In Heap Area 1 Object will be


created ie.,
a3=hello; will be created and
1 object is created in String
Constant Pool And Referenced by
a1 & a2.
Reply

Packiaraj Thusianthan says:


February 3, 2018 at 6:47 am

It feels good a er go thru these Q&A.


Thanks bro.
Reply

gundamaiah says: January 4, 2018 at 2:44 am

String s1=new String(“abc”).intern();


String s2=”abc”;
How many objects will be created here
?
Reply

Nas says: January 10, 2018 at 12:46 am

2 objects
Reply

Pravesh Kharb says:


March 7, 2018 at 4:47 am

only one object will be created


here in this case.
As here if you check s1==s2, it will
return true, as only one object is
there
Reply

palvi says: March 22, 2018 at 3:16 pm

1,
When the intern method is Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 15/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

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.
Reply

Sandeep Patil March


says:23, 2018 at 11:35 pm

2 objects because S2 is created


on second line thus s1 wont nd
any thing to equal thus create an
object in heap. intern returns
value of string if found in pool. s2
will b created in the pool whereas
s1 ll b in heap memory
Reply

Dotan Mal says: May 7, 2018 at 6:21 am

2 objects.
rst is argument in String
constructor “abc” will be created
in string pool – new String(“abc”)
second will be created in the
Heap by the ‘new’ operator
the .intern() method invokes a er
this 2 objects created, then
checks in string pool for “abc” (
which is there) and return a
reference to it
– in this case we have no
reference to the object created in
the heap by the new operator
– second line doesn’t change
number of objects created
Reply

Aditya(Anna The Great)


October says:
5, 2019 at 1:57 pm

3 objects because
for s1 – (one objects is created in
string constant pool and one is
created in non-constant pool or
heap ) here, 2 obj.
now, for s2 – there is only one
object is created in scp(string
constant pool).
thus, 3 objects are created .
Reply

bhupendra patidar says: 29, 2017 at 9:08 am


November

Awesome collection of question keeps


it Up Good work.
Reply

Anurag Singh says: July 21, 2017 at 3:55 am

for interview point of view String is a


most important topic.
thank you to share this knowlge.
Reply Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 16/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Mayank Tyagi says: June 30, 2017 at 9:35 am

Hi Pankaj,
I read all the comments and got more
confused. Can you please explain the
pointers below.
In “What are di erent 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
Reply

waqas_kamran says:
February 15, 2018 at 11:04 pm

it will store or create new object in


heap memory but literal “hello”
will be in string pool .
Reply

Ajeet Kumar says:


March 5, 2018 at 10:55 am

Yes, Line 1 :- Checks if “Hello” is


in Pool , if Not Then Creates in
Pool. else nothing.( count = 1)
Then it creates String in Heap
which will be referenced by s1.
(count = 2)
Line 2 :- Checks if “Hello” is in
Pool , if Not Then Creates in Pool.
but it is already there so nothing
to do.
Then it creates String in Heap
which will be referenced by s2.
(count = 3)
Reply

bharat jha says:June 22, 2018 at 10:33 pm

when we create string object with


the new operator , at that time
“HELLO” rst get in string pool, if
it is already in string pool then it
will not go in pool, a er that the
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 17/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

new line will execute and create


one object in heap.
Reply

Sever says: June 10, 2017 at 2:28 pm

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 rst created in
the pool and then in the heap space, so
total 2 string objects will be created.”
So which one is right ?
Reply

Pankaj says: June 10, 2017 at 10:21 pm

Both are correct. See when we


use new operator with String, we
also use String literal. So
depending on whether the string
literal is present in the string pool
or not, either 1 or 2 string object
will be created.
First statement just specify that
String created will not be stored in
the pool, it doesn’t say how many
string objects will be created.
Both the statements are correct in
their own area.
Reply

joginder Sheoran says:


March 17, 2019 at 10:46 am

Pankaj, Agree with your point


:
What you mean to say is
while creating string through
new operator we are passing
string literal in double quotes
as argument, so it creates a
String Object in Pool.
If this is true, why do we
need intern() method which
when invoked on String
object return String reference
from pool if String already
exist, otherwise it do create a
new Sting literal in pool and
returns a reference.
Reply

Sidagouda Patil says: May 23, 2017 at 6:22 am

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 18/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

When we create a string object by


using new keyword.. 2 objects created
one in heap.. and another in SCP.
Please con rm and reply back thank
you.
Reply

Aditya(Anna The Great)


October says:
5, 2019 at 2:04 pm

absolutely right
Reply

jayashree says: April 16, 2017 at 9:19 pm

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 di erent objects are created in
heap. please clarify
Reply

Pankaj says: April 17, 2017 at 1:58 am

First statement, 2 objects will be


created, one in pool and then next
one in heap.
Second statement, since “Hello” is
already part of pool only one
object will be created in heap.
Total 3 objects. I hope it’s clear
now.
Reply

TirupathiNovember
Reddy 9,says:
2017 at 6:40 am

Hi ,
According to your answer
just think if it will create two
objects one in heap and one
in pool then what is the use
of intern() method in String.
Reply

Ajeet March
Kumar says:
5, 2018 at 11:26 am

String s1 = “Rakesh”;
String s2 = “Rakesh”;
//s1 and s2 referencing
to same object in Pool
String s3 =
“Rakesh”.intern(); //s1 ,
s2 and s3 referencing to
same object in Pool
String s4 = new
String(“Rakesh”); //s4
creates in Heap and
referencing to same in
Heap
String s5 = new
String(“Rakesh”).intern();
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 19/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

//again s5 referencing to
Literal in Pool so s1, s2,
s3 and s5 are referncing
to same object in Pool
if ( s1 == s2 ){
System.out.println(“s1
and s2 are same”); // 1.
}
if ( s1 == s3 ){
System.out.println(“s1
and s3 are same” ); // 2.
}
if ( s1 == s4 ){
System.out.println(“s1
and s4 are same” ); // 3.
}
if ( s1 == s5 ){
System.out.println(“s1
and s5 are same” ); // 4.
}
will return:
s1 and s2 are same
s1 and s3 are same
s1 and s5 are same
Reply

Javed Khan Siddiqui


June 5, says:
2017 at 10:02 pm

Double Quote work progress:-


—————————–
1) By using double Quote The
String object(Value :- Hello)
2) is created in SCP (If and only if
there is no Value in SCP like Hello
earlier in SCP)
new operator work progress:-
——————————
3) By using ‘new’ operator it will
store String object(Value :- Hello)
4)is created in Heap Memory and
5)is created SCP as well (If and
only if there is no Value in SCP
like Hello earlier in SCP ,
otherwise no use of SCP it is to
provide less space in
memory)********
Now coming to example
(A)
String s1 = new String(“Hello”); //1
String s2 = new String(“Hello”);//2
//1 will create 1 in heap memory
and as well as 1 in SCP because
he found no such value in SCP
//2 will create 1 in heap memory
and when he also going to create
1 in SCP as per process , it
stopped because he found
value(Hello) already there a er
compilation ,
So total = 3
(B)
String s1 = new String(“Hello”); //1
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 20/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

String s2 = new String(“Hello”);//2


String s3 = ‘”Hello”‘;//3
//1 is creating 1 in heap and 1 in
SCP
//2 is creating 1 in heap and 0 in
SCP (because already there a er
executing //1)
//3 is creating 0 in SCP (because
already there a er executing //1)
So total 1+1+1 = 3
(C)
String s1 = ‘”Hello”‘;//1
String s2 = new String(“Hello”); //2
String s3 = new String(“Hello”);//3
String s4 = ‘”Hello”‘;//4
String s5 = ‘s4 //5
//1 is creating 1 in SCP(because
he didn’t nd any thing like this)
//2 is creating 1 in heap memory
but 0 in SCP(Because already
created in //1)
//3 is creating 1 in heap
memorybut 0 in SCP(Because
already created in //1)
//4 is creating 0 in SCP (Because
already created in //1)
//5 this is important … passing
reference…. again 0 means “Hello’
passing to both reference s1 and
s5
So total again 1+1+1 = 3
Reply

bhargav says:
July 16, 2017 at 5:05 am

IF it will create 3 object that


means..
String s1=new String(“Hello”);
String s2=new String(“Hello”);
String s3=”Hello”;
if total 3 object get created
consider s1 will stored in
SCP and if i compared
s1==s3 it should be true. if
not then check q5. Only
intern method is responsible
to stored in SCP.
correct me if i am wrong.
Reply

Tirupathi Reddy
November 9, 2017 says:
at 6:45 am

yes it’s correct.


we are going to create
object by using new
operator it will be
created in Heap
memory not in SCP. if
you are going to place
the same object in SCP
then we can use intern()
method.
Reply
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 21/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Ketki Gawande says:April 14, 2017 at 11:01 am


good
Reply

arun says: February 18, 2017 at 10:03 am

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
Reply

sahil mudgal says:


March 23, 2017 at 11:51 pm

Hello arun,
I think the rst two methods for
creating string are optimum .
The 3rd method i.e String.valueOf
(arg a) returns the string
representation of the passed
argument for char,boolean,int and
double. whereas 4th method only
concats two string and creates
another object of String classs.
please correct me if i am wrong.
Reply

Szanowne says: December 30, 2016 at 8:27 am

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.
Reply

Pankaj says:
December 31, 2016 at 11:17 am

Because “Hello” will be rst


created in String Pool, then s1 and
s2.
Reply

Hareesh January
says: 4, 2017 at 10:30 am

We have created string


objects using the new Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 22/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

operator.
String s1 = new
String(“Hello”);
String s2 = new
String(“Hello”);
I am thinking this objects will
store only in Heap. If I am
wrong correct me how
exactly String objects store?.
Reply

Hareesh says:
January 4, 2017 at 7:52 pm

No need answer. I got it.


Thanks
Reply

Harshal
Marchsays:
11, 2017 at 11:47 pm

By using new operator


alwaz 2 objects are
created , one in string
constant and other in
heap
Reply

sachinApril
says:12, 2017 at 7:27 am

i think you are not know


that when we use a
string literal than it
create a new string
object in the string pool
area the object which is
created in string pool
can be reused
Reply

SzanowneJanuary
says:6, 2017 at 1:14 pm

I am confused, as far as I
leant, string created with new
operator goes into heap
memory, NOT in the String
pool. So why in this case an
object is added in String
pool?
I thought that in this case,
the only way to add one of
this objects in the string pool
is using intern(), so smtg like
this:
String s1 = new
String(“Hello”).intern();
Reply

Dushyant
FebruarySheoran says:
17, 2017 at 7:38 am

Using the intern


function does not
explicitly add a String in
the String pool. What
intern() does is that it
assigns the reference
from the String pool if it
is available. So it would Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 23/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

point the object to the


same reference. See
question 5 to clear all
your doubts
Reply

arun says:18, 2017 at 9:27 am


February

(String constant
pool(scp)) in the name
only meaning is there
constant values are
stored in scp.
example String s1=new
String(“hello”);;
hello is constant one
object is created in scp
and new keyword create
another object in heap
area.
if you give String
s1=”arun” ————-
>arun is constant object
created in scp only
String s1=”arun”
String
s2=”arun”______________
________>in this case
only 1 object is created
for s1 and s2.
in scp already same
content exists no object
created
Reply

Javed Khan says:


June 5, 2017 at 10:16 pm
Siddiqui
the new operation only
creates one object.
<<<<<<<<<<>>>>>>
Any time you use a
String literal, you
implicitly create an
object (unless the same
literal was already used
elsewhere). This isn’t
skipped just because
you then use the object
as a parameter for a
new String() operation.
FYI…
String literal internally
call intern method
So new operator work
as 2 object ,
Think logically if new
operator create only 1
then SCP will be empty
So literals has to be
there to provide in SCP ,
that’s why we mostly not
using new operator to
avoid memory
optimization
Reply Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 24/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Sunitha Kristipati November


says: 17, 2016 at 1:46 am

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.?????
Reply

Smruti says:November 21, 2016 at 9:26 pm

s1 and s are referencing the same


object “sun”
Reply

ilavarasan says:28, 2016 at 1:13 am


November

Eventhough it points the


same objects , it returns false
because you are using the ==
operator to compare their
references but not content.
Reply

Raja says: December 13, 2016 at 6:10 am

If You use == Operator that is


Identical Comparsion so.New
Object Will be genearted so that is
Why it return False But They are
Stored in String Constant Pool
only.
Reply

anshu says: January 1, 2017 at 11:44 am

In rst object , your object in


string constant pool is anonymous
, it means object which have not
any reference . next time when
you creating object with same
content then it will not create new
object only it refers earlier object
to new reference a reference and
for making “s1′ to the reference of
sun then you should have to write
code like – s1=s1.intern(); then it
returns true
Reply

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 25/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

arun says: February 18, 2017 at 9:33 am


if u r useing compareing new key
word objects it will compare hash
code
String s1=new String(“arun”) String
s2=new String(“arun”);
new means it create object in
heap area ———- if you use string
literal method object is created in
scp if same contenet is there new
object not created only reference
will store so when u use == the
object ref both same thats why it
will give true
new key word means di erent
objects will created so di erent
ref == compares so it gives false
Reply

Sunitha Kristipati November


says: 17, 2016 at 1:35 am

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 e cient ,then why we also
using ‘new’ ,please explain the
scenarios where we can use them and
main di erentiating point to use them.
Reply

Vimal says: October 16, 2016 at 9:14 pm

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?
Reply

rajesh says:November 18, 2016 at 6:44 am

one object, whc is stored in


constant pool area,zero obj
avai;able for garbage collector
Reply

AtSvm says:
January 15, 2017 at 11:40 am

I think 9 String literals will be


created in given below
sequence:-
“test” , “test2” , “testtest2” ,
“test3”, “testtest2test3” ,
“test4” , “testtest2test3test4”
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 26/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

, “test5” ,
“testtest2test3test4test5”
and str will point to
testtest2test3test4test5 at the
end .
So remaining all 8 literals will
be eligible for Garbage
Collection.
Reply

arun says: February 18, 2017 at 9:38 am

9 objects will create 4 objects for


garbage collection
in scp 5 objects will create
in heap area 4 objects will create
one very imp point is scp area all
object are not eligible for garbage
collection
scp area object are distroyed
when jvm shuddown
so during schudle maintaince
objects will distoryed
scp area objects are not eligible
for garbage collection
Reply

Javed Khan Siddiqui


June 5, says:
2017 at 10:29 pm

String str = “test”;//1


str = str+”test2″;//2
str = str+”test3″;//3
str = str + ”test4″;//4
str = str + “test5”;//5
//1 1 in SCP = test
total object till now one with value
—– “test”
and now str is refering to “test”
//2 1 in SCP = testtest2
total object till now two with value
—– “test” , “testtest2”
and now str which was refering to
“test” start referering to
“testtest2”
//3 1 in SCP = testtest2test3
total object till now three with
value —– “test” , “testtest2” ,
“testtest2test3”
and now str which was refering to
“testtest2” start referering to
“testtest2test3”
//4 1 in SCP = testtest2test3test4
total object till now four with value
—– “test” , “testtest2” ,
“testtest2test3” ,
“testtest2test3test4”
and now str which was refering to
“testtest2test3” start referering to
“testtest2test3test4”
//5 1 in SCP =
testtest2test3test4test5
total object till now four with value
—– “test” , “testtest2” , Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 27/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

“testtest2test3” ,
“testtest2test3test4” ,
“testtest2test3test4test5”
and now str which was refering to
“testtest2test3test4” start
referering to
“testtest2test3test4test5”
So if you put S.O.P(str) =
testtest2test3test4test5
and check how many “” object are
there
test
testtest2
testtest2test3
testtest2test3test4
testtest2test3test4test5
=== Fiveeeeeeeeeeeeee
Reply

shailesh says: September 29, 2016 at 12:33 pm

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.hashC
ode());
System.out.println(“hash2=”+str2.hashC
ode());
System.out.println(“hash3=”+str3.hashC
ode());
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?
Reply

Pankaj says:
September 30, 2016 at 12:09 am

str1 and str2 points to two


di erent String objects, hence ==
is false.
Reply

Abhi says: August 11, 2016 at 4:37 am

Could you please add some details


about hashcode() and equals operator Previous Next 
in String class

https://www.journaldev.com/1321/java-string-interview-questions-and-answers 28/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Reply

Srinivas says: August 10, 2016 at 9:00 am

Stringbu er sb=new Stringbu er(“ab”);


Stringbu er sb1=new
Stringbu er(“ab”);
syso(sb==sb1);
O/P ?
Reply

Ujjwal says: August 14, 2016 at 2:11 pm

False
Reply

siva ranjan says:


November 7, 2016 at 7:50 pm

false
Reply

anshu says: January 1, 2017 at 11:53 am

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.
Reply

GAURAV PANT says: July 5, 2016 at 10:21 am

Hi Pankaj,
In di erent 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
Reply

Pankaj says: July 5, 2016 at 12:02 pm

“Hello” in the String constructor


argument will be created rst in
the Pool, since it’s a string literal.
Then s1 will be created in the
heap.
Reply

GAURAV PANT
July 5,says:
2016 at 11:21 pm
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 29/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

So whenever we are creating


string using “new” operator,
JVM is storing the string into
the String Pool also?
Reply

Pankaj July
says:6, 2016 at 9:15 am

It is because you are


also providing string
literal in double quotes
as constructor
argument. So Yes, if
there is not a string with
same value in the pool.
No, if a string with same
value exists in the pool.
Reply

arun says: February 18, 2017 at 9:44 am

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
Reply

Jigar says: July 1, 2016 at 3:13 am

How many object will create?


String str1 = new String(“abc”);
String str2 = new String(“xyz”);
Reply

Ankita says: July 5, 2016 at 5:10 am

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
di erent for both str1 and str2
hence “abc”,”xyz” string from
string pool is not reused.
Reply

arun says:
February 18, 2017 at 9:47 am

yes it is correct
Reply

Ajay Dwivedi says: March 10, 2016 at 11:37 am

Di erence between String, StringBu er


and StringBuilder?
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 30/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Ans : So when multiple threads are


working on same String, we should use
StringBu er 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
StringBu er.
Reply

Pankaj says: March 10, 2016 at 8:25 pm

The given answer is correct.


StringBu er is thread safe, not
StringBuilder.
Reply

chandini says:
March 20, 2017 at 3:52 am

Strings are immutable(we


cant modify once created).
These are thread safe and
uses more memory.
StringBu er : Theses are
mutable(modifyable) . the
objects created using
StringBu er are stored in
heap.Methods under
StringBu er class are
Synchronized so these are
thread safe.Due to this it
does not allow two threads to
simultaneously access the
same method . Each method
can be accessed by one
thread at a time .
StringBuilder : StringBuilder
are similar to StringBu er but
the only di erence is they
are not Thread safe
Reply

Vijay says: March 5, 2016 at 12:53 am

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”
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 31/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

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..
Reply

Puneet SrivastavaJune
says:
8, 2016 at 9:35 pm

whenever you write any string in


double quotes it automatically
creates an object of string in
string pool.
Reply

Ashutosh says: February 17, 2016 at 1:00 pm

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 nd any satisfactory
answer or logic?
I hope you will reply. Thanks- Your’s
Reader .
Reply

Pankaj says:February 19, 2016 at 11:49 am

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.
Reply

Pankaj Verma says:


June 2, 2016 at 6:28 am

1. String s1 = new
String(“Hello”);
2. String s2 = new
String(“Hello”);
Answer is 3.
Then how three object
created here.
I am very confused here.
According to you when you
create String through new
Keyword it will create two
object one is on constant
pool and another one is on
heap.please correct me if am
wrong.
Reply

Pankaj June
says:
2, 2016 at 7:16 am

“Hello” object in pool,


Previous Next 
then s1 and s2 in heap

https://www.journaldev.com/1321/java-string-interview-questions-and-answers 32/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

memory. Total 3 objects,


i hope it clari es your
doubt.
Reply

Pankaj says:
June 19, 2016 at 1:39 am
Verma
Thanks Pankaj for
the reply it really
help.

Navneet says:
July 1, 2016 at 3:54 am

How will “Hello” go


in pool? We have
not used intern()
method here….Am I
missing anypoint
here?

Mandeep says:
July 24, 2016 at 1:35 am

without calling
intern() method
how can Hello can
be stored in pool.

chandini says:
March 20, 2017 at 4:01 am

How will “Hello” go


in pool? We have
not used intern()
method here….Am I
missing anypoint
here?
For the above
question(as of i
know)–>
in java Anything we
write between
double quotes is a
compile time
constant and it will
be moved into the
String pool.
String s1 = new
String(“Hello”);
“Hello” will be
compiled(because
it is inside double
quotes) and thus
will be added to
the String
constants pool for
the current JVM at
compile time.
and the value of
“s1′ will be
resolved at run-
time and will be
added to the heap
during run-time.

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 33/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

raju says: June 14, 2016 at 11:12 pm


when we create string object
using new keyword two
objects will be created one is
in heap and onother one is
scp(string constant pool) . if
u creating another object
with same content like above
that time only aboject will be
created in heap but not scp.
bxz in scp duplicate not
allowed
Reply

Hareesh says:
January 4, 2017 at 7:35 pm

Thanks Raju.
Reply

Sundara Baskaran February


says: 6, 2016 at 5:06 pm

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?
Reply

dilli says: February 8, 2016 at 1:12 am

Equals() method always compares


contents of the strings.
Reply

Amit says: March 17, 2016 at 4:05 am

because equals method in String


class is overridden.
Reply

mani_v says: December 19, 2015 at 6:43 pm

Hii pankaj,
Your articles are super, rst i tq u to ur
thinking like to make it all useful info
into one place.
Reply

Ravi says: December 12, 2015 at 11:19 am

It is tremendously written thanks for


such great explanation .. Keep writing
we will hope for more and more
concept
Reply

Pankaj says:
December 12, 2015 at 11:15 pm

Thanks Ravi, we are determined to


write best articles. You should
also subscribe to our newsletter
where we send exclusive tips and
free eBooks.
Reply

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 34/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

PraveenDecember
Kumar 17, 2015 at 7:42 am
says:
Hi ,
I am a great fan of your
articles. It would be awesome
if you could integrate disqus
in your blog for comments. I
have a little doubt regarding
strings in java. Can you tell
me how many objects are
created in these two lines of
code ?
StringBuilder sb = new
StringBuilder(“abc”);
sb.append(“def”);
Kindly mail me if possible.
Thanks a lot.
Reply

Hareesh says:
January 4, 2017 at 7:44 pm

Hi Praveen,
StringBu er is
immutable.
at this line StringBuilder
sb = new
StringBuilder(“abc”); —
>one object created
sb.append(“def”); —-
>you are trying to
change content. so
existing object goes for
GC and a new object
created with “abcdef”
Reply

Vishnu says:
March 25, 2017 at 7:58 am
Prasad
Hi Hareesh..
You are wrong.
StringBuilder is
Mutable .
If you create
StringBuilder
sb=new
StringBuilder(“abc”
); then only one
object will be
created..and if you
are try to modify
StringBuilder
Object then new
object are not
create.Only modify
on that object..
Because
StringBuilder
capacity is
ByDefault 16.and
It’s Mutable
StringBuilder sb =
new
StringBuilder(“abc”
);
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 35/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

System.out.println(
sb.capacity());// 16
For Example-
StringBuilder sb =
new
StringBuilder(“abc”
);
System.out.println(
sb.capacity());//19
=> 3 abc+16 default
System.out.println(
sb.length());//3
sb.append(“def”);
System.out.println(
sb.capacity());//19
System.out.println(
sb.length());//6
If Default capacity
is full then JVM will
create a new
Object ..
sb.append(“I self
Vishnu”);
System.out.println(
sb.capacity());//19
System.out.println(
sb.length());//19
Hear Default
capacity is full
again if you try to
modify then JVM
will create new
Object
and copy all data
of previous Object
a er then destroy
the previous
Object
like :formula of
New Object
Capacity:
New Capacity=
(Initial
Capacity*2)+2
=(19*2)+2
=38+2=40
Ex:
sb.append(“Prasad
”);
System.out.println(
sb.capacity());//40
System.out.println(
sb.length());//25
If you De ne our
own capacity then
Create the
StringBuilder
Object to Following
way..
StringBilder(int
Initial Capacity);
Ex:=>
Previous Next 
StringBuilder

https://www.journaldev.com/1321/java-string-interview-questions-and-answers 36/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

sb1=new
StringBuilder(100);
System.out.println(
sb1.capacity());
//100
System.out.println(
sb1.length()); //0

Walter Frobin Ekka says: 10, 2015 at 8:17 am


November

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 con icting to me.
Reply

Pankaj says:
November 11, 2015 at 10:28 pm

Strings are stored in String Pool as


plain text and have longer life,
anybody having access to memory
dump can nd 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.
Reply

ARVIND AGGARWAL says:6, 2015 at 9:05 pm


November

Hey Pankaj…..
Where is comparison operator in
Question 1 for which U R saying that
don’t confuse with that?
Reply

Senthil Narayanan August


says: 11, 2015 at 10:51 am

Very helpful…. thanks pankaj:)


Reply

shank's says:October 4, 2015 at 11:45 am

deep approach in string…..its


really helpful
Reply

irfan says: July 29, 2015 at 4:07 pm

Amazing work Pankaj… keep up the


good work…I have been a regular visitor
of your site and posts.
Reply

maitrey says: July 12, 2015 at 1:55 am

Dear sir,
I have one basic question.
Why java supports both features of
string string creation.
String str=”abc”; Previous Next 
String strObj=new String(“abc”);
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 37/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

str=”abc” is better than new String().


So why Java supports new String();
Reply

Chetan says:
September 23, 2015 at 12:59 pm

I am also having the same


question. Recently interviewer
asked this to me that what is the
signi cance of string object
creation with new keyword. If you
have any thoughts then please
add it
Reply

ashishNovember
says: 20, 2015 at 10:23 pm

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 e cient compared
to String strObj=new
String(“abc”);
Reply

Ashutosh says:
February 17, 2016 at 1:09 pm

Only designer of Java can give


you more speci c 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
Reply

Ashutosh says:17, 2016 at 1:20 pm


February

one more point is on why to


create string using new
keyword, you can use
di erent constructors to
create a string.
For example:
creating string by char array
creating string for speci c
encoding etc.
Reply

srikanth says: May 31, 2015 at 12:03 am

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 ?
Reply
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 38/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Pankaj says: May 31, 2015 at 12:30 am

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.
Reply

Lukman says: March 23, 2015 at 10:49 pm

Hi Pankaj,
Very useful work………
keep it up…
Reply

ram says: March 18, 2015 at 7:43 am

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
Reply

siddharth says:
September 9, 2015 at 5:02 am

use trim() method when need


spaces
Reply

siddharth says: 9, 2015 at 5:03 am


September

sorry use append(” “);


method
Reply

Hareesh says: January 4, 2017 at 8:00 pm

search in GOOGLE with below


words:
how to trim a string in java
Reply

amar says: January 16, 2015 at 5:59 am

How to Print source code as output in


java??
Reply

amar says: January 16, 2015 at 5:55 am

hi..
How to print program source code as
output in java language..?
Reply

arun says: December 25, 2014 at 10:43 pm

hi I have one small doubt which data


type is used to check whether the
given string student is present or
absent
Reply

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 39/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Sarita says: October 2, 2014 at 12:31 am

Hi pankaj,
I have a question in string permutation?
for example: Input: sarita
key :ri
the out put should be :sarita, sarIta,
saRita, saRIta
Reply

Sanjana says: September 30, 2014 at 10:35 pm

Hi,
I need a solution for this
Consider String str1 = “hari”;
String str2 = “malar”;
now nd the same characters in both
the string and delete the repeated
characters
So, the output must be
str1 = hi
str2 = mla
Reply

sudhakar says: September 22, 2014 at 2:03 am

can you expalin about thread in real


time?
Reply

Ishan Aggarwal says:


September 20, 2014 at 6:09 am

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
Reply

Pankaj says:
September 20, 2014 at 10:36 am

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.
Reply

vallabhiSeptember
says: 25, 2014 at 2:20 am

Hi Pankaj
Thanks for these wonderful
questions
I have a doubt that if we can
create objects through String
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 40/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

literals than why do we use


creating string objects
through new keyword as it is
not memory e cient way. Is
it possible to completely
remove the feature of
creating String objects
through new keyword..Please
Explain
Reply

Pankaj says:
September 25, 2014 at 2:55 am

Since String is an
Object and we can use
new operator to
instantiate it. It’s not
possible to remove this
option.
Reply

vallabhi
September says:
25, 2014 at 5:42 am

Thanks for the


reply.. But the
question is that is
there any situation
where we can only
use String Object
with new keyword
instead of String
literal. Actually an
interviewer asked
me the question
that when String
literal is memory
e cient than why
do we create
object in string
using new
keyword..

Ruchi Gupta
September says:
29, 2014 at 5:12 am

Strings created in pool


are not garbage
collected.
Please correct me
Pankaj if i am wrong.
Reply

chandini says:
March 20, 2017 at 4:24 am

I hope those
strings will be
there as long as
their scope

Anoop December
says: 17, 2014 at 3:26 am

If the references were


de ned as instance
variables, they are created in
the heap memory.
Reply
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 41/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

aditya says: October 16, 2014 at 10:26 am

Only two objects will be created …


one objects for String s1 = “abc”
and another for new String(“abc”)
Reply

Dhruba Jyoti Talukdar


December says:
21, 2014 at 11:01 am

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
Reply

Ruchi Gupta says:


September 11, 2014 at 6:28 am

public void testFinally(){


System.out.println(setOne().toString());
}
protected String setOne(){
String s1=new String();
try{
s1.concat(“Cool”);
return s1=s1.concat(“Return”);
} nally{
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”.
Reply

Pankaj says:
September 11, 2014 at 11:09 pm

The point to remember is that


String is immutable, so in
s1.concat(“Cool”); line, a new
String is created but since you
Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 42/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

didn’t assigned it, it’s lost. s1 value


is still “”.
s1=s1.concat(“Return”); : here
you are assigning a er concat, so
s1 is “return” now, hence the
output.
Reply

rose says: September 19, 2014 at 2:12 am

String is Immutable ,whenever we


are adding anything using concat
method it points new ref a er
concatination if string not
modi ed 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.
Reply

Harikrishna says: May 28, 2014 at 3:24 am

String is not nal by default since you


have mentioned “String immutable and
nal in java”?
Reply

Pankaj says: May 28, 2014 at 9:09 am

String is a nal class and


immutable too.
Reply

RajeshSeptember
says: 24, 2014 at 11:40 am

not satis ed…..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
Reply

Pankaj says:
September 25, 2014 at 1:19 am

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.
Reply

Anshul says:
November 14, 2014 at 9:27 am Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 43/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

lol….pankaj is saying
String class is declared
nal in JDK source code
dumbo…
nal class String {} in
JDK
Reply

Hareesh says:
January 4, 2017 at 9:42 pm

whatever Pankaj said


that is True.
String s1 = “hello”; –>
new object created
System.out.println(s1.to
UpperCase()); –>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.
Reply

saurabh moghe says:May 21, 2014 at 10:44 pm

Hi ,
in answer of ‘What are di erent 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
‘http://www.coderanch.com/t/245707/ja
va-programmer-
SCJP/certi cation/String-object-
created’
(http://www.coderanch.com/t/245707/ja
va-programmer-
SCJP/certi cation/String-object-
created%27) .. please elaborate this
string concept
Reply

Gary says: April 18, 2014 at 1:05 pm

Very helpful, just wanted to say that I


appreciate the clarity with which the
answers are presented.
Reply

ADITYA VALLURU says:


April 8, 2014 at 5:30 pm
Previous Next 
Hi Pankaj,

https://www.journaldev.com/1321/java-string-interview-questions-and-answers 44/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

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
di erent manner. Expecting more like
this from you. I will be in touch with you
a er this. I met this site rst time.
Reply

Pankaj says: April 8, 2014 at 7:46 pm

Thanks Aditya, please look into


other posts too. I am sure you nd
a lot of good stu s. 🙂
Reply

kiki says: March 29, 2014 at 4:13 pm

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
Reply

Ashi says: February 18, 2014 at 2:57 pm

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?
Reply

senthil hari says: December 9, 2013 at 2:15 pm

Hi pankaj,
Thanks a lot for providing examples
and good explanations.if you have stu
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
Reply

devs says: November 5, 2013 at 11:26 am

All your tutorials are great. Helping me


in my job jump. Thanks a lot.
Reply

nilesh shinde says: July 6, 2013 at 4:35 pm

a er 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
Previous Next 
Reply
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 45/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Pankaj says: July 7, 2013 at 6:47 am

Thanks Nilesh, it really feels good


that my articles are helping and
cleared your doubts.
Reply

dinesh says:
February 3, 2014 at 6:03 am

its really good and useful…try


to post some typical and
tricky programs on strings
which will be helpful for
interviews and thanks……
Reply

Trilochan says: June 27, 2013 at 10:49 am

really this material is gud. de nitely it


will help a lot 2 give a good concept in
string…
Reply

Pankaj says: July 7, 2013 at 6:48 am

Thanks for liking it.


Reply

tamil says: August 15, 2013 at 2:09 pm

sir pls clearly explain the java in


string concept
Reply

Pankaj says:
August 15, 2013 at 8:43 pm

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- nal-in-java
https://www.journaldev.com/
797/what-is-java-string-pool
Reply

nandan says: June 24, 2013 at 7:58 pm

Hi pankaj ,
your stu 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!!!
Reply

Pankaj says: July 7, 2013 at 6:48 am

Thanks Nandan for kind words. It’s


these appreciations that helps me Previous Next 
keep going.
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 46/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Reply

aicotutorial.com says:June 1, 2013 at 3:37 pm

Thanks for nally talking about > Java


String Interview Questions
and Answers | JournalDev < Loved it!
Reply

Prosenjit says: May 3, 2013 at 1:24 am

Nice Material….
Keep it up to make us knowledgeable..
Reply

Ravi says: April 16, 2013 at 1:10 pm

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.
Reply

Pankaj says: July 7, 2013 at 7:02 am

Thanks Ravi, yes you are right.


Corrected the post.
Reply

Amit Malik says:


September 10, 2013 at 4:46 am

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 Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 47/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

be created on the heap.


Since s1 and s2 are referring
to di erent objects s1 == s2
will return false.
If we want s1 to refer object
created on the pool then use
s1.intern().
Reply

Pankaj says:
September 10, 2013 at 5:34 pm

Thats what is mentioned


here…
Reply

deepak
August says:
31, 2016 at 11:20 pm

please explain why


intern() is needed if
the object will be
created in both
constant pool and
heap when we use
new operator.

deepak says: August 31, 2016 at 11:18 pm

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.?
Reply

Rhicha January
says: 13, 2019 at 10:26 pm

I have the exactly same


question
Reply

Ayan says: February 1, 2013 at 7:17 am

Can you please explain the statement


“Strings are immutable, so we can’t
change it’s value in program. ” by a
sample program
Reply

Pankaj says: February 2, 2013 at 10:55 pm

String str = "abc";


str = "xyz"; // here the value
of Object str is not changed, a
new String literal "xyz" is Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 48/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

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
Reply

siddu says:
October 13, 2013 at 7:49 pm

String s1=new String(“Hello”)


above code How many
objects will create?
Reply

Deepak Chauhan
November 14, 2013 at says:
6:28 pm

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
ne. 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..
Reply

Paramjeet says:
September 13, 2014 at 11:55 pm
Singh
String s=new
String(“Deepak”);
when u have create
a String object by
using new keword
than every time Previous Next 
create new object
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 49/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

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

Leave a Reply
Your email address will not be published.
Required elds are marked *

Comment

Name * Email *

Post Comment

Previous Next 
https://www.journaldev.com/1321/java-string-interview-questions-and-answers 50/51
11/22/2019 Java String Interview Questions and Answers - JournalDev

Newsletter for You

Enter your email address here... 

Most Popular Favorite Sites

JournalDev is one of the most


popular websites for Java, Python, Java / Java EE Java SE
Tutorials
Android, and related technical
articles. Our tutorials are regularly Spring.io
Core Java Tutorial
updated, error-free, and complete.
Every month millions of developers Python.org
like you visit JournalDev to read our Python Tutorials

tutorials. Mkyong
Java Interview
JournalDev was founded by Pankaj Questions
Python Tutorials
Kumar in 2010 to share his
experience and learnings with the Core Java Interview
Questions JavaString
whole world. He loves Open source
technologies and writing on
Java Design Patterns Resources
JournalDev has become his passion.

Spring Tutorial

© 2019 · Privacy Policy · Contact Us · About Me · Powered by WordPress

https://www.journaldev.com/1321/java-string-interview-questions-and-answers 51/51

You might also like