Posts

Showing posts from June, 2013

The best way to join Strings in Java

Joining strings in java is quite simple, just take two strings and add them using the "+" sign as follows: String s = "One" + " Two"; Which results in: s == "One Two". The thing is that String objects in Java are immutable, so you can't actually change any string, which means that in the following example: String a = "One"; String x = a; in memory now: (a == x) a = a + " Two";  Will result in the following in-memory statement:  ( a != x ) which is a reason for many many bugs in many programs. Another side effect of immutable objects is that every "change" of the string will actually create a new one, resulting in lots of dead objects which will later on be ditched by the garabage collector, but in the meanwhile they consume memory, and will use CPU to collect them. StringBuilder / StringBuffer The simplest solution supplied by Java is using StringBuilder / StringBuffer (Strin