What printing is for
The console is the place where a program shows text to the person running it. Most of the work a program does is invisible: values are computed and stored, but nothing appears on the screen unless the code asks for it. Printing is how you look inside your program, whether to show a result or to check what a variable holds while you debug.
The text a program writes to the console is called its output.
println
In Scala, println prints a value and then moves to a new line. This program:
println(13)
produces this output:
13
The value goes inside the parentheses. A number is written without quotes, and println prints it as it is. Text goes in double quotes, and the quotes are not printed:
println("Hello world")
Hello world
The newline
After printing its value, println writes a newline character. It is invisible, and it acts like pressing Enter: the next output starts on a fresh line. That is why several calls produce several lines:
println(1)
println(2)
println(3)
1
2
3
The newline comes after the value, so the output of println(13) is the characters 13 followed by a line break. Nothing is printed before the value.
print: no newline
The name print works the same way but without the newline, so the next output continues on the same line:
print("a")
print("b")
println()
ab
The last line, println() with nothing inside, prints only a newline. It ends the line that print left open.
Numbers and text are different
The quotes decide what a value is. 1998 is a number and "1998" is text made of four characters. Both print the same way, but they behave differently once you start combining them:
println(1 + 2)
println("1" + "2")
3
12
Adding two numbers does arithmetic, while + between two pieces of text joins them.
Printing more than one thing
A single println call prints one value, but text can be joined with + to make one longer value:
println("Hello" + " " + "world")
Hello world
Inside a string, \n is an escape sequence that stands for a newline, so one call can produce two lines:
println("a\nb")
a
b
Common mistakes
- Missing parentheses. The value goes inside parentheses, and every opening parenthesis needs a closing one.
- Quotes around a number you want as a number.
println("1998")prints the same characters, but the value is text, so it won't take part in arithmetic. - Misspelling the name. Scala is case-sensitive:
PrintlnandprintLnare notprintln. The compiler reports that the name was not found. - Expecting
printto start a new line. It doesn't; useprintlnwhen each value should be on its own line.
The exercise
The task is to print the number 1998. Write the call with the number inside the parentheses and no quotes:
println(1998)
Run it in the editor above, and the console shows 1998.
Key takeaways
println(value)prints the value and then a newline.- Several
printlncalls produce several lines. print(value)prints without the newline.- Numbers are written bare; text goes in double quotes, which are not printed.
