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.
Here is the link that opens in a new tab: Java String Quiz
Java String Interview Questions
- What is String in Java? String is a data type?
- What are different ways to create String Object?
- Write a method to check if input String is Palindrome?
- Write a method that will remove given character from the String?
- How can we make String upper case or lower case?
- What is String subSequence method?
- How to compare two Strings in java program?
- How to convert String to char and vice versa?
- How to convert String to byte array and vice versa?
- Can we use String in switch case?
- Write a program to print all permutations of String?
- Write a function to find out longest palindrome in a given string?
- Difference between String, StringBuffer and StringBuilder?
- Why String is immutable or final in Java
- How to Split String in java?
- Why Char array is preferred over String for storing password?
- How do you check if two Strings are equal in Java?
- What is String Pool?
- What does String intern() method do?
- Does String is thread-safe in Java?
- Why String is popular HashMap key in Java?
- String Programming Questions
What is String in Java? String is a data type?
String is a Class in java and defined 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 final 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 different 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, StringBuffer 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 find 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 we can use to check if String is palindrome or not.
private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}
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 find out if it’s palindrome or not.
private static boolean isPalindromeString(String str) {
if (str == null)
return false;
int length = str.length();
System.out.println(length / 2);
for (int i = 0; i < length / 2; i++) {
if (str.charAt(i) != str.charAt(length - i - 1))
return false;
}
return true;
}
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(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}
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?
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 first 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 flow for Strings, you can use if-else conditions and you 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 find 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 find all permutations of String.
Write a function to find out longest palindrome in a given string?
A String can contain palindrome strings in it and to find longest palindrome in given String is a programming question.
Check this post for complete program to find longest palindrome in a String.
Difference between String, StringBuffer and StringBuilder?
The string is immutable and final 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 – StringBuffer and StringBuilder.
StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So in a multi-threaded environment, we should use StringBuffer but in the single-threaded environment, we should use StringBuilder.
StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.
Check this post for extensive details about String vs StringBuffer vs StringBuilder.
Read this post for benchmarking of StringBuffer vs StringBuilder.
Why String is immutable or final in Java
There are several benefits of String because it’s immutable and final.
- String Pool is possible because String is immutable in java.
- 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 find 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 ? "+(s1==s2)); //true
System.out.println("s1 == s3 ? "+(s1==s3)); //false
System.out.println("s1 equals s3 ? "+(s1.equals(s3))); //true
What is String Pool?
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
- What is the output of below program?
package com.journaldev.strings; public class StringTest { public static void main(String[] args) { String s1 = new String("pankaj"); String s2 = new String("PANKAJ"); System.out.println(s1 = s2); } }
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.
- What is the output of below program?
package com.journaldev.strings; public class Test { public void foo(String s) { System.out.println("String"); } public void foo(StringBuffer sb){ System.out.println("StringBuffer"); } public static void main(String[] args) { new Test().foo(null); } }
The above program will not compile with error as “The method foo(String) is ambiguous for the type Test”. For complete clarification read Understanding the method X is ambiguous for the type Y error.
- 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 different reference. If we create them using double quotes, then they will be part of string pool and it will print true.
- 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 find a check using instanceof operator to check if the type of passed object is String? If not, then return false.
- 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 different reference. If we change the code in line 3 to
s2 = s2.intern();
then output will be true. - 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.
Thnxs, PankaJ!
Very useful! 👍
Hello
I am not able to find compareToIgnoreCase() method in Comparable interface
How many objects will be created for both line and why?
String str1 = “one”.concat(“two”).concat(“three”); //line #1
String str1 = str1 + “ABC”+”XYZ” //line #2
Hi Panakj,
Good Collection on String.
I have a question as below.
When we create a String object with any method or you can say approach. Than we mention that JVM will check that the particular String is already exists in String Pool or not.
My question is that how JVM will compare this string with string pool data. Which function use by JVM for the comparison.
Hi Pankaj,
First of all, really great work posting these interview Q&A for the core concepts.
I think a correction is needed in Q# 2, as you said when we use new operator, it doesn’t get stored in pool but that’s contradicting your last practical example where you said there would be three strings. And i think the latter is correct. And it does store in pool in case its not there already. Please correct me if am wrong.
When we use new operator, the string gets created in the heap area. Since we are providing string literal argument, that argument first gets created in the string pool area.
String s = new String(“Java”);
This will create two string objects – “s” in the heap area and “Java” argument string in the pool area.
Thanks for the explanation, Pankaj.
That being said, maybe Q# 2 can be corrected as:
> If a string object is created and initialized in a single statement using new() operator then it stores that initialized object instance in string pool and the object itself gets store in heap memory too, thus creating two instances.
> If a string object is created but not initialized(refer below) using new() operator, then the object is just stored in heap memory.
String s = new String(); – – created but not initialized with a string literal
Again, please correct me if i am missing something here.
But as you explained intren() is used to push the string to string pool. In your above question 6 only strings are intialized using new operator and no intern method is called. Then we say that there are three objects created here.
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
Read this tutorial:
https://www.javastring.net/java/string/java-string-intern-method-example
This is some great work! Thanks for sharing.
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously but in diffrence you mentioned opposite StringBuilder is used for multi threaded application not StringBuffer
Hi Pankaj,
Good collection on Strings. Appreciate your efforts. I have only one doubt on String pool. Your statements regarding the below question is contradictory.
What are different ways to create String Object?
String str = new String(“abc”);
String str1 = “abc”;
When we create a String using double quotes, JVM looks in the String pool to find 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.
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 first, 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 string reference you are getting is present in the heap area.
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.
Method removeChar will not work if c is special reg exp character (e.g. ‘.’, ‘[‘). String.replaceAll takes regexp as first parameter. You need to use String.replace instead of String.replaceAll.
sir please explain about trim() function in strings
Hii surya
trim() function is method of spring which eliminate spaces before the string and spaces after 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
Hi Dharmendra,
the above example, you didn’t assigned again to str1 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
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;
}
‘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
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
The argument in String constructor is first created in Pool, you missed to count this one.
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
Ha ha ha, did you even read the question? What you have posted in the comment is totally different. Please clear your concepts before posting such a harsh comment.
How many objects is created in following code?
String a1=”hello”;
String a2=”hello”;
String a3=new String(“hello”);
Two, first a1 in string pool, then a3 in heap.
case : 1
String a1=”hello”;
String a2=”hello”;
String a3=new String(“hello”);
as per pankaj’s comment: 2 objects will be created (first a1 in string pool, then a3 in heap.)
so according to the above result,if we consider below 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 ..
thanks ,
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.
1
It feels good after go thru these Q&A. Thanks bro.
String s1=new String(“abc”).intern();
String s2=”abc”;
How many objects will be created here ?
2 objects
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
1,
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.
2 objects because S2 is created on second line thus s1 wont find 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
2 objects.
first 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 after 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
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 .
Awesome collection of question keeps it Up Good work.
for interview point of view String is a most important topic.
thank you to share this knowlge.
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
it will store or create new object in heap memory but literal “hello” will be in string pool .
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)
when we create string object with the new operator , at that time “HELLO” first get in string pool, if it is already in string pool then it will not go in pool, after that the new line will execute and create one object in heap.
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 ?
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.
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.
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.
absolutely right
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
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.
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.
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(); //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
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 after compilation ,
So total = 3
(B)
String s1 = new String(“Hello”); //1
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 after executing //1)
//3 is creating 0 in SCP (because already there after 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 find 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
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.
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.
good
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
Hello arun,
I think the first 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.
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.
Because “Hello” will be first created in String Pool, then s1 and s2.
We have created string objects using the new 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?.
No need answer. I got it. Thanks
By using new operator alwaz 2 objects are created , one in string constant and other in heap
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
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();
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 point the object to the same reference. See question 5 to clear all your doubts
(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
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
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.?????
s1 and s are referencing the same object “sun”
Eventhough it points the same objects , it returns false because you are using the == operator to compare their references but not content.
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.
In first 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
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 different objects will created so different ref == compares so it gives false
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.
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?
one object, whc is stored in constant pool area,zero obj avai;able for garbage collector
I think 9 String literals will be created in given below sequence:-
“test” , “test2” , “testtest2” , “test3”, “testtest2test3” , “test4” , “testtest2test3test4” , “test5” , “testtest2test3test4test5”
and str will point to testtest2test3test4test5 at the end .
So remaining all 8 literals will be eligible for Garbage Collection.
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
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” , “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
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?
str1 and str2 points to two different String objects, hence == is false.
Could you please add some details about hashcode() and equals operator in String class
Stringbuffer sb=new Stringbuffer(“ab”);
Stringbuffer sb1=new Stringbuffer(“ab”);
syso(sb==sb1);
O/P ?
False
false
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.
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
“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.
So whenever we are creating string using “new” operator, JVM is storing the string into the String Pool also?
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.
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
How many object will create?
String str1 = new String(“abc”);
String str2 = new String(“xyz”);
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.
yes it is correct
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.
The given answer is correct. StringBuffer is thread safe, not StringBuilder.
Strings are immutable(we cant modify once created). These are thread safe and uses more memory.
StringBuffer : Theses are mutable(modifyable) . the objects created using StringBuffer are stored in heap.Methods under StringBuffer 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 StringBuffer but the only difference is they are not Thread safe
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..
whenever you write any string in double quotes it automatically creates an object of string in string pool.
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 .
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.
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.
“Hello” object in pool, then s1 and s2 in heap memory. Total 3 objects, i hope it clarifies your doubt.
Thanks Pankaj for the reply it really help.
How will “Hello” go in pool? We have not used intern() method here….Am I missing anypoint here?
without calling intern() method how can Hello can be stored in pool.
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.
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
Thanks Raju.
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?
Equals() method always compares contents of the strings.
because equals method in String class is overridden.
Hii pankaj,
Your articles are super,first i tq u to ur thinking like to make it all useful info into one place.
It is tremendously written thanks for such great explanation .. Keep writing we will hope for more and more concept
Thanks Ravi, we are determined to write best articles. You should also subscribe to our newsletter where we send exclusive tips and free eBooks.
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.
Hi Praveen,
StringBuffer 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”
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”);
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 after 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 Define our own capacity then Create the StringBuilder Object to Following way..
StringBilder(int Initial Capacity);
Ex:=>
StringBuilder sb1=new StringBuilder(100);
System.out.println(sb1.capacity()); //100
System.out.println(sb1.length()); //0
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.
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.
Hey Pankaj…..
Where is comparison operator in Question 1 for which U R saying that don’t confuse with that?
Very helpful…. thanks pankaj:)
deep approach in string…..its really helpful
Amazing work Pankaj… keep up the good work…I have been a regular visitor of your site and posts.
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();
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
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”);
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
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.
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 ?
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.
Hi Pankaj,
Very useful work………
keep it up…
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
use trim() method when need spaces
sorry use append(” “); method
search in GOOGLE with below words:
how to trim a string in java
How to Print source code as output in java??
hi..
How to print program source code as output in java language..?
hi I have one small doubt which data type is used to check whether the given string student is present or absent
Hi pankaj,
I have a question in string permutation?
for example: Input: sarita
key :ri
the out put should be :sarita, sarIta, saRita, saRIta
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
can you expalin about thread in real time?
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
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.
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
Since String is an Object and we can use new operator to instantiate it. It’s not possible to remove this option.
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 efficient than why do we create object in string using new keyword..
Strings created in pool are not garbage collected.
Please correct me Pankaj if i am wrong.
I hope those strings will be there as long as their scope
If the references were defined as instance variables, they are created in the heap memory.
Only two objects will be created … one objects for String s1 = “abc” and another for new String(“abc”)
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
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”.
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.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.
String is not final by default since you have mentioned “String immutable and final in java”?
String is a final class and immutable too.
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
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.
lol….pankaj is saying String class is declared final in JDK source code dumbo…
final class String {} in JDK
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.
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%27) .. please elaborate this string concept
Very helpful, just wanted to say that I appreciate the clarity with which the answers are presented.
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.
Thanks Aditya, please look into other posts too. I am sure you find a lot of good stuffs. 🙂
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
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?
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
All your tutorials are great. Helping me in my job jump. Thanks a lot.
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
Thanks Nilesh, it really feels good that my articles are helping and cleared your doubts.
its really good and useful…try to post some typical and tricky programs on strings which will be helpful for interviews and thanks……
really this material is gud. definitely it will help a lot 2 give a good concept in string…
Thanks for liking it.
sir pls clearly explain the java in string concept
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
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!!!
Thanks Nandan for kind words. It’s these appreciations that helps me keep going.
Thanks for finally talking about > Java String Interview Questions
and Answers | JournalDev < Loved it!
Nice Material….
Keep it up to make us knowledgeable..
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.
Thanks Ravi, yes you are right. Corrected the post.
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().
Thats what is mentioned here…
please explain why intern() is needed if the object will be created in both constant pool and heap when we use new operator.
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.?
I have the exactly same question
Can you please explain the statement “Strings are immutable, so we can’t change it’s value in program. ” by a sample program
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
String s1=new String(“Hello”)
above code How many objects will create?
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..
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