Variables
Variables play a crucial role in any programming. They are the names you give to the locations in a computer’s memory where values are stored for use in computer programs, and you use those names later to retrieve the stored values and utilize them in your program.
Kotlin variables can hold values of different types, such as numbers, characters, booleans, strings, arrays, and objects. Kotlin has a rich type system that includes both primitive and reference types. The following are the primitive data types in Kotlin:
Byte
: 8-bit signed integerShort
: 16-bit signed integerInt
: 32-bit signed integerLong
: 64-bit signed integerFloat
: 32-bit floating-point numberDouble
: 64-bit floating-point numberChar
: 16-bit Unicode characterBoolean
: true/false value
To declare a variable in Kotlin, we use the following syntax:
var variableName: DataType = value // mutable variable
val variableName: DataType = value // immutable variable
Here, variableName
is the name of the variable, DataType
is the type of the variable, and value
is the initial value assigned to the variable. For example:
var age: Int = 30
val name: String = "John"
var isTrue: Boolean = true
val pI: Double = 3.14
Kotlin also allows us to declare variables without initializing them. In this case, we must specify the data type of the variable. For example:
var count: Int
count = 10
In the above example, we declare a mutable variable count
of type Int
without initializing it. We then assign the value 10
to the variable later.
Conclusion
Kotlin variables are a fundamental concept that every programmer should understand. They allow us to store and manipulate data in our programs. In Kotlin, we can declare mutable and immutable variables of different data types using the var
and val
keywords. We can also declare variables without specifying their data type, and Kotlin uses type inference to determine the data type.
If you want to know more about the variable types, you can find here.
Please let me know your suggestions and comments. Follow for more such easy and helpful tutorials.
Thanks for reading…
Happy Coding!