Input and Output in Kotlin

In this tutorial, we will learn about Input and Output in Kotlin. We have written several Kotlin programs in previous tutorials and in many programs we have displayed some output on the screen. We have two functions in Kotlin to show output on the screen.

  • print() 
  • println()

The only difference between is when we use print() method it prints output and leaves the cursor on the same line. But on the other side, when we use println() it prints output and leaves the cursor on the next line.

fun main(args: Array<String>) {  
    int num1=20;
    println("Welcome to Owlbuddy ") 
    println("Welcome to Owlbuddy ") 
    println("Number is "+20)
    print("Welcome to Owlbuddy ") 
    print("Welcome to Owlbuddy ") 
}  

If you want to concatenate a variable with the output you can use concatenate operator (+) to do this. Please check the above example

Now we know how to show some output on the screen. Next, we will learn how to get input from the user.

Taking input from user in Kotlin:

Kotlin has an inbuilt readLine() to take input from the user. This readLine() function is mainly used to take string inputs. But we can also take other types of input but we have to explicitly change in their corresponding types.

Example Program:

fun main(args: Array<String>) {  
    println("Your Fav Programming language")  
    val lang = readLine()  
    println("Your age please")  
    var age: Int =Integer.valueOf(readLine())  
    println("Your fav programming language is $lang and Your age is $age")  
}  

In case you don’t want to change the data type of every variable explicitly. You can use standard Scanner class from the Java standard library.

Example Program:

import java.util.Scanner  
fun main(args: Array<String>) {  
    val obj = Scanner(System.`in`)  
    println("Enter your age")  
    var age = obj.nextInt()  
    println("Your age is "+age)  
}  

Available Functions in Scanner class:

Function Description
nextBoolean() Read boolean input
nextByte() Read byte input
nextDouble() Read double input
nextFloat() Read float value
nextInt() Read int input
nextLine() Read string input
nextLong() Read long value
nextShort() Read short input
Spread the love
Scroll to Top