1

How many objects will be create for the following string on the heap:

String a = "abc"; String b = "def"; String c = "ghi"; String d = a+b+c 

How many objects are created on the heap?

3
  • No way to know. Maybe 0 or 1 Commented Dec 1, 2013 at 14:13
  • possible duplicate of stackoverflow.com/questions/7370593/… Commented Dec 1, 2013 at 14:15
  • Two, unless you count the internal objects in the StringBuilder instance. Commented Dec 1, 2013 at 15:24

1 Answer 1

1
String a = "abc"; //String literal String b = "def"; //String literal String c = "ghi"; //String literal String d = a+b+c //String d = new StringBuilder(d).append(b).append(c).toString(); 

Note that StringBuilder#append returns an object. Now it's easy for you to determine how many objects were created..

Also note that toString doesn't create a new String, it returns an already created one.

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

7 Comments

Does new StringBuilder() count as object?
So the objects would be a, b, c, an anonymous StringBuilder, and d?
@mathguy54 - You're not paying attention. a, b, and c are literals. They were created when the class was loaded.
LOL! StackOverflow, or how to get my degree without ever turning on my brain!
@mathguy54 -- Two, the StringBuilder and the String value assigned to d.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.