Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Comments and Printing Data  ›  Lesson

print and println

print & println 12 minprintln writes its argument followed by a new line, print writes it without one, and both turn any value into text using its toString.

print and println

The fastest way to see what your program is doing is to make it talk. For the café, that might be a receipt on the screen or a quick check that a total is what you expect. Kotlin gives you two functions for this, and they differ by exactly one character: a new line.

The rule

println ends the line; print leaves the cursor waiting.

println("Pebble Café")
print("Latte")
print(" x")
println(2)
println()
println("Thanks!")

Output:

Pebble Café
Latte x2

Thanks!
  • println(value) writes the value, then a line break.
  • print(value) writes the value and stays on the same line.
  • println() with nothing inside writes only a line break, giving a blank line.

Both accept any value, not just strings. They call the value's toString() to turn it into text:

println(3.5)                       // 3.5
println(true)                      // true
println(listOf("latte", "chai"))   // [latte, chai]
println('A')                       // A

Lists, sets and maps print their contents nicely. Arrays do not: println(arrayOf(1, 2)) shows something like [Ljava.lang.Integer;@1b6d3586. Use arrayOf(1, 2).contentToString() to see [1, 2].

Both functions are available everywhere without an import, because they live in kotlin.io, a default import. There is also readln() for reading one line of text typed by the user.

The shortcut

Track an imaginary cursor. Each print moves it right; each println moves it right and then down to the start of the next line. Draw the output by following the cursor.

Following the cursorStep 1 of 4
  1. print("Cups: ")

    Screen: Cups: and the cursor stays at the end of that line.

A common slip is ending a program with print. The last line may then run straight into the terminal prompt that follows it.

Drills

Answer fast — trust the rule.

quick drill

How many lines does print("a"); print("b"); println("c") produce?

quick drill

What does println() with no argument do?

quick drill

What does println(listOf(2, 4)) print?

quick drill

How do you print the contents of val cups = arrayOf(1, 2, 3)?

Remember

  • println adds a line break; print does not; println() alone makes a blank line.
  • Any value can be printed through its toString().
  • Follow the cursor to predict the output; arrays need contentToString().

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLay out a receipt

Write the print and println calls that produce a receipt with the heading "Pebble Café" on the first line, then "Latte x2" on the next line built from three separate print calls, then a blank line, then "Thanks!". Explain why each call is print or println.