Kotlin Input and Output Using Console

In this tutorial you will learn how to take input and print output on console in Kotlin.

Kotlin Print Output on Console

Kotlin provides print() and println() functions for printing something on console. As kotlin language is derived from Java so these two functions internally call java methods System.out.print() and System.out.println().

Output

HelloWorld
10

There is a little difference between print() and println() in kotlin. The print() function doesn’t adds a new line after printing the statement while println() adds new line. You can see in above program output, the World is printed just after Hello. While the value of num variable is printed in a new line.

For printing the value of variable on console we simply add $ sign before variable name in the print statement.  You can see this in above example.

Kotlin Take Input from Console

For taking input from user in kotlin we have a function readLine(). This function reads a line from console and by default the value that is read is string type.

Output

enter your name:neeraj
hello neeraj

How to Read Integer in Kotlin?

In above program we read a string type value. What if you want to read other type of value? Let say you want to read integer value from console in kotlin, it can be done in following way.

Output

enter a number:20
you entered 20

In above program we converted string input to integer using toInt() function. You can use toFloat(), toLong(), etc to convert to any other type also.

You can ask your queries in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.