Skip to main content
Quick Reference

Julia Cheatsheet

Julia on one page — arrays, multiple dispatch, broadcasting, and the traps around indexing, strings, and types.

10 sections 10 tables 14 code snippets

Run a file

A file

julia analysis.jl

A vector

pages = [412, 300, 180]

The names

NameMeaning
juliaRuns a file. The REPL prompt is julia>
=Assigns a name. # comments to the end of the line
Commas[1, 2, 3] is a Vector. Spaces, [1 2 3], are a 1 by 3 Matrix
;Starts the next row. [1 2; 3 4] is a 2 by 2 matrix
1 and 1.01 is an Int, Int64 on a 64-bit machine. 1.0 is Float64
endCloses if, for, function, struct, and a block

This page is the Julia language. DataFrames.jl and plotting packages are left out.

Arrays

The first value

pages[1]

The last value

pages[end]

Index rules

ExpressionResult
pages[1]The first value. Indexes start at 1
pages[0]A BoundsError. Zero is not a valid index
pages[end]The last value. pages[begin] is the first
1:3The range 1, 2, 3. Both ends are included. collect makes a Vector
eachindexThe valid indexes. Prefer this to 1:length(pages)
StorageColumn-major. The first index changes fastest. length counts elements. size is a tuple

Numbers

Float division

5 / 2

Truncating division

div(5, 2)

Arithmetic rules

ExpressionResult
5 / 22.5, a Float64. Division with / promotes to float
div(5, 2)2. Truncates toward zero. The ÷ operator is the same call
5 // 2The rational 5//2, not a float
typemax(Int) + 1Wraps to typemin(Int). Int arithmetic does not raise
-2^2-4. Power binds tighter than the leading minus
0.1 + 0.2 == 0.3false. Compare floats with isapprox

Strings

Insert a value

title = "Dune"
"Book $title"

Text rules

FactDetail
QuotesDouble quotes build a string. Single quotes build one character
*Concatenates strings. + has no string method
$titleInserts the value. Parentheses after the dollar insert an expression
IndexesByte positions, not character counts. An index inside a character throws StringIndexError
lengthThe number of characters. ncodeunits is the number of bytes
Safe walksfirst, last, and eachindex land on character boundaries

Missing values

A fallback

year = missing
coalesce(year, 0)

Three different empties

ValueMeaning
nothingNo value. Its type is Nothing. It does not spread through arithmetic
missingA missing data point. 1 + missing is missing. missing == 1 is missing
if missingThrows. if needs a Bool
NaN == NaNfalse. NaN === NaN is true
isequalTreats NaN as equal to NaN, and missing as equal to missing
coalesceThe first argument that is not missing

Multiple dispatch

Two methods

pages_of(n::Int) = n
pages_of(title::String) = length(title)

Call rules

FactDetail
One functionEach signature is a method. The most specific method runs
Return valueThe last expression. return leaves early
!A trailing bang means the function mutates an argument, as push! does
Shared arraysThe argument is the caller array. A bang changes that array
&& and ||Return the last value they evaluate. The first value must be a Bool
importRequired to add a method to a function owned by another module. using only brings names in

Types

An immutable book

struct Book
    title::String
    pages::Int
end

Type rules

FactDetail
structFields cannot be reassigned. mutable struct allows field updates
ConcreteA concrete type such as Int has no subtypes
InvariantVector{Int} <: Vector{Integer} is false
<: in bracesVector{Int} <: Vector{<:Integer} is true. This is the argument type to accept
::On an argument, it selects a method. On a value, it checks the type
GlobalsA global that changes type slows the code. Pass the value in, or mark the binding const

Broadcasting

Add one to each page

pages .+ 1

Elementwise rules

FormWhat it does
sin.(pages)Calls sin on each element
.+Elementwise add. * on two matrices is matrix multiplication
FusionSeveral dotted calls in one expression run as one loop
mapCalls a function on each element and returns a new collection
Comprehension[x^2 for x in pages] builds a Vector
A missing dotJulia looks for a method on the whole array and throws MethodError

Mutation

Add at the end

push!(pages, 90)

In place or a copy

CallEffect
push!Appends a value and returns the same array
pop!Removes the last value
sort!Sorts in place. sort returns a new array
b = pagesAnother name for the same array. Assigning into b changes pages
copy(pages)A shallow copy. Nested arrays are still shared
A bang in a functionThe caller sees the change, because the array was not copied

Interview traps

Traps worth memorising

TrapWhat happensPrefer
[1 2 3]A 1 by 3 matrix, so later linear algebra treats it as a row[1, 2, 3] for a vector
pages[0]BoundsError. There is no element before the firstpages[1] or pages[begin]
An index inside a characterStringIndexError. Indexes are byte positionseachindex, first, or last
"a" + "b"MethodError. Strings have no +"a" * "b"
Vector{Int} <: Vector{Integer}false. The parameter is invariantVector{<:Integer} in the argument
A trailing 'Conjugate transposetranspose when conjugation is the wrong result
b = pagesBoth names share one arraycopy(pages) when the next edit must stay local
5 / 22.5, not 2div(5, 2) for truncating division
typemax(Int) + 1Wraps around. No overflow errorA wider type such as BigInt when the magnitude matters
-2^2-4, because power runs before the minus(-2)^2 when the sign belongs inside
NaN == NaNfalseisnan, or === when you mean the same bits
if missingThrows, because missing is not a Boolismissing or coalesce before the branch

Commas make a vector

[412, 300, 180]

Stay on character boundaries

eachindex("Dune")

How to use this page: build vectors with commas, index from 1, and broadcast with a dot. Walk strings with eachindex, and write Vector{<:Integer} when a method should accept every integer vector.