Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.In this post, we will go through Kotlin program to read and print string.
You can read values in 2 ways –
1. Read String (Using Scanner)
Sourcecode –
import java.util.* fun main() { val read = Scanner(System.`in`) println("Enter String:") val a = read.next() println("Entered String value = $a") }
When you run the program, output will be
Enter String: SampleStringWithoutSpace Entered String value = SampleStringWithoutSpace
Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.
read.next() means read anything entered by user before space or line break from standard input – Keyboard.
Input read by scanner is then stored in variable a
It means, if you enter “Welcome to India”, read.next() will read only Welcome
Finally, we print read value using println() method.
2. Kotlin Program to read and print String Without Using Scanner
Sourcecode –
fun main() { println("Enter string: ") val sInput = readLine() println("Entered string value: $sInput") }
When you run the program, output will be
Enter string: SampleStringWithoutString Entered string value: SampleStringWithoutString
Output In Case 2 (When you enter string with space)
Enter string: Sample String With Space Entered string value: Sample String With Space
We have used readLine() method to read values from standard input – Keyboard.
readLine() reads value entered by user before line break. It means, readLine() reads value with
spaces as well.
Value returned by readLine() is stored in a variable sInput.
Finally, we print variable sInput using println() method.