Possible Duplicate:
Questions about Java’s String pool
I have a doubt in java Strings object creation.
String s1 = "Hello"+"world";
String s2 = s1+"Java";
in this program how many String objects will be created and how ?please explain it. Thanks.
Here is the shortest version (Java 1.5+ required): repeated = new String(new char[n]). replace("\0", s); Where n is the number of times you want to repeat the string and s is the string to repeat.
The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Duplicating an object creates a copy of it and adds it to the bottom of the object list in the Objects palette. When duplicating, you can choose to copy just the object or both the object and its associated shader network. 1.
The answer is 3
Two String objects will be created once per JVM start:
Both will be interned, because they are constants (known at compile time).
They will be reused every time this code runs. A StringBuilder will be created to concatenate the two String above. References to them will be assigned to s1 and s2.
Here's the bytecode for the code:
0: ldc #37; //String Helloworld
2: astore_1
3: new #39; //class java/lang/StringBuilder
6: dup
7: aload_1
8: invokestatic #41; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
11: invokespecial #47; //Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
14: ldc #50; //String Java
16: invokevirtual #52; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: invokevirtual #56; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
22: astore_2
23: return
You can't really say, how many String
s are created, since there's several differences due to the different implementations of the JVM.
As String
is an immutable class, the naive answer is 5. But with some optimization (e.g. using a StringBuffer
/ StringBuilder
there would only be 2 String
s.
As concats would be summarized via append()
-calls.
Edit: As the're some different answers here an explanation why I said 5:
if you look at the compiled code, you can easily guess:
String s1 = "Helloworld";
String s2 = (new StringBuilder(String.valueOf(s1))).append("Java").toString();
We can't accurately know by just looking at source code as many optimizations are done by the compiler before execution.
Here we see that 1 String object is created for s1, and another String object for s2. Here 2 string literals are there in the string pool: "Helloworld" and "Java"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With