This question already has answers here:
How can a string be initialized using " "?
(10 answers)
Closed 6 years ago.
I am new to stackoverflow which I am finding it very useful, thanks so much for a great community. While I've been understanding about Strings in java, I just wanted to know how are Strings literals source created? I understood most of the concept of Strings in java. It is a special kind of class that is final, I also understood when creating a String literal, an object will be created on the heap and its reference will be in the string constant pool. by using this.
String name = "Manchester";
I also understood that when a string is created using new operator, the reference will have the object on the heap and a reference in the string constant pool. By this way.
String name = new String("United");
As I did understand how the object was created on the heap using the new operator, what I didnt understand is how the object is created on the heap when we use double quotes " ". How is this accomplished? I went thought the source code of String.class too but it wasn't of any help for me.
Can anyone please let me know how this works? Thanks.
String name = "Manchester";
will search in constant pool of string(in heap) for the same valued object and if found will use that, if not will do this :
String name = new String("Manchester");
Do note that String is immutable, so it tries to use already present objects rater than creating one.
You can check it in this way:
String x = "a";
String y = "a";
x==y //true
And
String x = new String("a");
String y = new String("a");
x==y //false
Related
This question already has answers here:
Java String Immutability and Using same string value to create a new string
(4 answers)
Closed 7 years ago.
i know Strings are immutable in java and i just read some theory about it
Once a String is declared it cannot be changed . i declared a String and changed it's value just by appending some value to it . it should not have happened
String s = "amol";
s = s + "abc";
System.out.println(s); //output is amolabc
The String s didn't get changed. When you did s + "abc", it created a new String object with the result of the operation.
You need to understand the concept of String Pool in Java. Please go through the link
http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html
You are right that Strings are immutable. Here, You didn't change the String s. All distinct Strings are stored in the Heap Memory. So, all the variables (say 10 variables ) containing the same String (say "Hello" ) will occupy only 5 bytes of memory. They all will point to the same location. Separate instances will not be stored for each of those variables.
Here, when you write s = s + "abc", a new string "amolabc" is created in the heap,and now the variable s just points to the new string in the heap. You didn't modify the value of "amol". You just made a new String.
The meaning of immutable is not like you thought to be.Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used.
here you are appending another string value to it,which can be done.But you cannot concatenate with another string.
By appending it is creating another string.
Refer here
This question already has answers here:
String s = new String("xyz"). How many objects has been made after this line of code execute?
(21 answers)
Closed 7 years ago.
I was going through SCJP examination and found one line in one book.
String s = new String("abc");
And it was written that, two objects will be created on above line. one on HEAP and one on STRING POOL.
I am not satisfied by the declaration given there. Can someone make me understand why two objects are created ?
Thanks in advance.
Author is correct. When ever you used String literal, that literal goes to constant pool first.
Hence "abc" created in constant pool.
And when you use new key word a new Object called s created on heap.
The literal "abc" is created and interned ("string pool").
The new operator will create a new String that is not interned.
Author is correct:
one object will be created in the string pool for "abc" literal; and
another object will be created on the heap for new String(...)
Object 1 - "abc"
Object 2 - new String("abc")
This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
Closed 7 years ago.
String s = new String("abc")
I know that this would create a new String object in Heap.
But i am confused about a statement in SCJP book by Kathy Sierra.
It states that the above statement would create an object in heap and at the same if the String "abc" is not present in the String pool , it would also add "abc" to the String pool.
Could anyone please tell me if the object "abc" is also created in the String pool in the above case.
String s = new String("abc")
Yes,above line will create two objects, one in string pool and other in Heap.
So, now
1) If you create a string literal like:-
String s1="abc"; //abc value will be taken from string pool which is previously added
2) If you create a String object and call intern method, no new object will be created instead it will just refer to "abc" present in string pool.
String s2=new String("abc").intern();
Note: When we are creating new String object based on existing one, it reuses char[] value.
Since new String(someStringValue) creates an exact copy of existing string and strings are immutable, there is clearly no reason for the two to exist at the same time.
Even if you have two String objects, they might still point to the same content.
You can refer this:- https://dzone.com/articles/string-memory-internals
Yes, it will be created as you are not having the same string before this line in your code. Now consider this example.
String temp = "abc"; // line1
String s = new String("abc"); // line2
In this case "abc" is not recreated. s will point to "abc" that was created at line 1.
sujith in comment : But in that case i do not see any difference between String temp ="abc" and String temp = new String("abc").
In line 1 a new "abc" will be created in heap. And a new String object will be created and added into the stack. And in line2 a new object of String will be created which will be referring to the "abc" that was created at line1 in heap. To better understand what thing goes to stack and what goes to heap visit here.
Yes it does. To optimize memory use, it does so.
In case you create another variable with same value "abc",
new variable will still point to earlier rather than creating a new one.
Somehow it is trying not to create two equal objects
This question already has answers here:
Difference between string object and string literal [duplicate]
(13 answers)
What is the difference between "text" and new String("text")?
(13 answers)
Closed 8 years ago.
I attended interview and i was asked this question.
String s=new String("Rohit");
Does this statement creates an object in heap only or it makes an entry in string pool as well?
I answered it does not make entry in pool. I think with .intern() it would make entry in string pool. Interviewer's thought was opposite.
Could you please guide me if i was wrong or interviewer?
Thanks in Advance.
EDIT:
String s1=new String("Rohit");
String s2="Rohit";
String s3=new String("Rohit").intern();
System.out.println(" "+(s2==s3)+" "+(s1==s2)+" "+(s1==s3)+" "+(s2==s3));
results as :true false false true
This makes me to think that without using intern() with new, there is no entry in pool for this object
Several things wrong with what you say he said:
First, doing new String always returns a new string, and never one that is interned.
Second, while it is true that the presence of the string literal "Rohit" might cause a String of that value to be "interned" (what is erroneously referred to as placing in the "string pool" or "string constant pool"), that would be done (if it was done) when the class was loaded, not when the statement was executed.
Third, since there can only ever be one copy of a String with a given pattern in the interned string table, even loading the class is not guaranteed to add a new entry, since one might already be there.
Of course, as is often the case, there may have been some misunderstanding on the part of one or both of you, or the question (or your answer) may have been poorly/unclearly worded.
I agree with #Hot Licks, but the behaviour of when a String literal is loaded changed in Java 7 AFAICS.
String literals are loaded when the class is loaded in Java 6 but in Java 7 they changed this to be when the first line which uses the string is executed. You can detect this by looking at the String returned by String.intern(); The first time it is called for a String it will return the same object, however when called again with an equals() String it will return the previous object.
StringBuilder sb = new StringBuilder("Hell");
sb.append("o");
String s = sb.toString();
String si = s.intern(); /* same string if not loaded. */
String s2 = "Hello";
System.out.println( System.getProperty("java.version")+" " + (s == si) + " "+(s2 == s));
prints
1.6.0_45 false false
as you expect, but in Java 7+
1.7.0_45 true true
If s2 is loaded first, the intern() string si will be the same as it, and thus different to s However, if s2 is loaded after, all the Strings use the same object.
This question already has answers here:
How many objects are being created? [duplicate]
(2 answers)
Closed 9 years ago.
How many string objects will be created by the following code?
String s="";
s+=new String("a");
s+="b";
I had this question at exam. I want to know the right answer . I said 2 objects.
The object from pool that contains "" , "b" and the object created by new String("a");
I'll anwser to another, clearer question: how many String instances are involved in the following code snippet:
String s="";
s+=new String("a");
s+="b";
And the answer is 6:
the empty String literal: "";
the String literal "a";
the copy of the String literal "a": new String("a");
the String created by concatenating s and the copy of "a";
the String literal "b"
the String created by concatenating s and "b".
If you assume that the three String literals have already been created by previously-loaded code, the code snippet thus creates 3 new String instances.
String s="";
creates no objects.
s+=new String("a");
creates five objects. the new String, the StringBuilder and its char[] and the String resulting and its char[]
s+="b";
creates four objects, the StringBuilder and its char[] and the String resulting and its char[]
So I get a total of nine objects of which are three String objects
Note: You can be sure that "" has already been loaded as it appear in many system classes including ClassLoader and Class.
The Strings "a" and "b" may or may not be considered as new Strings for the purpose of this question. IMHO I wouldn't count them as they will only be created at most once and if this code is only run once, it hardly matters how many strings are created. What is more likely to be useful is to know how many objects are created each time the code is run.
The number of objects actually created in a JITC situation is indeterminate. The JITC may well recognize that new String("a") is an identity, and that no intermediate values of s are referenced, so that only the StringBuilder is created. There are several potential side-effects that must be mimicked in the general case (eg, where the argument to new String() may be invalid), but with literals they can't occur.
In fact, javac could very well recognize that the result is "ab", with no potential side-effects, and just produce a String literal of that value. (It does string combining in slightly less complicated cases.)
Creating New Strings
Earlier we promised to talk more about the subtle differences between the various methods of creating a String. Let's look at a couple of examples of how a String might be created, and let's further assume that no other String objects exist in the pool:
String s = "abc"; // creates one String object and one reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects, and one reference variable
In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the pool.
From SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065).pdf