A variable is referred to a location to store data in memory in any programming language. The type of variables defines the range of value that the variable can hold. To indicate a storage area, each variable should be given a unique name.
How to declare variables in Kotlin
There are two types of variables in Kotlin
- Immutable Variable
- Mutable Variable
Immutable variable means you can not change value of this variable after once it is declared. val keyword is used for this variable. You can also say that immutable variable means read only variable. It can not be reassigned after it is initialized.
You can declare it as below
Mutable variable means you can change variable value whenever you want. To declare this variable var keyword is used. This variable can be reassigned after it is initialized. You can declare it as below
You can change value of variable but not its type. For example
Difference with Java
You can declare multiple variables on single line in java. But in kotlin this is not possible. You can declare only one variable on single line.
There are five data types in kotlin
Byte (8 bit) : This data type has values from -128 to 127.
Short (16 bit) : This data type has values from -32768 to 32767.
Int (32 bit) : This data type has values from -2,147,483,648 to 2,147,483,647.
Long (64 bit) : This data type has values from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. We have to add suffix L for this data type.
Float (32 bit) : This data type has values from 1.40129846432481707e-45 to 3.40282346638528860e+38. We have to add suffix L for this data type.
Double (64 bit) : This data type has values from 4.94065645841246544e-324 to 1.79769313486231570e+308.
This data type is represented using char keyword. It is declared using single quote.
Value of Boolean type can be true or false. It is used to represent logical values.
Arrays in Kotlin are represented by the Array class. You can create an array in Kotlin either using the library function arrayOf() or using the Array() constructor. Array has get (), set() function, size property as well as some other useful member functions.
Strings can be created with either double quotes or triple quotes.
You can access the character at a particular index in a String
You can also show dynamic string using $ character.