Adds new line marker to text that is actually in StringBuffer. Next part will be shown in the line below.
Videos
+ creates new intermediate String objects as Strings are immutable in Java whereas StringBuffer's append() works on the same string and that's why it is considered faster. However, you should use StringBuilder from java 5 onwards as it is said to be faster than StringBuffer as its methods are not synchronized like StringBuffer.
This is high level theoritical explanation. For more specific details look at String concatenation: concat() vs "+" operator post.
If your code isn't executed in a loop many thousand times, + is perfectly okay. Exception to the rule, an ever growing string, with reallocation of memory over and over again:
// fine:
for (customer: list)
System.out.println ("Customer: " + customer);
// prolematic for bigger lists:
for (word: list)
chain += word;
With 100 words of length 50, you end up with lengths 50, 100, 150, ... 5000 - totally 250 000 chars, a lot of work for the garbage collection.
Nope.
And given that they're hardcoded strings, it'd be identical to write
buff1 = new StringBuffer("some value Asome value B");
BTW, it's a bit more efficient to use a StringBuilder rather than a StringBuffer (and the API is identical).
It's very likely that code was generated by some refactoring tool and the coder wasn't bothered to remove the redundant lines.
Thanks to the compiler, you are already using StringBuilder which is the newer, faster version of StringBuffer.
Your code above will compile to the equivalent of:
public static void winner ()
{
if (position1 >= 100){
System.out.println(new StringBuilder("THE WINNER IS ").append(name1).toString());
}
else if (position2 >= 100){
System.out.println(new StringBuilder("THE WINNER IS ").append(name2).toString());
}
}
So, in this case, you would not be accomplishing anything that isn't already being done for you. Use StringBuilder when you are building a String in a loop.
In your situation, they were probably talking about pre-initializing a single StringBuilder for both cases:
public static void winner() {
StringBuilder out = new StringBuilder("THE WINNER IS ");
if (position1 >= 100) {
out.append(name1);
} else if (position2 >= 100 {
out.append(name2);
} else {
return; // Preserve previous behavior just in case, remove this if it's not needed
}
System.out.println(out);
}
You probably want something like:
public static void winner ()
{
StringBuffer sb = new StringBuffer("THE WINNER IS ");
if (position1 >= 100)
System.out.println(sb.append(name1).toString());
else if (position2 >= 100)
System.out.println(sb.append(name2).toString());
}
BUT generally StringBuilder is preferred to StringBuffer as access to StringBuffer is synchronized.