Skip to content

Kotlin: println vs print

Kotlin, println, print1 min read

When working with Kotlin for Android development, you may often find yourself needing to display output or debugging information. Two commonly used methods for this purpose are println and print. In this article, we will dive into the distinctions between these two functions and illustrate their usage through examples.

The Basics: println

The println function is a standard library function in Kotlin that allows you to print a line of text followed by a new line character. It is typically used for displaying messages or debugging information in a console-based environment. Here's an example of using println in Kotlin:

1fun main() {
2 val name = "John"
3 println("Hello, $name!")

The above code will output:

1Hello, John!

Printing Without New Line: print

On the other hand, the print function also prints text but does not append a new line character at the end. This means that subsequent output will appear on the same line. Let's see an example to understand it better:

1fun main() {
2 val firstName = "John"
3 val lastName = "Doe"
4 print("Full Name: $firstName ")
5 print("$lastName")
6 println("!") // Add a new line manually

The output of the code snippet above will be:

1Full Name: John Doe!

As you can see, the two variables firstName and lastName are printed on the same line without any separation.

Choosing Between println and print

The decision of whether to use println or print depends on the specific scenario and the desired output format. If you want each print statement to appear on a new line, then println is the appropriate choice. On the other hand, if you need to display multiple values on the same line without a line break, you should opt for print.

It's worth mentioning that in Android development, using println or print directly in your code may not always be the best approach. The Android platform provides more specialized alternatives, such as logging utilities like Log.d or Timber, which offer better control over logging levels and can be more useful in debugging complex applications.