User Input and Output
User Input and Output
Video Explanation

Output: Printing to Console
println() — Print with Newline
println("Hello, World!")
println(42)
println(3.14)
println(true)
print() — Print without Newline
print("Hello, ")
print("World!")
// Output: Hello, World!
System.out.printf() — Formatted Output
System.out.printf("Name: %s, Age: %d, Score: %.2f%n", "Alice", 25, 98.5)
// Output: Name: Alice, Age: 25, Score: 98.50
String Templates
val name = "Bob"
val score = 95
println("Student: $name scored $score marks")
println("Next year score: ${score + 5}")
Input: Reading from Console
readLine() — Read a Line of Text
fun main() {
print("Enter your name: ")
val name = readLine()
println("Hello, $name!")
}
Note:
readLine()returnsString?(nullable String).
Reading and Converting Input
fun main() {
print("Enter your age: ")
val age = readLine()?.toInt() ?: 0
println("You are $age years old")
}
Reading Different Data Types
Integer Input
fun main() {
print("Enter a number: ")
val num = readLine()!!.toInt()
println("Square: ${num * num}")
}
Double Input
fun main() {
print("Enter price: ")
val price = readLine()!!.toDouble()
println("With tax: ${price * 1.18}")
}
Boolean Input
fun main() {
print("Are you a student? (true/false): ")
val isStudent = readLine()!!.toBoolean()
println("Student status: $isStudent")
}