menu

Kotlin Basic Programs for Beginners

Kotlin Basic Programs for Beginners - Important Points


1.

What is the output of the following Kotlin code?

fun main() {
val num1: Int? = null
val num2: Int = 5
println(num1 ?: num2)
}

A. null

B. 5

C. Compilation error

D. Runtime error

Discuss Work Space

Answer: option b

Explanation:

Here, num1 is a nullable Int variable that is assigned the value null. The Elvis operator (?:) is used to return the value of num1 if it is not null, or the value of num2 if num1 is null. Since num1 is null, the value of num2 (which is 5) is printed.

2.

What is the output of the following Kotlin code?

fun main() {
val num1 = 10
val num2 = 20
val result = if (num1 > num2) "num1 is greater than num2" else "num2 is greater than num1"
println(result)
}

A. num1 is greater than num2

B. num2 is greater than num1

C. Both num1 and num2 are equal

D. Compilation error

Discuss Work Space

Answer: option b

Explanation:

Here, an if-else expression is used to determine whether num1 is greater than num2. Since num2 is greater than num1, the string "num2 is greater than num1" is assigned to the result variable and printed.

3.

What is the output of the following Kotlin code?

fun main() {
val arr = arrayOf(1, 2, 3, 4, 5)
for (i in arr.indices step 2) {
println(arr[i])
}
}

A. 1 2 3 4 5

B. 1 3 5

C. 2 4

D. Compilation error

Discuss Work Space

Answer: option b

Explanation:

Here, a for loop is used to iterate through the indices of the arr array with a step of 2. This means that the loop will start at index 0 (which contains the value 1), then move to index 2 (which contains the value 3), and then to index 4 (which contains the value 5). Therefore, the output will be "1 3 5".

4.

What is the output of the following Kotlin code?

fun main() {
var i = 0
while (i < 5) {
println("Hello, world!")
i++
}
}

A. Compilation error

B. Runtime error

C. Hello, world!

D. Hello, world! (printed 5 times)

Discuss Work Space

Answer: option d

Explanation:

Here, a while loop is used to print the string "Hello, world!" five times. The loop continues to run as long as the variable i is less than 5, and the i++ statement increments the value of i by 1 after each iteration of the loop.

5.

What is the output of the following Kotlin code?

fun main() {
val name: String? = null
println(name?.length ?: -1)
}

A. null

B. -1

C. Compilation error

D. Runtime error

Discuss Work Space

Answer: option b

Explanation:

Here, the safe call operator (?.) is used to access the length property of the nullable String variable name. If name is null, then the Elvis operator (?:) returns the value -1. Since name is null in this case, the value -1 is printed.


Subscribe for Latest Career Trends
Subscribe Now
Use AI and ChatGPT for Career Guidance

Unlock Your Future

Join Now
Worried for Placements in 2024?

Join FAST TRACK Course

Join Now
Supercharge Your SUCCESS

Join All in One Placement Mock Tests-2024

Join Now