4

How many objects are created in the following code?

String a, b, c;
a = "1234";
b = a;
c = a + b;

I was been told the answer is 2, because only a and b point to their own data.

c is only created from using a and b. However, isn't the act of declaring a variable considered creating it? Is this question vague? I said 3.

7
  • 2
    If I do String a;, where's the object? What if I do String a = null;? Commented Nov 5, 2014 at 15:40
  • 2 object it seems, a="1234" and a+B Commented Nov 5, 2014 at 15:47
  • 1
    "However, isn't the act of declaring a variable considered creating it?" Yes, you create the variable, not the object. Commented Nov 5, 2014 at 16:09
  • 1
    you can tell your teacher the question is vague, because + operator may create two objects (1- StringBuilder, 2- String) Commented Nov 5, 2014 at 16:17
  • 1
    Also, the "1234" String might be interned, so you could even ask if it qualifies as "creating" an object ;). Commented Nov 5, 2014 at 16:25

2 Answers 2

3

a = "abcd" creates a String object, and initializes it with the value "abcd". So that's one object

b = a makes b point to the same spot as a, so then a + b will create a new object, which is then assigned to c. That makes a total of two objects created

Sign up to request clarification or add additional context in comments.

1 Comment

I do believe this is what the teacher was looking for. Students aren't meant to know at this stage that + can be implemented with StringBuilders or that a String is backed by a char[].
0

I think the answer is 2. when b=a, in fact, a has a reference to b. when you debug your program on your eclipse, you will see a and b have a same id. They are one Object actually.

1 Comment

as @FlorentBayle have already mentioned. a + b creates another object of type StringBuilder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.