Skip to content
LumenaryAcademy
Foundations 55 min

Types, values and control flow

Julia's numbers and its tree of types, what type annotations really do, and the loops, conditionals and comprehensions you will write every day.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Dynamic, but not untyped

Julia is often described as dynamically typed, and that is true: you never have to write a type, a variable can hold an integer now and a string later, and errors about types appear when the program runs rather than when it is compiled. But it would be a mistake to conclude that types matter less in Julia than in, say, Python. They matter more. Every value has a precise concrete type, the compiler tracks types through your code to make it fast, and, as you will see in the next lesson, the types of a function's arguments decide which code runs.

So this lesson is about getting to know the values Julia works with: its numbers, which are closer to the machine than in most high-level languages; the tree of types they sit in; what a type annotation does and does not do; and then the everyday machinery of conditionals, loops and comprehensions that moves those values around.

DefinitionsH

Numbers and the type tree

The numbers you will meet

julia
# A tour of Julia's number types
for x in (42, 4.2, 42f0, 0x2a, 3//4, 2 + 3im, big(42), true, 'λ', "λ")
    println(rpad(repr(x), 10), " is a ", typeof(x))
end

println()
println("Int64 runs from ", typemin(Int64), " to ", typemax(Int64))
println("typemax(Int64) + 1 = ", typemax(Int64) + 1)          # wraps around
println("big(typemax(Int64)) + 1 = ", big(typemax(Int64)) + 1)
println("Int8(127) + Int8(1) = ", Int8(127) + Int8(1))

println()
println("0.1 + 0.2 = ", 0.1 + 0.2)
println("0.1 + 0.2 == 0.3 is ", 0.1 + 0.2 == 0.3, ", but ≈ says ", 0.1 + 0.2 ≈ 0.3)
println("eps(1.0) = ", eps(1.0), ", the gap between 1.0 and the next Float64")
println("1/0 = ", 1 / 0, ", 0/0 = ", 0 / 0, ", and NaN == NaN is ", NaN == NaN)
println("1//3 + 1//6 = ", 1//3 + 1//6, " exactly")
println("(1 + 2im) * (1 - 2im) = ", (1 + 2im) * (1 - 2im))

It prints:

text
42         is a Int64
4.2        is a Float64
42.0f0     is a Float32
0x2a       is a UInt8
3//4       is a Rational{Int64}
2 + 3im    is a Complex{Int64}
42         is a BigInt
true       is a Bool
'λ'        is a Char
"λ"        is a String

Int64 runs from -9223372036854775808 to 9223372036854775807
typemax(Int64) + 1 = -9223372036854775808
big(typemax(Int64)) + 1 = 9223372036854775808
Int8(127) + Int8(1) = -128

0.1 + 0.2 = 0.30000000000000004
0.1 + 0.2 == 0.3 is false, but ≈ says true
eps(1.0) = 2.220446049250313e-16, the gap between 1.0 and the next Float64
1/0 = Inf, 0/0 = NaN, and NaN == NaN is false
1//3 + 1//6 = 1//2 exactly
(1 + 2im) * (1 - 2im) = 5 + 0im

Some notes on that output:

  • Int64 is the default integer on 64-bit machines (Int is an alias for it), and Float64 is the default floating-point number. 42f0 is a 32-bit float, used on GPUs and wherever memory matters more than precision. 0x2a is hexadecimal and makes an unsigned UInt8.
  • Integers wrap around. typemax(Int64) + 1 is typemin(Int64), and an Int8 holding 127 plus 1 becomes −128. Julia chooses this, as C and Rust's release builds do, because checking every addition would slow down every loop. For exact arithmetic on huge numbers use BigInt; for money, use integers of the smallest unit or a decimal package.
  • Floating-point numbers are binary fractions. 0.1 + 0.2 is not exactly 0.3 in any language that uses IEEE 754 doubles, which is nearly all of them; Julia simply shows you the full result. Compare with ≈ (isapprox), and remember eps(1.0), about 2.2 × 10⁻¹⁶, the relative precision of a Float64. Division by zero gives Inf and 0/0 gives NaN ("not a number"), which is not equal even to itself.
  • Exact rationals and complex numbers are built in. 1//3 + 1//6 is exactly 1//2, and im is the imaginary unit.
  • Char and String differ. Single quotes make one Unicode character; double quotes make a string. Julia strings are UTF-8, so length("λ") is 1 character while ncodeunits("λ") is 2 bytes.

The type tree

Every type in Julia has a supertype, and following supertypes always ends at Any, the type of everything. Types come in two kinds:

Definition— Abstract and concrete types

A concrete type, such as Int64 or String, can have values (instances), and has a fixed memory layout. An abstract type, such as Real or AbstractString, cannot have instances; it exists to group related types, so that you can write code for "any real number" or "any string". In Julia, concrete types are final: they cannot have subtypes. Only abstract types have children.

AnyNumberAbstractStringRealComplex{Float64}IntegerAbstractFloatRational{Int64}StringSignedUnsignedBoolFloat64Float32Int64Int8UInt8
Part of Julia's type tree. Abstract types (dashed, italic) group concrete types (solid), which are always leaves.

You can explore the tree yourself:

julia
# Walking up the type tree, and asking questions about types
function ancestry(T)
    chain = [T]
    while T !== Any
        T = supertype(T)
        push!(chain, T)
    end
    return join(chain, " <: ")
end

println(ancestry(Int64))
println(ancestry(Float64))
println(ancestry(Rational{Int64}))
println(ancestry(String))

println()
@show 3 isa Integer  3 isa Real  3 isa AbstractFloat  Int64 <: Number  Number <: Int64
@show isconcretetype(Int64) isconcretetype(Real) isabstracttype(Real)

println()
# Conversion is explicit; promotion happens when types mix in arithmetic.
@show convert(Float64, 3) Int(3.0) round(Int, 3.7) trunc(Int, -3.7) floor(Int, -3.7)
@show 1 + 2.5 promote(1, 2.5) 1 + 1//2 1.0 + (1 + 2im)
try
    Int(3.5)
catch err
    println("Int(3.5) threw ", typeof(err), ": 3.5 has no exact Int value")
end

It prints:

text
Int64 <: Signed <: Integer <: Real <: Number <: Any
Float64 <: AbstractFloat <: Real <: Number <: Any
Rational{Int64} <: Real <: Number <: Any
String <: AbstractString <: Any

3 isa Integer = true
3 isa Real = true
3 isa AbstractFloat = false
Int64 <: Number = true
Number <: Int64 = false
isconcretetype(Int64) = true
isconcretetype(Real) = false
isabstracttype(Real) = true

convert(Float64, 3) = 3.0
Int(3.0) = 3
round(Int, 3.7) = 4
trunc(Int, -3.7) = -3
floor(Int, -3.7) = -4
1 + 2.5 = 3.5
promote(1, 2.5) = (1.0, 2.5)
1 + 1 // 2 = 3//2
1.0 + (1 + 2im) = 2.0 + 2.0im
Int(3.5) threw InexactError: 3.5 has no exact Int value

x isa T asks whether a value belongs to a type; S <: T (read "S is a subtype of T") asks the same about two types. Rational{Int64} and Complex{Float64} are parametric types: one definition, Rational{T}, produces a family of concrete types, one per integer type. Lesson 5 shows how to write your own.

Strings and characters

Strings deserve a closer look, because Julia makes a choice that surprises people coming from Python. A String is a sequence of bytes in UTF-8, the encoding used by nearly all text on the web, in which an ASCII letter takes one byte and other characters take two, three or four. Julia indexes strings by byte position, not by character number, so that indexing is always fast:

text
julia> s = "São Paulo"
"São Paulo"

julia> length(s), ncodeunits(s)
(9, 10)

julia> s[1], s[2]
('S', 'ã')

julia> s[3]
ERROR: StringIndexError: invalid index [3], valid nearby indices [2]=>'ã', [4]=>'o'

julia> collect(eachindex(s))
9-element Vector{Int64}:
  1
  2
  4
  5
  6
  7
  8
  9
 10

julia> uppercase(s), replace(s, "São" => "Sao"), occursin("Paulo", s)
("SÃO PAULO", "Sao Paulo", true)

julia> split("2026-11-19", "-")
3-element Vector{SubString{String}}:
 "2026"
 "11"
 "19"

julia> join(["x", "y", "z"], ", ")
"x, y, z"

"São Paulo" has 9 characters but 10 bytes, because ã needs two. s[2] is the character starting at byte 2, and byte 3 is the middle of that character, so s[3] is an error that helpfully lists the valid neighbouring indices. In practice you rarely index strings by number at all. Loop over the characters with for c in s, get valid positions with eachindex(s), and use the many string functions: uppercase, replace, occursin, startswith, split, join, strip and regular expressions written r"...". split returns SubStrings, views into the original string that avoid copying; both String and SubString are subtypes of AbstractString, which is what functions taking text should accept.

Conversion and promotion

Julia never quietly changes a value's type when you assign it, but arithmetic on mixed types promotes them to a common type first: 1 + 2.5 turns the 1 into 1.0, and 1 + 1//2 turns the 1 into 1//1. Explicit conversion is done by calling the type as a function, as in Float64(3) or Int(3.0), and it is exact or nothing: Int(3.5) throws an InexactError rather than guessing what you meant. To choose, say so: round(Int, x), trunc(Int, x) (towards zero) and floor(Int, x) (downwards) differ for negative numbers, as the output above shows. Note that round rounds exact halves to the nearest even number by default, so round(Int, 2.5) is 2; this avoids a systematic upward bias when many values are rounded.

ExplanationH

What type annotations do

The :: operator attaches a type to something. It means different things in different places, and new Julia programmers often add annotations hoping they will make code faster. Usually they do not. Here they are in a REPL session:

text
julia> function area(r::Real)
           return π * r^2
       end
area (generic function with 1 method)

julia> area(2)
12.566370614359172

julia> area(1//2)
0.7853981633974483

julia> area("two")
ERROR: MethodError: no method matching area(::String)
The function `area` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  area(!Matched::Real)
   @ Main REPL:1


julia> function mean_of(xs)::Float64
           return sum(xs) / length(xs)
       end
mean_of (generic function with 1 method)

julia> mean_of([1, 2, 3, 4])
2.5

julia> y = (2 + 3)::Int
5

There are three uses:

  1. On function arguments, r::Real restricts which arguments the method accepts. Calling area("two") fails with a MethodError that lists the "closest candidates". This is the most important use by far, because, as the next lesson explains, it lets you write different methods for different types.
  2. On a function's return value, function mean_of(xs)::Float64 converts the result to Float64 before returning (or throws if it cannot). It is occasionally useful as documentation or a safety net.
  3. On an expression, (2 + 3)::Int is a type assertion: it checks the value's type and throws a TypeError if it is wrong. Inside a function, local x::Float64 = 1 declares that x always holds a Float64, converting assignments to it.

Why no speed-up? Because Julia compiles a separate version of a function for each combination of concrete argument types it is actually called with. area(r) without the annotation, called with an Int64, produces exactly the same machine code as area(r::Real) called with an Int64. The compiler already knows the concrete types; your annotation tells it nothing new. So the professional rule is: annotate arguments to control dispatch and to document intent, and keep annotations as general as the code allows (Real rather than Float64, AbstractVector rather than Vector{Float64}), so that your function also works with rationals, big floats, dual numbers for automatic differentiation, or GPU arrays. The one place where concrete annotations really do matter for speed, the fields of your own types, is the subject of lesson 5.

Worked examplesH

Control flow

Conditionals, loops and short circuits

The Collatz problem is a famous open question: take a positive integer, halve it if it is even, otherwise replace it by three times itself plus one, and repeat. Every starting value anyone has tried eventually reaches 1, but nobody has proved that all of them do. It makes a fine playground for control flow:

julia
# Control flow: if/elseif/else, while, for, break, continue, ternary and short-circuits.
# The Collatz rule: halve an even number; replace an odd n by 3n + 1. Does every start reach 1?
function collatz_steps(n::Integer)
    n > 0 || throw(ArgumentError("n must be positive, got $n"))
    steps = 0
    while n != 1
        n = iseven(n) ? n ÷ 2 : 3n + 1
        steps += 1
    end
    return steps
end

for start in (1, 6, 7, 27)
    s = collatz_steps(start)
    label = if s == 0
        "already there"
    elseif s < 20
        "quick"
    else
        "a long journey"
    end
    println("start ", start, ": ", s, " steps (", label, ")")
end

# The first start value that needs more than 100 steps, skipping even ones
for start in 1:1000
    iseven(start) && continue
    if collatz_steps(start) > 100
        println("first odd start needing over 100 steps: ", start)
        break
    end
end

# Looping over a collection with its positions, and over two at once
rivers = ["Nile", "Amazon", "Yangtze", "Mississippi"]
lengths_km = [6650, 6400, 6300, 3730]
for (i, river) in enumerate(rivers)
    println(i, ". ", river)
end
for (river, km) in zip(rivers, lengths_km)
    km > 6000 && println(river, " is longer than 6000 km")
end

It prints:

text
start 1: 0 steps (already there)
start 6: 8 steps (quick)
start 7: 16 steps (quick)
start 27: 111 steps (a long journey)
first odd start needing over 100 steps: 27
1. Nile
2. Amazon
3. Yangtze
4. Mississippi
Nile is longer than 6000 km
Amazon is longer than 6000 km
Yangtze is longer than 6000 km

The constructs, in order of appearance:

  • cond || action runs action only if cond is false, and cond && action only if it is true. Julia programmers use these as compact one-line if statements, especially for argument checks (n > 0 || throw(...)) and loop shortcuts (iseven(start) && continue). The left side must be a Bool.
  • while cond ... end repeats while the condition holds.
  • c ? a : b is the ternary operator: a if c is true, otherwise b. Spaces around ? and : are required.
  • if ... elseif ... else ... end is an expression, so it has a value: here it is assigned straight to label. In fact almost everything in Julia is an expression, including begin ... end blocks, whose value is their last line.
  • for x in collection loops over anything iterable: ranges, tuples like (1, 6, 7, 27), arrays, strings, dictionaries. break leaves the loop and continue skips to the next iteration.
  • enumerate pairs each element with its position, and zip walks several collections in step. Both destructure neatly into (i, river).

Conditions must be genuine Bools. Unlike C, Python or JavaScript, Julia has no notion of "truthy" values:

text
julia> if 1
           println("one is true?")
       end
ERROR: TypeError: non-boolean (Int64) used in boolean context

julia> x = -5
-5

julia> x > 0 ? "positive" : "not positive"
"not positive"

julia> result = if x < 0 "negative" else "non-negative" end
"negative"

Comprehensions and generators

A comprehension builds an array from a loop in one expression, in the notation mathematicians use for sets:

julia
# Comprehensions and generators
squares = [k^2 for k in 1:8]
println(squares)

odd_squares = [k^2 for k in 1:8 if isodd(k)]
println(odd_squares)

# Two loops make a matrix: rows from i, columns from j
table = [i * j for i in 1:3, j in 1:5]
println(typeof(table), " of size ", size(table))
display(table)

# Two loops with a filter, written on one line, make a flat list of pairs
pythagorean = [(a, b, c) for c in 1:20 for b in 1:c for a in 1:b if a^2 + b^2 == c^2]
println(pythagorean)

# A Dict comprehension, and a generator that never builds a list
words = ["sol", "luna", "estrella", "cielo"]
letters = Dict(w => length(w) for w in words)
println(letters["estrella"], " letters in estrella")
println("total letters: ", sum(length(w) for w in words))

It prints:

text
[1, 4, 9, 16, 25, 36, 49, 64]
[1, 9, 25, 49]
Matrix{Int64} of size (3, 5)
3×5 Matrix{Int64}:
 1  2  3   4   5
 2  4  6   8  10
 3  6  9  12  15
[(3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15), (8, 15, 17), (12, 16, 20)]
8 letters in estrella
total letters: 20

Read [k^2 for k in 1:8 if isodd(k)] as "the list of k2k^2 for kk from 1 to 8, keeping odd kk". When a comprehension has two loops separated by a comma, it builds a multidimensional array, one dimension per loop, as in the 3 × 5 multiplication table. When the loops are written one after another without a comma, they nest like ordinary loops and produce a flat list; the Pythagorean triples come from three nested loops with a filter. display(table) shows a matrix the way the REPL does.

Remove the brackets and you have a generator, which yields values one at a time. Passing a generator to sum, maximum, any or Dict avoids allocating a temporary array, which is both faster and lighter on memory for long sequences.

Common misconceptionsH

Pitfalls

Misconception

"A loop in a script can update a variable defined above it." At the top level of a file, it cannot do so silently. This script:

julia
total = 0
for k in 1:3
    total += k
end
println(total)

fails when run with julia script.jl. Run on Julia 1.13 it printed:

text
┌ Warning: Assignment to `total` in soft scope is ambiguous because a global variable by the same name exists: `total` will be treated as a new local. Disambiguate by using `local total` to suppress this warning or `global total` to assign to the existing global variable.
└ @ /tmp/tmpkuyhpc01/main.jl:3
ERROR: LoadError: UndefVarError: `total` not defined in local scope

A for loop introduces a new local scope, and in a file an assignment inside it creates a new local variable unless you write global total. The REPL is more forgiving and treats the same code as you probably intended, which makes the surprise worse when you move code into a file. The real fix is the one experienced programmers use anyway: put the loop inside a function, where total is simply a local variable.

Misconception

"Annotating every variable with ::Float64 makes Julia faster." It makes code less general, not faster: the compiler already knows the concrete types of a function's arguments when it compiles it. Annotations speed things up only in places where the compiler otherwise cannot know the type, chiefly the fields of structs and untyped global variables.

Misconception

"round(2.5) is 3." It is 2.0. Julia's default rounding mode for exact halves is "round half to even", as recommended by IEEE 754. If you need halves rounded away from zero, use round(x, RoundNearestTiesAway).

Exercises

Exercises

Predict each answer first, then check it in the REPL.

1. Types, values and control flow

CoreComputational

What does println(typeof(3//4 + 1)) print?

2. Types, values and control flow

Warm-upComputational

What does 0.1 + 0.2 == 0.3 evaluate to in Julia?

Choose one

3. Types, values and control flow

CoreComputational

What happens when Julia runs if 1 println("yes") end?

Choose one

4. Types, values and control flow

CoreHuman

Which of these types are abstract (they cannot have values of their own)? Select all that apply.

Choose all that apply

5. Types, values and control flow

CoreComputational

What does println(round(Int, 2.5) + round(Int, 3.5)) print?

6. Types, values and control flow

Warm-upComputational

What does println(sum([x for x in 1:10 if x % 3 == 0])) print?

7. Types, values and control flow

CoreComputational

What does println(size([i + j for i in 1:3, j in 1:4])) print?

8. Types, values and control flow

StretchComputational

An Int8 holds integers from −128 to 127. What does println(Int8(100) + Int8(100)) print?

Further reading and resources