Java Console Output

Display text (and spaces/numbers/symbols)

System.out.println("Hello World 123 @$%#.,");
  • To display multiple print commands on the same line, use "print" instead of "println".

Arrange text (tab, new line)

System.out.println("Hello \t World \n Testing");
  • "\t" will tab "world" to the right.
  • "\n" will put the text following it onto a new line.

Display calculated values

System.out.println(12+34); // This will display: 46
  • With calculations you don't use quotes, otherwise it will display the calculation numbers "12+34" rather than the answer.

Display both text and calculated values

System.out.println("Hello world " + (12+34)); // This will display: Hello World 46
  • If the calculation isn't in parentheses, it will display the numbers as 1234, rather than the answer 46.

Display a value with 2 decimal places

System.out.println( String.format("%.2f", 14f) ); // This will display 14.00
  • The f is not needed after the value being displayed if it is already a decimal, such as 14.4567
  • You can display to another number of decimals places, just change the number after '%.'
  • To display a large number separated by commas (e.g. 23,661,523), put a comma after the '%' (e.g. "%,.2f").
  • Alternatively you can use 'System.out.printf("%.2f", ___ )'

Have content take up a fixed amount of space

System.out.println( String.format("%-12.12s", "Name") ); // This will take up 12 spaces
  • This is useful if you have another value on the same line and want it to be a fixed distance from the left side.
  • Use this if you have multiple lines containing words/numbers of varying length that you want to line up in columns.
  • The number to the left of the point specifies the minimum amount of space to fill (padding is added after short words).
  • The number to the right of the point specifies the maximum amount of space to fill (longer words are cut short).
  • If the maximum amount is not needed, remove both the point and the number on the right (e.g. leaving "%-12s").

Display content aligned to the right

System.out.println( String.format("%12s", "hi") ); // This will align to a point 12 spaces right

Challenge

Write a program that will display the following on a line (where the blank lines should show the actual answers calculated by the program, <tab> is replaced by a real position tab, and the numbers are shown to the 3rd decimal): The square root of 134 is ___, <tab> also 13^4 = ___.

Quiz

Completed