print() vs println()
Using print()
print() writes text to standard output without adding a newline afterward, so the next thing printed continues right where the previous output left off.
Example: Using print()
fun main() {
print("Hello, ")
print("World!")
print(" No newline between these.")
}
Login to try C/C++/Java/PHP code in the editor
Using println()
println() behaves like print() but appends a newline character at the end, so each call starts fresh on the next line of output.
Example: Using println()
fun main() {
println("First line")
println("Second line")
println("Third line")
}
Login to try C/C++/Java/PHP code in the editor
Printing Non-String Values
Both print() and println() accept numbers, booleans, and other types directly -- Kotlin converts them to their string representation automatically before printing.
Example: Printing Non-String Values
fun main() {
println(42)
println(3.14)
println(true)
}
Login to try C/C++/Java/PHP code in the editor
Mixing print() and println()
Combining both lets you build a single line piece by piece with print() and then finish it with a println() call, which is useful for formatting output that has multiple parts.
Note: Overusing print() for multi-part lines can get confusing -- string templates (covered later) are often clearer.
Example: Mixing print() and println()
fun main() {
print("Score: ")
print(95)
println("/100")
println("Done!")
}
Login to try C/C++/Java/PHP code in the editor
- Using
print()repeatedly and being surprised that output runs together on one line without spaces or newlines. - Forgetting to add a space or separator manually when chaining several
print()calls together. - Assuming
println()with no arguments does nothing, when it actually prints just a newline.
print()outputs text with no trailing newline; the next output continues on the same line.println()outputs text followed by a newline, moving subsequent output to the next line.- Both functions can print numbers, booleans, and other types by converting them to their string form automatically.
println()called with no arguments simply prints an empty line.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: