How to Use print in Kotlin: Syntax and Examples
In Kotlin, you use
print() to display text without a newline and println() to print text followed by a newline. Both functions output text to the standard output (console).Syntax
The print() function outputs text to the console without moving to a new line, while println() prints the text and then moves to the next line. You can pass any value or expression inside the parentheses.
kotlin
fun print(value: Any?) fun println(value: Any?)
Example
This example shows how to use print() and println() to display text and numbers on the console.
kotlin
fun main() {
print("Hello, ")
print("world!")
println() // moves to next line
println("Welcome to Kotlin.")
println(123)
}Output
Hello, world!
Welcome to Kotlin.
123
Common Pitfalls
A common mistake is expecting print() to add a newline automatically, but it does not. Use println() when you want to move to the next line after printing. Also, forgetting to call println() after multiple print() calls can cause output to run together.
kotlin
fun main() {
// Wrong: prints on the same line without space or newline
print("Hello")
print("World")
// Right: adds space and newline
print("Hello ")
println("World")
}Output
HelloWorld
Hello World
Quick Reference
- print(value): Prints value without newline.
- println(value): Prints value with newline.
- Use
println()with no arguments to just print a newline.
Key Takeaways
Use
print() to output text without moving to a new line.Use
println() to print text and then move to the next line.Remember
print() does not add spaces or newlines automatically.Use
println() with no arguments to print a blank line.Both functions accept any value and convert it to string automatically.