-7

I have below Scenario where I am confused to choose between String and StringBuffer

final MY_STRING =  VAR1 + "," + VAR2 + "," +VAR3 + ","+..........VAR15;

So in this case does each concatenation operation will create a new String object or after all the concatenation operations is completed a Single String object is created and assigned to MY_STRING.

Or is it memory efficient to do the above operation with StringBuffer and convert it to String at last

dimo414
  • 47,227
  • 18
  • 148
  • 244
Prabhu
  • 27
  • 5
  • use StringBuilder if its async. – Spartan Mar 23 '17 at 04:34
  • 1) use `StringBuilder`, not `StringBuffer`. 2) string concatenation in a single expression is efficient, don't worry about it. 3) try Googling your problem first. – dimo414 Mar 23 '17 at 05:49

1 Answers1

0

As @Modus Tollens describes in comment. It suggests that the + operator could be implemented using a StringBuffer or a similar technique. So depending on the Java compiler, the + operator is probably already using a StringBuffer (or StringBuilder) internally.

androidcodehunter
  • 21,567
  • 19
  • 47
  • 70
  • 3
    You keep forgetting that the string + is worked on by the compiler. – GhostCat Mar 23 '17 at 04:38
  • Yes it worked but String is immutable so whenever we put plus it creates new String object. – androidcodehunter Mar 23 '17 at 04:56
  • 1
    Please see [JLS 15.18.1](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.1). It suggests that the + operator could be implemented using a StringBuffer or a similar technique. So depending on the Java compiler, the + operator is probably already using a StringBuffer (or StringBuilder) internally. – Modus Tollens Mar 23 '17 at 05:21
  • Thanks for your clarification @ModusTollens Now I got it. – androidcodehunter Mar 23 '17 at 15:13