tags:

views:

143

answers:

2
+1  A: 

In the first case, the compiler knows the value of the String s1. Thus, all strings with the same value will use the same memory locations:

String s1 = "abc";
String s2 = "abc";

Although there are two String references (s1 and s2), there is only one "abc" sequence in memory. The new operator is not needed because the compiler does the job.

In the second case, the compiler doesn't perform the evaluation of the String value. Thus, the sentence will generate a new instance of String, at runtime:

String s1 = "abc";
String s2 = new String("abc");

The constant "abc" in line 1 references the same memory as the constant "abc" in line 2. But the net effect of line 2 is the creation of a new String instance.

Bruno Unna
So String s1 = "abc"; is creating any object/instance or just allocating memory
Ajay
Since String objects are immutable, there is no difference between both things. Indeed: you can invoke the String methods in a string constant:int stringLength = "hello".length();
Bruno Unna
+3  A: 

The first will use a fixed String that will be compiled in the code. The second variant uses the fixed String and creates a new String by copying the characters. This actually creates a new separate object in memory and is not necessary, because Strings are immutable. For more information, you can read this thread.

The main advantage of having internalized strings is that the performance is better (e.g. through caching etc.).

As a programmer there is no real upside to creating a new String, unless you come by the following example:

String sentence = "Lorem ipsum dolor sit amet";
String word = sentence.substring(5);

Now the word has a reference to the sentence (substring does not copy the characters). This is efficient while the sentence is also used, but when this one is thrown away you use a lot more memory than needed. In that case a new String can be created:

word = new String(word);
Marc
... upvoted to early - I doubt, that the example is correct, because the `String(String s)` constructor doesn't create a new char array but keeps the reference, too. Exactly like `substring(int a, int b)`, which internally calls `new String(int start, int length, char[] chars)`
Andreas_D
It checks for exactly that case and creates a new, resized array.
Hardcoded
The `String(String s)` constructor does make a copy when the original value is much longer that the view.From the javadoc:`Initializes a newly created {@code String} object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string`
Marc