Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Variables

To perform any operation on data, we first need to store that data in memory. For example, if we need to write a program to add two given numbers, we’ll have to save the two numbers in memory first.

To save some data in memory, we use variables.

Variable is a named memory location used to store a certain type of data.

A variable must have an identifier / name, type and an optional value. Here is the syntax to define a variable :

 var <name>: <type> = <value>

// Example - number 5 stored in variable named a
var a = 5
 

In example above, we have defined a variable named a & assigned the number 5 to it. This creates a space in memory named a & stores the number 5 there.

Any variable is of a certain data type i.e. it can store data only of a certain data type in it. Here a is of type - Int. We need not write the type explicitly because Kotlin supports Type inference i.e. it automatically recognises the type of data from the value we assign to it. Example :

 fun main() {
		var a = 5 // type infered = Int
		var b = 3.14f // type infered = Float
		var c = 'A' // type infered = Char
		var d = "Turing" // type infered = String
}
 

We can also define the type explicitly :

 fun main() {
		var a: Int = 5
}
 

If we do not assign a value to a variable while defining it, we must specify its type :

 fun main() {
		var b: String

		var c // Type not defined - Not allowed!
}
 

Kotlin is Statically typed language i.e. once a variable is declared of a certain data type, its type can not be changed. If variable a is of type Int, we can not assign a String to it.

 fun main() {
		var a = 5
		a = "ABCD" // Not allowed!
}
 

As the name - variable denotes, its value is variable i.e. it can be reassigned. Example :

 fun main() {
		var a = 1
		a = 100 // reassigned 100 to a
}
 

But if we want to define a Constant i.e. the value of which does not change, then we use the keyword val instead of var. Example :

 fun main() {
		val pi = 3.14f
		pi = 5 // pi is val, re-assignment not allowed!
}
 

There are 3 terms related to Variables :

  1. Declaration - Defining a variable with its name & type
  2. Assignment - Assigning a value to variable
  3. Initialization - Declaration + Assignment

Example :

 fun main() {
		var b: Int // Declaration
		b = 10 // Assignment
		var a = 5 // Initialization
}