Left Index

Kotlin Input/Output

In this article, you will learn to display output to the screen, and take input from the user in Kotlin.

Koltin Output

You can use println() and print() functions to send output to the standard output (screen). println() will display message and move cursor to beginning of new line, and print() display message and do not move cursor. Let's take an example:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	println("Hello println() method")
	print("Hello print() method")
	println("*Check custor position")
}
Output:
Hello println() method
Hello print() method*Check custor position

Let's have an example to print variable values:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var rollNo: Int = 30
	
	println("Student roll no.: ${rollNo}")
	// or 
	println("Student roll no.: " + rollNo)
}
Output:
Student roll no.: 30
Student roll no.: 30

Kotlin Input

In this section you will learn how to take user input from console. Kotlin has standard library function readLine() which is used for reads line of string input from standard input stream. It returns the line read or null. Let's see an example:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	print("Enter student name: ")
	var name = readLine();

	print("Enter student roll no.: ")
	var rollNo = readLine();
	
	println()
	println("Student name: ${name} and roll no.: ${rollNo}")
}
Output:
Enter student name: John Carlo
Enter student roll no.: 38

Student name: John Carlo and roll no.: 38