Kotlin Kotlin Basics and Syntax 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, while `var` declares a mutable variable.
Question 2: What is the correct way to define a nullable String in Kotlin?
- String
- String!
- String? (Correct answer)
- Nullable<String>
Correct answer: String?
In Kotlin, appending `?` to a type makes it nullable, so `String?` can hold a String value or null.
Question 3: Which of the following is NOT a valid Kotlin data type?
- Int
- Double
- Float
- Integer (Correct answer)
Correct answer: Integer
Kotlin uses `Int`, `Double`, and `Float` as built-in types; `Integer` is a Java wrapper class, not a Kotlin type.
Question 4: What does the `?.` operator in Kotlin do?
- Forces a non-null assertion
- Performs a safe call on a nullable object (Correct answer)
- Casts a type forcefully
- Checks equality of two nullable values
Correct answer: Performs a safe call on a nullable object
The safe call operator `?.` calls a method or accesses a property only if the object is non-null; otherwise it returns null.
Question 5: Which keyword is used to define a constant at the top level in Kotlin?
- val
- const val (Correct answer)
- static val
- final val
Correct answer: const val
`const val` is used to declare compile-time constants in Kotlin, which must be at the top level or inside an object.
Question 6: What will `println(10 / 3)` output in Kotlin?
- 3.33
- 3 (Correct answer)
- 3.0
- Error
Correct answer: 3
In Kotlin, dividing two Int values performs integer division, so `10 / 3` results in `3`.
Which keyword is used to declare an immutable variable in Kotlin?