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().

fun main(args: Array<String>){
	val num = 10
	print("Hello")
	println("World")
	print("$num")
}

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.

fun main(args: Array<String>){
	print("enter your name:")
	val name = readLine()
	print("hello $name")
}

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.

fun main(args: Array<String>){
	print("enter a number:")
	var num = readLine()!!.toInt()	//!! ensures that input is not null
	print("you entered $num")
}

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 Comment

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