WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 7 of 100

Explain the difference between val and var in Kotlin.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, ‘val‘ and ‘var‘ are keywords used for declaring variables. The difference between them is that ‘val‘ is immutable, which means that its value cannot be changed once assigned. On the other hand, ‘var‘ is mutable and its value can be reassigned.

Let’s consider an example:

val x = 5
var y = 10

In this example, ‘x‘ is assigned the value of ‘5‘, and since it is declared as a ‘val‘, its value cannot be changed later in the program. However, ‘y‘ is assigned the value of ‘10‘, and since it is declared as a ‘var‘, its value can be changed later in the program.

y = 15

Now ‘y‘ will have a new value of ‘15‘.

The advantage of using ‘val‘ wherever possible is that it helps in achieving immutability and hence, reduces the risk of unexpected changes to the variables. This helps in making the code more robust, easier to read, and maintainable.

In summary, if we want to declare a variable which can be reassigned, then we use ‘var‘. However, if we want to declare a variable whose value should remain the same throughout the program, then we use ‘val‘.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics