In this tutorial you will learn about the Kotlin Input Output and its application with practical example.
Kotlin Input Output
Kotlin Input Output statements are used to read input stream from any standard input device (ex. keyboard) to main memory and to send data stream to any standard output device (ex. monitor).
Koltin Output
In Kotlin, we have println() and print() functions available to send output to the standard output (screen).
Example:-
1 2 3 4 5 6 7 |
fun main(args : Array<String>) { println("line 1 of println"); println("line 2 of println"); print("line 1 of print "); print("line 2 of print"); } |
Output:-
The println() and print() outputs the given string as following.
1 2 3 |
line 1 of println line 2 of println line 1 of print line 2 of print |
Difference Between println() and print()
The print() function prints the given string, while println() function prints the given string similar like print() function. Then it moves the cursor to the beginning of the next line.
Kotlin Input
Kotlin readline() function is used to read a line of string from standard input device like keyboard.
Example:-
1 2 3 4 5 6 |
fun main(args: Array<String>) { print("Please enter a string: ") val istring= readLine()!! println("You entered: $istring") } |
Output:-
When you run the program, it will prompt you for input then it will print the given string in screen.
1 2 |
Please enter a string: I Love Kotlin! You entered: I Love Kotlin! |
Example2:-
1 2 3 4 5 6 7 |
fun main(args: Array<String>) { println("Enter your name:") val name = readLine() println("Enter your age:") var age: Int =Integer.valueOf(readLine()) println("Your name is $name and your age is $age") } |
Output:-
1 2 3 4 5 |
Enter your name: John Enter your age: 35 Your name is John and your age is 35 |
The readLine() function takes any input as a string and convert its to values of other data type (like Int) explicitly.
In Kotlin, if you want input of other data types as input the Scanner object. For that, you need to import Scanner class from Java standard library as following –
1 |
import java.util.Scanner |
Getting Integer Input
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.Scanner fun main(args: Array<String>) { // Creates an instance Scanner class val reader = Scanner(System.`in`) print("Enter a number: ") // nextInt() reads the next integer from the keyboard var integer:Int = reader.nextInt() println("You entered: $integer") } |
Output:-
1 2 |
Enter a number: 15 You entered: 15 |
Here, the nextInt() method takes integer input from the user then store it in an integer variable. To take Long, Float, double and Boolean input from the user, you can use nextLong(), nextFloat(), nextDouble() and nextBoolean() methods respectively.