5

So I'm studying for the SCJP from the Kathy Sierra book. In the chapter for strings, this is a question:

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat( "fall ");
s2.concat(s1);
s1 += "winter";
System.out.println(s1+" "+s2);
---------------------------
What's the output, and how many string objects and ref variables are created?

The output is spring winter spring summer and there's two reference variables, that's fine.

Then it says there are eight string objects created (spring, summer, spring summer... etc) INCLUDING the ones that are lost due to nothing referencing them.

However, it does not include anything from the last sysout.

My question is, in the last line of code, since s1 and s2 are being concat with a space, doesn't this also create new objects? Or will it simply be passed to the string buffer for display, and not create new objects?

This is obviously very basic and I looked elsewhere but nothing directly answered this. From my understanding, it should create new objects there too, but I need to be sure for the exam! Thoughts?

Thanks, in advance!

Nilay Panchal
  • 541
  • 6
  • 17
  • 2
    Compile the code above, feed it to `javap -c`, and check what bytecode it compiles to. Should be an implicit `StringBuffer` that ultimately gets `toString()` called on it, which should answer the question. – millimoose May 22 '13 at 11:05
  • 2
    (Also, the question is like everything that's wrong with certification. What does it even mean for a reference variable to be *created*? They're a compile-time construct, they're at best declared. There's also the ambiguity arising from when string literals are created - they're certainly created earlier than the results of the string manipulation operations.) – millimoose May 22 '13 at 11:10
  • @millimoose i think those questions are designed to test your knowledge of object instantiation, the jvm and String constants - all very valid areas :) – vikingsteve May 22 '13 at 11:20
  • 2
    @vikingsteve They may be *designed*, but they are *badly designed*. Strings from the constant pool are not created by the code in question; they have a completely independent lifecycle. This question is a didactic nightmare and it's not the first time I see such low quality related to SCJP. – Marko Topolnik May 22 '13 at 11:27
  • @vikingsteve I'm not saying that knowing the nitty gritty at certification-level of detail is worthless. I'm saying that the question, as phrased, is vague and ambiguous and basically amounts to figuring out what the author was thinking. Basically, if the SCJP question was asked on SO as-is (i.e. without the OP asking for clarification on a specific part of it), it would likely get buried and closed. This means you're less likely to learn these concepts well when preparing for the certification, which means the certification is not a good indicator of knowledge. – millimoose May 22 '13 at 13:57
  • @vikingsteve This should be readily apparent seeing as it's possible for me to point out flaws in the certification material without ever having given one a passing glance. And again, this is not saying you will learn nothing when taking a certification course, or that you're better off actively avoiding them. Formal conceptual education is obviously not a fundamentally broken idea, but practically speaking the actual certification courses and exams could, and should be at a much higher level of quality than I keep seeing. – millimoose May 22 '13 at 14:03
  • I agree with you for the most part @millimoose, but I would just like to add that this is for an basic level prog. and for people still grasping the basic concepts of object oriented programming. This question was more a clarification for myself. That said, of course they shouldn't ever teach something incorrect, but I don't think anything taught is entirely wrong, just less required details on the exam are explained vaguely. Unfortunately, there are some really stupid mistakes in this book (like the one in my question!) and the authors shouldn't still allow such glaring errors in the book! – Nilay Panchal May 23 '13 at 15:02

2 Answers2

5

My question is, in the last line of code, since s1 and s2 are being concat with a space, doesn't this also create new objects?

Yes, it creates a 10th string.

Note that this piece of code in itself only necessarily creates 5 strings - if you run it several times in the same JVM, it will create 5 new strings each time you call it. The string literals won't create a new string each time the code runs. (The same string object is reused for "spring " each time, for example.)

There are 10 strings in the code you've given:

  • 5 literals: "spring ", "summer ", "fall ", "winter " and " "
  • 5 concatenation results: s1 + "summer", s1.concat("fall "), s1 + winter (with compound assignment) and s1 + " " + s2.

As I've just commented, a string literal appearing in code doesn't always involve a separate string. For example, consider:

String x = "Foo" + "Bar";

You might expect that to involve three string objects - one for each of the literals, and one for the concatenation. In fact, it only involves one, because the compiler performs the concatenation at compile-time, so the code is effectively:

String x = "FooBar";
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • You mean if they exist in the string constant pool, they won't be re-created correct? Won't it create five strings though? Including the space in the last line of code - " " Then what exactly does the book mean, when it says it creates string objects? Does it mean 9 string objects, but only 5 string literals? – Nilay Panchal May 22 '13 at 11:09
  • Unless you say new() in which case a copy will be created. – Aniket Thakur May 22 '13 at 11:12
  • @nilay9999: You're absolutely right: I miscounted. There are 10 strings; 5 literals (`"spring "`, `"summer "`, `"fall "`, `"winter "`, `" "`) and 5 concatenation results (`s1 + "summer"`, `s1.concat("fall ")`, `s1 + winter` (with compound assignment) and `s1 + " " + s2`). – Jon Skeet May 22 '13 at 11:13
  • @JonSkeet If you don't mind though, could you possibly explain how I could representationally think about a String vs a String Object vs a String literal? Correct me if I'm wrong: When a new String("abc") is used, it creates a string that cannot be interned. This would be a string object, but abc would be the literal value? I'm a little boggled right now! – Nilay Panchal May 22 '13 at 11:22
  • @nilay9999: Yes, that would involve two strings: the object associated with the literal `"abc"`, and a *new* string with the same content. A literal *does* end up being associated with a string object in itself (at least unless it's part of a bigger constant expression - for example `"foo" + "bar"` would be optimized by the compiler into just `"foobar"` using a single object instead of three). – Jon Skeet May 22 '13 at 11:26
  • Right, so the literal would be the actual value in the memory pool. The "String" as we generally refer to, would be the string object that refers to the literal in the pool. When we use new, a new String object is created, as well as a copy of the literal value abc in the pool. Therefore, there would be two abc's in that pool which is what the memory management 'interning' tries to avoid. Thanks as lot! Cheers – Nilay Panchal May 22 '13 at 11:31
  • @nilay9999: No, the literal itself is only in the source code. It would be a real String object in the intern pool. The class file contains the literal data, and uses a `ldc` instruction to access it when you use the literal in the code. The JVM sorts out the literals from all the classes it loads, to pool them. – Jon Skeet May 22 '13 at 11:38
  • 1
    I think the answer missed a concat from the comments :-) – Dave Newton May 22 '13 at 12:32
2

I'll anwser to another, clearer question: how many String instances are involved in the following code snippet:

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat( "fall ");
s2.concat(s1);
s1 += "winter";
System.out.println(s1+" "+s2);
  1. String literal "spring"
  2. String literal "summer"
  3. Concatenation of s1 and "summer"
  4. String literal "fall"
  5. Concatenation of s1 and "fall"
  6. Concatenation of s2 and s1
  7. String literal "winter"
  8. Concatenation of s1 and "winter"
  9. String literal " "
  10. Concatenation of s1 and s2 in sysout

So 10 in total.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Thanks for this - was just about to ask Jon Skeet to add this to his answer. Very helpful. – Andrew Martin May 22 '13 at 11:11
  • @AndrewMartin: As the OP pointed out, there's also " " - so there are 10 in total. I missed that first time too. – Jon Skeet May 22 '13 at 11:15
  • @JonSkeet: Funny, was just scratching my head over that one. Makes sense now, cheers. – Andrew Martin May 22 '13 at 11:16
  • Thanks Aniket, yes @JonSkeet already corrected that. Thanks for the detail though! – Nilay Panchal May 22 '13 at 11:24
  • 2
    And also note that what string concatenation compiles into is java compiler-dependent and could alse be compiled as `s1.concat(" ").concat(s2)`. This is another way such exam questions are a case of bad teaching and misinforming. – Marko Topolnik May 22 '13 at 11:30