Skip to content
LumenaryAcademy
Foundations 50 min

First steps in Julia

The two-language problem Julia was built to solve, how to install it, and your first hour in the REPL.

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

The two-language problem

Imagine you are a climate scientist with an idea for a better model of how clouds form. You sketch it in Python, or MATLAB, or R: a few hundred lines, easy to change, full of plots. It works on a small grid. Then you try the real grid, and a run that took four seconds now takes four days. The interpreted inner loops are simply too slow. So you do what scientists have done for decades: you rewrite the hot parts in C, C++ or Fortran, glue them back to the high-level code, and from then on every change to the model means changing code in two languages, debugging across the boundary between them, and hiring people who know both.

This is the two-language problem: one language for thinking, another for running fast. It is not just an inconvenience. The people who understand the science can no longer read the code that actually runs, the fast code is hard to change, and libraries written in the slow language cannot easily be combined with libraries written in the fast one. NumPy, SciPy and PyTorch are triumphs of engineering, but under every one of them is a large body of C, C++ or Fortran that most of their users will never open.

Julia was designed to make the two-language problem go away. You write high-level, dynamic code, with no type declarations required, an interactive prompt, and maths that looks like maths. Julia then compiles each function to machine code for the exact types it is called with, so a plain loop over numbers runs at roughly the speed of the same loop in C. The packages you use are, almost always, written in Julia all the way down, which means you can read them, step into them with a debugger, and combine them in ways their authors never planned.

That last point is less obvious than speed, and it may matter more. It comes from Julia's central idea, multiple dispatch, which you will meet properly in the third lesson. For now, hold on to the promise: one language, readable and fast. This course will also be honest about the price Julia pays for it, which you will notice within the hour: the first time you run something, Julia has to compile it, and you wait.

History & global context

From MIT to Julia 1.x

Julia was started in 2009 by Jeff Bezanson, Stefan Karpinski, Viral B. Shah and Alan Edelman, with Edelman's group at MIT as its first home. They announced it publicly in February 2012 with a blog post called Why We Created Julia, which is still worth reading: it is a cheerful list of everything they wanted at once, from the speed of C and the dynamism of Ruby to the mathematical notation of MATLAB and the macros of Lisp. That is why this course gives 2012 as Julia's year.

Six years of rapid, sometimes breaking change followed. In August 2018 the project released Julia 1.0, with a promise that mattered to everyone building on it: code written for any 1.x version keeps working on later 1.x versions. Since then each minor release (1.1, 1.2, and so on) has added features and, above all, reduced compile-time latency, while the 1.x promise has held. This course is checked against Julia 1.13, the current stable release as of late 2026, and points out features that need a recent version.

Julia's design borrows openly from older languages, and knowing where each idea came from helps you understand it:

IdeaInherited fromWhat it means in Julia
Multiple dispatchCommon Lisp's CLOS, Dylana function chooses its method from the types of all its arguments
Macros, code as dataLispprograms can build and transform Julia code before it runs
Array syntax, 1-based indexing, column-major orderFortran, MATLABA[1, 1] is the first element; columns are contiguous in memory
Just-in-time compilationmany, through LLVMeach function is compiled to native code the first time it is called with new argument types
Garbage collection, dynamic typingLisp, Python, Rubyyou never free memory or declare types unless you choose to

Julia is free and open source under the MIT licence, and its development happens in public on GitHub. A company, JuliaHub, employs some core developers and sells services, but the language itself is a community project. Today it is used in climate modelling, astronomy, pharmacology, economics, power systems, optimisation and scientific machine learning, mostly by people whose first job is science or engineering rather than software.

ComputationC

Installing Julia and meeting the REPL

Installing with juliaup

The official way to install Julia is juliaup, a small version manager. Follow the instructions at julialang.org/downloads: on Linux and macOS it is a single shell command that downloads an installer script, and on Windows juliaup is installed from the Microsoft Store or with winget. Afterwards, three commands cover most needs:

bash
juliaup status          # which Julia versions are installed, and which is the default
juliaup update          # move to the newest release in your channels
juliaup add lts         # also install the long-term-support version

Avoid installing Julia from a Linux distribution's package manager: those builds are often old or patched in ways the Julia developers do not support. Check your installation by typing julia in a terminal. You should see a banner and a prompt.

The REPL

The prompt is the REPL, for read-eval-print loop: you type an expression, Julia evaluates it and prints the result. Julia programmers spend a great deal of time here, trying ideas before they become code in files. A short session:

text
julia> 2 + 2
4

julia> 1 / 3
0.3333333333333333

julia> typeof(1 / 3)
Float64

julia> 2^64
0

julia> big(2)^64
18446744073709551616

julia> name = "Wanjiru"
"Wanjiru"

julia> "Habari, $(name)! Your name has $(length(name)) letters."
"Habari, Wanjiru! Your name has 7 letters."

julia> "Habari, $name!"
ERROR: UndefVarError: `name!` not defined in `Main`
Suggestion: check for spelling errors or missing imports.

julia> [1, 2, 3] .^ 2
3-element Vector{Int64}:
 1
 4
 9

Look at the fourth result. 2^64 printed 0, not an error. Ordinary integers are 64-bit machine integers, and arithmetic on them wraps around silently, exactly as in C; big(2) makes an arbitrary-precision integer instead. This is a deliberate trade-off for speed, and the next lesson discusses it.

The REPL has modes, each entered by one key at the start of an empty line and left with Backspace:

KeyPromptWhat it does
(none)julia>evaluate Julia code
?help?>show the documentation of a function, type or macro, e.g. ?println
;shell>run a shell command, e.g. ;ls
]pkg>manage packages: add, rm, status, update, activate

A few habits pay off immediately. Tab completes names, and also turns LaTeX-like names into symbols: type \alpha then Tab to get α, or \sqrt then Tab for √. If you type ? followed by a name you only half remember, the help mode suggests close matches. The up arrow searches history by what you have already typed. And ending a line with a semicolon, as in y = 5;, suppresses the printed result.

Packages in one paragraph

Julia's package manager, Pkg, is built in. Press ] and type add Example to install a package from the General registry, the community's public list of registered packages; status lists what is installed and update upgrades it. Packages are installed into an environment, described by two files, Project.toml and Manifest.toml, and every project can have its own. The default environment is named after the Julia version, which is why the package prompt reads something like (@v1.13) pkg>. Lesson 7 treats environments properly; for now, remember that ] is the way in.

Running scripts

For anything longer than a few lines, write a file with the extension .jl and run it from the terminal:

bash
julia hello.jl                     # run a script
julia --project=. hello.jl         # run it in the environment of the current folder
julia -t auto hello.jl             # with as many threads as the machine has cores
julia -e 'println(1 + 1)'          # run one expression

Inside the REPL, include("hello.jl") runs a file in the current session, which keeps everything it defined available for you to inspect afterwards.

Worked examplesH

First programs

Hello, Julia

julia
# hello.jl: a first Julia program
println("Hello, Julia!")
println("This is Julia ", VERSION, " running on ", Sys.KERNEL, ".")

It prints:

text
Hello, Julia!
This is Julia 1.13.4 running on Linux.

There is no main function, no class and no import: a Julia script runs from top to bottom. println prints its arguments, all of them, one after another, and then a newline; print does the same without the newline. VERSION is a constant holding the running Julia's version, and Sys.KERNEL names the operating system. Comments start with #; a block comment is written between #= and =#.

Values, names and interpolation

julia
# Values, names and string interpolation
city = "Nairobi"
altitude_m = 1795          # an Int
mean_temp_c = 17.8         # a Float64
rainy = true               # a Bool

println("$city sits at $altitude_m metres.")
println("Its mean temperature is $(mean_temp_c)°C, or $(9/5 * mean_temp_c + 32)°F.")

@show typeof(altitude_m) typeof(mean_temp_c) typeof(rainy) typeof(city)

# Arithmetic reads like the blackboard
x = 3
y = 2x^2 + 1               # 2x means 2 * x
θ = π / 6                  # type \theta then Tab in the REPL
@show y sin(θ) 7 / 2 7 ÷ 2 7 % 2 "Ki" * "su" * "mu"

It prints:

text
Nairobi sits at 1795 metres.
Its mean temperature is 17.8°C, or 64.03999999999999°F.
typeof(altitude_m) = Int64
typeof(mean_temp_c) = Float64
typeof(rainy) = Bool
typeof(city) = String
y = 19
sin(θ) = 0.49999999999999994
7 / 2 = 3.5
7 ÷ 2 = 3
7 % 2 = 1
"Ki" * "su" * "mu" = "Kisumu"

Several things here are characteristic of Julia:

  • No declarations. A name is created by assigning to it, and the value carries its type: 1795 is an Int64, 17.8 a Float64, true a Bool, and text in double quotes a String.
  • String interpolation. Inside a string, $name inserts the value of a variable and $(expression) the value of any expression. The temperature conversion shows an honest floating-point result, 64.03999999999999, because 17.8 has no exact binary representation; lesson 2 explains why, and how to round for display.
  • Maths notation. 2x^2 means 2 times x squared: a number written directly before a name multiplies it. π is built in (type \pi and Tab, or write pi), and so are Greek and other Unicode letters as names. Notice that sin(π/6) is not exactly 0.5; that is floating-point rounding, not a bug.
  • Two divisions. / always produces a floating-point number, so 7 / 2 is 3.5. Integer division is ÷ (type \div and Tab) or the function div(7, 2), and % is the remainder.
  • Strings join with *. Julia uses * for concatenation because, in algebra, * is used for non-commutative products, and joining text is not commutative.
  • @show is a macro (anything starting with @). It prints each expression together with its value, which makes it the quickest debugging tool there is.

A loop, a function and a little mathematics

In 1734 Leonhard Euler found that 1+14+19+116+⋯=π261 + \tfrac14 + \tfrac19 + \tfrac1{16} + \cdots = \tfrac{\pi^2}{6}, the famous Basel problem. That gives a slow but charming way to estimate π: add up many terms, multiply by six and take the square root.

julia
# The Basel problem: 1 + 1/4 + 1/9 + ... approaches π²/6.
function basel(n)
    total = 0.0
    for k in 1:n
        total += 1 / k^2
    end
    return total
end

for n in (10, 1_000, 100_000)
    s = basel(n)
    estimate = √(6s)
    println(rpad(n, 8), "terms: π ≈ ", estimate, "  (error ", abs(π - estimate), ")")
end

# The same sum as a one-line generator expression:
println(sum(1 / k^2 for k in 1:1_000) ≈ basel(1_000))

It prints:

text
10      terms: π ≈ 3.04936163598207  (error 0.09223101760772323)
1000    terms: π ≈ 3.1406380562059946  (error 0.00095459738379855)
100000  terms: π ≈ 3.141583104326456  (error 9.549263336960934e-6)
true

The function ... end block defines a function; return gives back its result (and could be left out, because a Julia function returns the value of its last expression). for k in 1:n loops over the range from 1 to n inclusive. Blocks end with the keyword end; indentation is for humans only. Underscores in 100_000 are ignored and just make the number readable. rpad(n, 8) pads a value to eight characters. √(6s) is the same as sqrt(6 * s).

The last line shows two more idioms. sum(1 / k^2 for k in 1:1_000) is a generator expression: it produces the terms one by one without building a list. And ≈ (typed \approx, or written isapprox) compares floating-point numbers with a sensible tolerance, which is almost always what you want instead of == for results of arithmetic.

ExplanationH

Why the first call is slow, and how Julia programmers work

Here is something you will notice in your first session. Run a function once and it takes a moment; run it again and it is instant. The reason is the heart of Julia's design.

When you call a function, Julia looks at the types of the arguments, say an Int64, and asks whether it already has machine code for this function with an Int64. If not, it infers the type of every variable inside the function, generates optimised code through the LLVM compiler framework (the same back end used by Clang and Rust), and stores the result. The second call with the same types reuses that compiled code. A call with different types, say a Float64, triggers another compilation, producing a second, separately optimised version. This is called specialisation, and it is why plain Julia loops are fast.

The cost is compilation latency, often called time to first X (TTFX): the first plot, the first data-frame operation, the first anything. Here is the effect, measured with the @time macro on a function that sorts 100 000 pairs by a custom key:

julia
f(v) = sort(v; by = x -> (abs(x[2]), x[1]))
v = [(i, sin(i)) for i in 1:10^5]
@time f(v)
@time f(v)

On our test machine it printed the following; your numbers will differ:

text
  0.291307 seconds (239.29 k allocations: 15.698 MiB, 97.59% compilation time)
  0.007520 seconds (6 allocations: 3.055 MiB)

Almost all of the first call was compilation. Julia has cut these delays sharply since 1.0, most of all since version 1.9 began caching packages' native code when they are installed, but some latency remains part of the bargain. It shapes how experienced users work:

  • They keep a session open. Instead of running julia script.jl from scratch after every edit, they work in a long-lived REPL, so compiled code is reused.
  • They use Revise.jl. The Revise package watches your source files and updates the running session when you save, so you rarely restart. It is one of the first packages most Julia programmers install.
  • They use an editor that talks to the REPL. The Julia extension for VS Code is the most widely used, with inline results, a plot pane and a debugger. Others work happily in Emacs, Vim or Jupyter and Pluto notebooks.
  • They put code in functions. Code at the top level of a script, operating on global variables, cannot be optimised well; the same code inside a function can. Lesson 6 explains why. The Basel example above already follows this rule.

None of this is complicated, but it is different from both compiled languages (where you build once and run many times) and interpreted ones (where nothing is compiled). Julia sits between them, and the sooner you work with its grain, the more you will enjoy it.

Optional Christian reflection · Craft and patience

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

A tool that rewards patience is a small lesson in itself. The first call to a Julia function is slow because the compiler is doing careful work once so that it never has to do it again. Much good work in any field looks like this: an unglamorous investment at the start that quietly pays for itself many times over.

Common misconceptionsH

Common early mistakes

Misconception

"Interpolation ends at the variable name." It ends where the name ends, and names may contain !, digits and underscores. In the REPL session above, "Habari, $name!" failed with UndefVarError: `name!` not defined, because Julia read the name as name!. Write $(name)! whenever the next character could belong to a name.

Misconception

"Integers in Julia never overflow." They do, silently: 2^64 gave 0. Int is a 64-bit machine integer on 64-bit systems, chosen for speed. When you need exact large integers, use big(...) or the type BigInt; when you need to know about overflow, use checked functions such as Base.checked_add.

Misconception

"Julia is slow; I timed it." If you timed a script once from the command line, you timed Julia starting up and compiling everything it used. Time the second call of a function, ideally with a benchmarking package such as BenchmarkTools.jl, and put the work inside functions.

Misconception

"Arrays start at 0, like in every real language." In Julia, as in Fortran, MATLAB, R and mathematics textbooks, the first element of an array is at index 1, and ranges like 1:n include both ends. It feels strange for a week and then it doesn't.

Exercises

Exercises

Try to answer each question before running anything; then check yourself in the REPL.

1. First steps in Julia

Warm-upHuman

Which of these best describes the two-language problem that Julia was designed to solve?

Choose one

2. First steps in Julia

Warm-upComputational

What does this program print?

x = 4
println("$x squared is $(x^2)")

3. First steps in Julia

CoreComputational

What does this line print?

println(7 / 2, " ", 7 ÷ 2, " ", 7 % 2)

4. First steps in Julia

CoreComputational

What does println(typeof(6 / 3)) print?

5. First steps in Julia

CoreComputational

What does this print?

x = 3
println(2x^2)

6. First steps in Julia

Warm-upComputational

How many times does the body of for k in 3:7 ... end run?

7. First steps in Julia

Warm-upHuman

At an empty julia> prompt, which key switches the REPL to package mode, where you can type add Example?

Choose one

8. First steps in Julia

CoreHuman

You call f(10) and it takes 0.3 seconds; a second f(10) takes 0.002 seconds. Which explanation is correct?

Choose one

Further reading and resources