kotlin variable

Variables are the containers which is used to hold some values. These values can be changes throughout our program. Variable refers to a memory location. It is used to store data. The data of variable can be changed and reused depending on condition or on information passed to the program.


How to declare variable in Koltin

Kotlin variable is declared using keyword var and val.


fun main(args: Array) {
    var language = "koltin programming language best for android"
    val name = "Created by durgesh"
   
    println(language)
    println(name)
}
koltin programming language best for android
Created by durgesh

Here, variable language is String type and variable salary is Int type. We don't require specifying the type of variable explicitly. Kotlin complier knows this by initilizer expression. This is called type inference in programming.
We can also explicitly specify the type of variable while declaring it.

Difference between var and val

  var (Mutable variable) : Value of var types variable can be modified. We can change the value of variable declared using var keyword later in the program.

  val (Immutable variable): Value of var types variable can not be modified. We cannot change the value of variable which is declared using val keyword.