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));
Use A String Builder!
Using a
StringBuilder( or aStringBufferfor older versions of the JDK ) is not only more readable, it also makes string concatenation more efficient. Also, useSystem.getProperty( "line.separator" )to ensure cross-platform line endings.