0 votes
in Kotlin by
What are the variables used in Kotlin?

1 Answer

0 votes
by

Variables are used to store data to be manipulated and referenced in the program. It is fundamentally a unit of storing data and labeling it waits for an expository alias so that the program is simple to read and easy to understand. In other words, we can say that variables are the containers to collect information.

In Kotlin, all the variables should be declared. However, if any variable is not declared, then it pops out to be a syntax error. Also, the declaration of the variable determines the type of data we are allowing to store in the variable. In Kotlin, variables can be defined using val and var keywords. Here is the syntax of declaring variables in Kotlin:

Var day = "Monday"
Var number = 3

Here, we have declared the local variable day whose value is “Monday’ and whose type is String and another local variable number whose value is 3 and whose type is Int because here the literal is of the type integer that is 3.

Local variables are customarily declared and initialized simultaneously. We can also perform certain operations while initializing the Kotlin variable.

We can perform an operation on the variable of the same data type, as in here num1 and num2 both are of the same data type that is Int, whereas day is of the string data type. Ergo, it will show an error. Here is one another technique how can you define variables in Kotlin.

var day : String = "GURU99"
var num : Int = 100

Let see how var and val keywords are different from each other.

Var :

Var is like a generic variable used in any programming language that can be utilized multiple times in a single program. Moreover, you can change its value anytime in a program. Therefore, it is known as the mutable variable.

Here is an example of mutable variable in Kotlin:

var num1 = 10
Var num2 = 20
Num1 = 20
print(num1 + num2) // output : 40

Here the value of num1 that is 20, is overwritten by the previous value of num1 that is 10. Therefore the output of num1 + num2 is 40 instead of 30.

Val :

Val is like a constant variable, and you cannot change its value later in the program, which neither can be assigned multiple times in a single program and can be used only once in a particular program. Ergo, it is known as an immutable variable.

Here is an Kotlin program example of immutable variables in Kotlin:

Val num1 = 10
Var num2 = 20

Here, the value of num1 that is 10 cannot be overwritten by the new value of num1 that is 20, as it is of val type that is constant. Therefore, the output is 30 instead of 40.

Note: In Kotlin, immutable variables are preferred over mutable variables.

...