Have a look at the Java® Language Specification where it tells you about the String concatenation operator. That should tell you whether a String "9" is created or not. Or maybe not. Maybe it says that is an implementation detail and the number of objects created differs from implementation to implementation.
Put the code into a class, compile it and inspect it with the javap −c command. See what that tells you.
I trust you haven't been given a question about that sort of code. As you will find out from my suggestions, there may not necessarily be a single answer to that sort of question.
posted 2 years ago
Have you worked out the answer yet? I used javap −c and only found one String object apparently " 9". Of course, that expression right of the = sign is a constant expression (=compile time constant), so it is evaluated and converted to a single expression or a single object by the compiler, so the answer is that one object is created.
Similarly, if you had this sort of declaration:-. . . javap −c would show that constant expression evaluated to 7. The bytecode will contain 7, not 1 2 or 3.
If that is a question from an exam, please tell us where it comes from, so as to minimise copyright problems.
posted 2 years ago
Thanks Campbell for your reply.
The idea came from a test question in OCA Java® SE 8 Programmer I Exam Guide by Kathy Sierra Bert Bates. specifically, question 9 of chapter 6 self test.
I don't know if it is OK to include the full question here but the statement
s = " " + i;
was inside a for loop where s is created by concatenating " " with the int variable i.
And the question was to estimate how many objects will exist in memory after the loop is done assuming the garbage collector dose NOT run.
The provided answer state that " " is created once and reused in every loop iteration.
The resulting String (s) of the concatenating will be an object created on every loop iteration.
My question is about the int i that is concatenating with " ".
will this variable be converted to a string and then concatenated with s.
If this the case what about that converted string i, does is it live in memory until the loop is done. If this is the case, the number of objects created will be double the provided answer.
I claim this furniture in the name of The Ottoman Empire! You can keep this tiny ad: