Kotlin Standard Input/Output
Kotlin standard input output operations are performed to flow byte stream from input device (keyboard) to main memory and from main memory to output device (screen).
Kotlin Output
Kotlin output operation is performed using the standard methods print() and println(). Let’s see an example:
Output
Hello World! Welcome to Tutor Aspire
The methods print() and println() are internally call System.out.print() and System.out.println() respectively.
Difference between print() and println() methods:
- print(): print() method is used to print values provided inside the method “()”.
- println(): println() method is used to print values provided inside the method “()” and moves cursor to the beginning of next line.
Example
Output:
10 Welcome to Tutor Aspire 20Hello
Kotlin Input
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:
Output:
Enter your name Ashutosh Enter your age 25 Your name is Ashutosh and your age is 25
While using the readLine() function, input lines other than String are explicitly converted into their corresponding types.
To input other data type rather than String, we need to use Scanner object of java.util.Scanner class from Java standard library.
Example Getting Integer Input
Output:
Enter your age 25 Your input age is 25
Here nextInt() is a method which takes integer input and stores in integer variable. The other data types Boolean, Float, Long and Double uses nextBoolean(), nextFloat(), nextLong() and nextDouble() to get input from user.