menu

Kotlin Basics

Kotlin Basics - Important Points


26.

What is the output of the following code?

fun main() {
val x = 5
val y = 10
val result = if (x > y) "x is greater than y" else "y is greater than x"
println(result)
}

A. A. x is greater than y

B. y is greater than x

C. 5

D. This code will not compile.

Discuss Work Space

Answer: option b

Explanation:

The if expression in Kotlin can be used to return a value based on a condition, similar to the ternary operator in other languages. In this code, the result variable contains a string indicating whether x or y is greater.

27.

What is the output of the following code?

fun main() {
val x = 5
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> println("x is not 1 or 2")
}
}

A. A. x is 1

B. x is 2

C. x is not 1 or 2

D. This code will not compile.

Discuss Work Space

Answer: option c

Explanation:

The when expression in Kotlin is similar to the switch statement in other languages, allowing you to evaluate multiple possible values of a variable and execute different code based on the value. In this code, the x variable is evaluated against the cases of 1 and 2. Since x is neither 1 nor 2, the default case is executed, which prints the message "x is not 1 or 2" to the console.


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