I am trying this textbook example, and I checked, this is exactly what was in the book:-
public class StringBuilderConstructors
{
public static void main(String[] args)
{
Object objectRef = "hello";
String string = "goodbye";
char[] charArray = {'a','b','c','d','e','f'};
boolean booleanValue = true;
char characterValue = 'Z';
int integerValue = 7;
long longValue = 10000000000L;
float floatValue = 2.5f;
double doubleValue = 33.333;
StringBuilder lastBuffer = new StringBuilder("last buffer");
StringBuilder buffer = new StringBuilder();
buffer.append(objectRef)
.append(System.getProperty("line.seperator"))
.append(string)
.append(System.getProperty("line.seperator"))
.append(charArray)
.append(System.getProperty("line.seperator"))
.append(booleanValue)
.append(System.getProperty("line.seperator"))
.append(characterValue)
.append(System.getProperty("line.seperator"))
.append(integerValue)
.append(System.getProperty("line.seperator"))
.append(longValue)
.append(System.getProperty("line.seperator"))
.append(floatValue)
.append(System.getProperty("line.seperator"))
.append(doubleValue)
.append(System.getProperty("line.seperator"))
.append(lastBuffer);
System.out.printf("buffer contains%n%s %n", buffer.toString());
}
}
But the result it is giving me is completely wrong.
buffer contains hellonullgoodbyenullabcdefnulltruenullZnull7null10000000000null2.5null33.333nulllast buffer
This whole thing is not supposed to be in one line.
Your problem is you are using System.getProperty("line.seperator")
instead use System.getProperty("line.separator")
, you are simple using seperator
instead of separator
typo i guess.Elliot already answered the other way of doing things, to add to your answer. I would prefer following code:
String lineSeparator=System.getProperty("line.separator");
buffer.append(objectRef)
.append(lineSeparator)
.append(string)
.append(lineSeparator)
.append(charArray)
.append(lineSeparator)
.append(booleanValue)
.append(lineSeparator)
.append(characterValue)
.append(lineSeparator)
.append(integerValue)
.append(lineSeparator)
.append(longValue)
.append(lineSeparator)
.append(floatValue)
.append(lineSeparator)
.append(doubleValue)
.append(lineSeparator)
.append(lastBuffer);
I prefer reusing the code, i think it make the code more robust.