Start learning free

LESSON 4 OF 414 · WELCOME TO KOTLIN

Variables in Kotlin

Lesson

In computer science, data is anything that is meaningful to the computer. Kotlin provides a large number of data types, the most frequently used being:

  • Int - represents integer numbers like 3 and -12
  • Double - represents floating point numbers like 3.14
  • Char - represents a single character like 'a', 'Z' or '?'
  • String - represents a sequence of characters like "John Doe"
  • Boolean - represents one of two values: true or false

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or "123 cats", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables are containers for storing values. A piece of information / data lives in memory and we use a variable to store and descriptively label that data.


Variable declaration:

To create / declare a variable, we must tell Kotlin the variable's name followed by its data type (after a colon), like so:

val name: String = "AlgoCademy"

creates a String variable named name.


Variable initialization:

We can initialize a variable to an initial value in the same line as it is created using the assignment operator (=). This code:

val name = "AlgoCademy"

creates a new String variable named name and assigns it an initial value of "AlgoCademy".

When executing this code, Kotlin will allocate some memory, then it will store the string "AlgoCademy" in that memory and finally will attach this name label to that memory location.

You can think of this memory location as a box. In that box, we put string "AlgoCademy". Then, we put the label name on this box.


val vs var:

Kotlin has two ways to declare a variable. val creates a read-only (immutable) variable — once set, it cannot be reassigned. var creates a variable you can reassign later. Prefer val whenever the value will not change.

val name = "AlgoCademy" // read-only
var age = 10            // reassignable
age = 11                // OK
// name = "Other"       // error: val cannot be reassigned

Accessing values in variables:

Now we can use this label anywhere in our program to access the value in that box. We can print it for example:

// We create and initialize two variables:
val name: String = "AlgoCademy"
val age: Int = 10

// We access the variables:
println(name)
println(age)

The output of this code is:

AlgoCademy
10

Important notice:

We almost never want to create a variable without initializing it! It's a bad coding practice and can create a lot of problems.


Assignment
Follow the Coding Tutorial and let's create some variables.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check