Object for the String [duplicate] - java

This question already has an answer here:
String s = "a" + "b" + "c"; Can anyone tell for this statement how many object will be created [duplicate]
(1 answer)
Closed 8 years ago.
How many object will be created for this syntax
String a="b" +"c" +"d";
I tried asking with different people some say it will create 4 object some say 1 object.

Only one!
Expression String a="b" +"c" +"d"; is a compile time constant and after compilation you will just have one String instance and that is "bcd"

For a constant concatenation: only the resulting String.
If there are String variables involved, a StringBuilder is new-ed and then everything appended, so the second object is the resulting String.

One!
Since your creating ONE String object, "b","c","d" are constants, the compiler won't allocate a space for them on the stack.

The jls spec clearly states that 1 String will result as a result of a constant expression.
That still results in more than one object, as the String itself is composed of a char[].

One object will be created!
String a="b" +"c" +"d"; bcd will show up at the class constant pool .(literal object)awesome answer by fellow stackoverflow member
You can even see this in the bytecode:
LDC "bcd"
ASTORE 1

One object will be created at the constant pool

Related

How many Strings are formed? [duplicate]

This question already has answers here:
How many string objects will be created in memory? [duplicate]
(4 answers)
Closed 3 days ago.
String a="hello";
String b=a+"Bye";
How many Strings are formed?
From my understanding of Java.
What happens in this code is:
String a="hello"; // hello is created in string pool
String b=a+"bye"; // new StringBuilder(a).append("bye")
So totally 2 strings are to be created, right?
1.Hello
2.HelloBye (In the Heap)
Or does Java create 3?
1.Hello
2.Bye
3.HelloBye
If this is the case, does append method create the appending strings in the string pool?
String a = "hello";
JVM will create one string in the string pool. (FIRST STRING IN POOL)
Now, here comes the tricky part>
b = a + "bye";
Internally + operator uses StringBuffer for concatenating strings.
String b= new StringBuilder(a).append("bye").toString(); (The toString() method of StringBuilder is returning a new String which will be definitely in the Heap since it is created with new String(...). So "bye" will be SECOND STRING IN POOL.)
Now,
b="hellobye" ("hellobye" will be THIRD STRING IN POOL)
First string "hello" is created and added to the string pool.
Next, the String "Bye" is created and added to the string pool.
The concatenation of a and "Bye" results in a new String "helloBye",
which is also added to the string pool.
A total of 3 Strings will be created in the pool: "hello", "Bye",
and "helloBye".
When you create a new StringBuilder and append a string to it, the resulting string will not be added to the string pool. Instead, a new String object will be created in the heap memory to represent the combined string.
So, the code new StringBuilder(a).append("bye") will create one new String object in the heap memory to represent the combined string and one string in pool for "a".
The only part of your question that can be answered with complete certainty is this:
Does append method create the appending strings in the string pool?
The answer is No. The result of a string concatenation that is not a constant expression is not placed in the string pool. At least not in any implementation of mainstream Java to date. However, there is no specification that actually guarantees this.
There are a couple of reasons why we don't know for sure how many strings are "formed".
We don't know when the String objects corresponding to the literals are actually created. In some Java implementation they will be created (and interned) when the code is loaded. In others, the string creation could occur the first time this code is run.
We don't know whether one or both of those literals are used by another class ... and hence whether this code is "forming" them.
Depending on the Java implementation, interning a string (to put it in the string pool) may result in a new String object being created. So you might get a scenario where two String objects get "formed" for each literal.
In short there is enough ambiguity that we cannot be 100% sure of the precise number of strings that are created during the execution of that code.
Does it matter that we don't know for sure?
Frankly, no. It should make zero difference to the way that you write your code1. Let the Java compiler and runtime take care of it ... and use a recent version of Java to get the benefit of the work they have done on optimizing this.
1 - But it is still wise to avoid string concatenation loops. I don't know if they can be optimized.
In your commented version you wrote:
String a = "hello"; // hello is created in string pool
String b = a + "bye"; // new StringBuilder(a).append("bye")
Both of those comments are questionable:
The "hello is created in string pool" comment is questionable for reasons that I gave above.
The new StringBuilder(a).append("bye") pseudo-code is questionable because that is an implementation detail. In Java 9 and later, expressions that involve string concatenations are translated to a invokedynamic bytecode. The JIT compiler generates native instructions directly. See How much does Java optimize string concatenation with +? for more information.

String.valueOf(someVar) vs ("" + someVar) [duplicate]

This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Closed 5 years ago.
I want to know the difference in two approaches. There are some old codes on which I'm working now, where they are setting primitive values to a String value by concatenating with an empty String "".
obj.setSomeString("" + primitiveVariable);
But in this link Size of empty Java String it says that If you're creating a separate empty string for each instance, then obviously that will take more memory.
So I thought of using valueOf method in String class. I checked the documentation String.valueOf() it says If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So which one is the better way
obj.setSomeString("" + primitiveVariable);
obj.setSomeString(String.valueOf(primitiveVariable));
The above described process of is done within a List iteration which is having a size of more than 600, and is expected to increase in future.
When you do "" that is not going to create an Object. It is going to create a String literal. There is a differenc(How can a string be initialized using " "?) actually.
Coming to your actual question,
From String concatenation docs
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
So unnecissarly you are creating StringBuilder object and then that is giving another String object.
However valueOf directly give you a String object. Just go for it.
Besides the performance, just think generally. Why you concatenating with empty string, when actually you want to convert the int to String :)
Q. So which one is the better way
A. obj.setSomeString(String.valueOf(primitiveVariable)) is usually the better way. It's neater and more domestic. This prints the value of primitiveVariable as a String, whereas the other prints it as an int value. The second way is more of a "hack," and less organized.
The other way to do it is to use Integer.toString(primitiveVariable), which is basically the same as String.valueOf.
Also look at this post and this one too

where do actual parameters in java store [duplicate]

This question already has answers here:
String Constant Pool
(5 answers)
Closed 9 years ago.
If I pass a String literal to some metohd as:
String s=new String("stack");
String s2=s.concat("overflow");
where string "overflow" will be stored.
one of my friends arguing that it is created in String constant pool and I'm opposing him.
please let me know
Thanks in advance.
All String literals go in the constant pool. The End. In this case, two constants, "stack" and "overflow", go into the pool. A new String is created that holds the same value as the "stack" in the pool, and then another String is created by concatenating the "overflow" from the constant pool to it.
Excerpt from javap -c -verbose Test:
Constant pool:
#1 = Methodref #10.#19 // java/lang/Object."<init>":()V
#2 = Class #20 // java/lang/String
#3 = String #21 // stack
#4 = Methodref #2.#22 // java/lang/String."<init>":(Ljava/lang/String;)V
#5 = String #23 // overflow
#6 = Methodref #2.#24 // java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;
This question is certainly undecidable, yet you can find out how a certain combination of java compiler and JVM does it.
As far as I can see, nothing could stop one from writing a java compiler that, when it sees a string constant, emits byte code to create that string in the heap in some way as long as the rules stated in the JLS concerning string literals are still maintained. For example, String.intern could maintain a global Map, and the compiler could compile a String literal like follows:
create a char array of the desired size
put character at index 0
put character at index 1
...
put character at index (length-1)
construct the actual string object
pass the String just created to String.intern and leave result on the stack
Actually, one could have a pre-processor changing all string constants to
(extra.HeapString.createString(new char[] { ... }))
and have createString create a String instance in such a way that the rules for String literals hold. And you couldn't write a program that could detect if it was compiled from the original source or from the preprocessed one (except through reflection on extra.HeapString).
The string stack will be in the heap, the string overflow is in the constant pool, the third string as the result of concatenation stackoverflow in the constant pool.

String objects and reference in java [duplicate]

This question already has answers here:
How many string objects will be created in memory? [duplicate]
(4 answers)
Closed 9 years ago.
String str = "Hello"+"World";
String str1 = str + "hello";
How many objects are created and how many references are created?
String is an immutable object. Whenever you manipulate a String, the JVM creates (at least) a new String and assigns it the new (concatenated) value.
As you did not specify you only care about String objects and references, we need to talk about StringBuffers. StringBuffers are (beside StringBuilders) a class that tries to work around the immutable nature of Strings. We all know, many times we just need to add two or more Strings together.
Imagine this code:
String sentence = "the " + "quick " + "brown " + "fox ";
Often times, when that happens, the Java Compiler will not create these Strings, one at a time adding them together, then forgetting about all intermediary Strings. What happens is that a StringBuffer is created. Then, all single Strings are added by using StringBuffer.append(String), then at the end one String is returned.
What you can say for sure is that 3 String references are created, referencing the inlined (and pooled) Strings "Hello", "World" and "hello". Each reference references a different String. That would have changed if the third word would have been "Hello" as well (uppercase h).

How many objects are created here - Java [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to know how many objects will be created with the following code?
I have following lines of code in a program
String str1 = "abc";
String str2 = str1;
String str3 = "abc";
I want to know how many objects are created when above 3 lines of code is executed.
All the three references refer to the same interned String object.
2, 1 string object and the string contains 1 character array.
only one object is created. The rest(str2,str3) are referred to internal string pool.
It can create 0 or 1 object.
If there is already an interned String object with value "abc" no objects are created and if its not present, it gets created.
3 objects, but they all use the same interned string (i.e. the string only exists once in the running JVM).

Categories

Resources