Skip to content
AgileLogics
5 min read

Variables

Prerequisites: Your first program

A variable is a name bound to a value. There's no keyword to create one — just assign:

city = "Lagos"
temperature = 24
println("It is $temperature degrees in $city")

temperature = 27
temperature += 1
println(temperature)

a, b = 1, 2
a, b = b, a
println(a, " ", b)
It is 24 degrees in Lagos
28
2 1
  • $name inside a string inserts a variable's value (interpolation).
  • Update operators: +=, -=, *=, /=, ^=.
  • a, b = 1, 2 assigns several variables at once; a, b = b, a swaps them.

Dynamic typing

A variable can be re-bound to a value of a different type:

x = 10
println(typeof(x))
x = "ten"
println(typeof(x))
Int64
String

It works, but in performance-sensitive code it's better to keep a variable's type the same — Level 3 explains why.

Naming

  • Names start with a letter (including Unicode letters) or _, and can contain digits and !: total, x2, β, push!.
  • Names are case-sensitive: score and Score are different.
  • Convention: snake_case or lowercase words run together (isempty, haskey) for variables and functions, CamelCase for types and modules.
  • Keywords like end, for, function, and if can't be names.

Constants

const SPEED_OF_LIGHT = 299_792_458   # metres per second
println(SPEED_OF_LIGHT * 2)
599584916

const tells Julia a global name will always refer to the same value (and type), which also makes code that uses it fast. Underscores in numbers are just for readability.

Practice

Store a product name and a price in variables and print Coffee costs 3.5 dollars using interpolation. Then increase the price by 0.5 with += and print it again.

Show solution
product = "Coffee"
price = 3.5
println("$product costs $price dollars")
price += 0.5
println("$product costs $price dollars")
Coffee costs 3.5 dollars
Coffee costs 4.0 dollars