Reputation: 1517
I'm building a console based inventory program and would like to override the toString() method to print the customer object to the screen.
I've got the following to approaches but they both look pretty messy. Which one is better practice?
String toString = (name + newLine +
addressLine_1 + newLine +
addressLine_2 + newLine +
city + newLine +
country + newLine +
postCode + newLine);
String toString = System.out.println(String.format("%s%n%s%n%s**%n%s%n%s%n%s%n", name, addressLine_1, addressLine_2, city, country, postCode));
Upvotes: 1
Views: 6215
Reputation: 349
You can now get the system dependent line separator with:
System.lineSeparator();
Upvotes: 1
Reputation: 22031
Use A String Builder!
StringBuilder strBuilder = new StringBuilder();
strBuilder.append( name );
strBuilder.append( System.getProperty( "line.separator" ) );
strBuilder.append( addressLine_1 );
/* ... */
System.out.println( strBuilder.toString() );
return strBuilder.toString();
Using a StringBuilder
( or a StringBuffer
for older versions of the JDK ) is not only more readable, it also makes string concatenation more efficient. Also, use System.getProperty( "line.separator" )
to ensure cross-platform line endings.
Upvotes: 3
Reputation: 5892
The best approach is to use StringBuilder. The + each time creates a new string - not the good practice. Just override function toString() with StringBuilder.
Upvotes: 0
Reputation: 23443
The first one is preferred.
Chances are, your program may be enhanced in near future to output complex objects e.g. Person
, it is much cleaner and maintainable to go with the first approach.
The String concatenation + .. + isn't much of a performance issue. Until then, you may further continue using StringBuilder
or StringBuffer
(if you are on JDK < 5)
Upvotes: 1
Reputation: 10352
You can use some ToString utilities to make the job easier. I know two variants:
Upvotes: 2