james_dean
james_dean

Reputation: 1517

Formatting toString() - New Lines

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

Answers (6)

siliconsmiley
siliconsmiley

Reputation: 349

You can now get the system dependent line separator with:

System.lineSeparator();

Upvotes: 1

tom
tom

Reputation: 2745

New lines can be created using \n.

Upvotes: 0

ApprenticeHacker
ApprenticeHacker

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

Julias
Julias

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

HJW
HJW

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

Related Questions