O. Ziggy wrote:
Consider the following exmamples
Example 1
For example 1, i initially thought 5 objects, i.e.
But then thinking about it i am not really sure because for example will the compiler concatenate `"A" + "B"` as one object? i.e creating 7 objects?
O. Ziggy wrote:
Consider the following examples
Example 1
Example 2
Example 3
* Are the number of objects created in example 2 exactly the same as Example 1 but with an additional string object?
O. Ziggy wrote:
* I think 3 objects are created in example 3. Is this correct? Also, do s1 and s2 both refer to the same string 'A' in the constant pool even though they are different objects?
O. Ziggy wrote:
I thought i understood the answer for example 4 as it was explained in the book. I posted a question on another site and the responses there seem to suggest that the compiler doesnt create the temporary objects as discussed in the book - See this discussion http://stackoverflow.com/questions/8316687/literal-string-creation-vs-string-object-creation Please can someone clarify this.
O. Ziggy wrote:
In the book it is mentioned that a total of eight objects will be created in the above code
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
O. Ziggy wrote: What is the difference in the above compared to s1 = "A" + "B" + "C" + "D";
Concatenation of compile time constants can be done at compile time. So, the compiler will generate code that will instantiate one string object -- "ABCD".
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
When the complier finds an expression in which a string appears in association with a + operator, it turns all items in the expression into strings, concatenates the strings, and creates a new String Object.
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
Dan Drillich wrote:
O. Ziggy wrote:
In the book it is mentioned that a total of eight objects will be created in the above code
Ok, so this part makes sense -
1) spring
2) summer
3) fall
4) winter
5) s1
6) s2
7) object created by - s1.concat("fall ");
8) object created by - s2.concat(s1);
O. Ziggy wrote:I need to know how to know how many objects are created. I did not know that there is a difference in the way strings are constructed if the string is a literal. For example, in your first reply you say that String s1 = "A" + "B" + "C" + "D"; will result in one String object being created. I thought 4 would be created but one will end up in the constant pool.
O. Ziggy wrote:Shouldnt the following initialisations have also been treated as string literal constants?
O. Ziggy wrote:Ok one final question. I had always thought that compile time constants are those that are declared public final. Is this not correct?
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |