Signup/Sign In

Kotlin Input and Output

In this tutorial, we will discuss how to print output to the console or screen and take input from user in Kotlin. The user input and output are essential part of any program. They will help in user interaction.

Showing Output in Kotlin

For printing output to the console window, we can use print() and println() function. While print() function will keep on adding the output to the same line, println() will print the output and move the cursor to the next line. Let us see this with an example:

println("Hello ")
println("World!!")

print("Bye")
print("World!!")


Hello
World!!
ByeWorld!!

In this example, first two outputs are printed using println() function. So, they appeared in different line. But next two statements are printed using print() function. They will appear in same line.

Output variables in Kotlin

We can print variables directly using print() and println() function.

var number= 25
var character = 'a'
println(number)
println(character)


25
a

We can also concatenate the variables with strings and print them. We can use + or $ operator for it. But use of $ is preferred over +.

var number= 25
var character = 'a'
    
println("Number is: " + number)
println("Character is: " + character)
    
println("Number is: $number")
println("Character is: $character")


Number is: 25
Character is: a
Number is: 25
Character is: a

Take User Input in Kotlin

For taking input from user, we use the readline() function. By default, it will take input as a string. If we need to take any other type of input like number, boolean etc., then it needs to be casted to specific type, which means explicitly specifying and converting the input from string to some other data type like Integer, etc.

println("Enter string: ")
var inputString = readLine()
println("Input in string format is: $inputString")

println("Enter number: ")
var inputNumber = Integer.valueOf(readLine())
println("Input in number format is: $inputNumber")


Enter string:
Hello World
Input in string format is: Hello World
Enter number:
10
Input in number format is: 10

We need to cast the input for different data type in each case. We can also create object of Scanner class and use it for taking input.

var scanner = Scanner(System.`in`)
    
println("Enter number: ")
var inputNumber = scanner.nextInt()
println("Input in number format is: $inputNumber")

Similarly, we will use nextBoolean(), nextFloat(), nextLong() and nextDouble() for different type of variables.

Summary

In this tutorial we discussed how to take input and print output in console. In the next tutorial, we will discuss about comments in Kotlin.



About the author:
I'm a writer at studytonight.com.