5.
You want to build a thread-safe string that appends numbers 1 to 3 separated by commas, resulting in "1,2,3". Which code snippet correctly uses StringBuffer to achieve this?
1. StringBuffer sb = new StringBuffer();
for (int i = 1; i <= 3; i++) {
sb.append(i);
if (i != 3) sb.append(",");
}
System.out.println(sb.toString());
2. StringBuffer sb = new StringBuffer();
for (int i = 1; i <= 3; i++) {
sb.append(i + ",");
}
System.out.println(sb.toString());
3. StringBuffer sb = new StringBuffer();
sb.append("1,2,3,");
System.out.println(sb.toString());
4. StringBuffer sb = new StringBuffer();
for (int i = 1; i < 3; i++) {
sb.append(i);
sb.append(",");
}
System.out.println(sb.toString());