Kotlin Kotlin Basics 1 — Questions and Answers
Question 1: Which keyword is used to declare an immutable variable in Kotlin?
- var
- val (Correct answer)
- let
- const
Correct answer: val
In Kotlin, `val` declares a read-only (immutable) variable that cannot be reassigned after initialization.
Question 2: What is the correct way to define a nullable String in Kotlin?
- String
- String!
- String? (Correct answer)
- Nullable<String>
Correct answer: String?
Appending `?` to a type in Kotlin marks it as nullable, allowing it to hold null values.
Question 3: Which of the following is the entry point of a Kotlin program?
- fun start()
- fun init()
- fun main() (Correct answer)
- fun begin()
Correct answer: fun main()
Every Kotlin application starts execution from the `fun main()` function.
Question 4: What does the `?.` operator do in Kotlin?
- Throws NullPointerException if null
- Calls the method only if the object is non-null (Correct answer)
- Forces a non-null value
- Declares a nullable type
Correct answer: Calls the method only if the object is non-null
The safe call operator `?.` invokes a method or accesses a property only when the receiver is non-null, returning null otherwise.
Question 5: Which of the following correctly declares a Kotlin function that returns an Int?
- function add(a: Int, b: Int): Int
- fun add(a: Int, b: Int) Int
- fun add(a: Int, b: Int): Int (Correct answer)
- def add(a: Int, b: Int): Int
Correct answer: fun add(a: Int, b: Int): Int
Kotlin functions use the `fun` keyword, with parameter types and return type separated by a colon.
Question 6: What will `println(10 / 3)` output in Kotlin?
- 3.33
- 3.333...
- 3 (Correct answer)
- 4
Correct answer: 3
Integer division in Kotlin truncates the decimal, so 10 divided by 3 equals 3.
Which keyword is used to declare an immutable variable in Kotlin?