Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 40 ยท Getting Started

Your First Julia Program

Write your first Julia program: print with println, add comments, create variables, build strings with interpolation and meet 1-based indexing.

Time to write some Julia. In this lesson you will print text, leave comments, store values in variables, build strings with interpolation and take a first look at the feature that surprises most newcomers: Julia counts from 1, not 0.

All Julia code here is read-only, and the output a real Julia session prints is shown in comments after #. Python stand-ins let you run the same ideas on this page. If you have not set up Julia yet, see Installing Julia and Using the REPL.

Hello, world

JULIA
println("Hello, world!")
# Hello, world!

println prints its arguments and adds a newline. print does the same without the newline. Both accept several arguments and join them without spaces:

JULIA
print("Hello, ")
print("Julia")
println()                      # just a newline
println("Total: ", 3 + 4)      # Total: 7
println("a", "b", "c")         # abc

Text goes between double quotes. Single quotes are for a single character ('a'), not strings. That is a common stumble if you come from Python.

You can save the first example as hello.jl and run it with julia hello.jl. In the REPL, println is optional for checking a value, because the REPL prints the result of every line. In a script, nothing is printed unless you ask for it.

Comments

JULIA
# This is a single-line comment
x = 5   # a comment after code

#=
This is a multi-line comment.
   #= They can even be nested. =#
=#

A line comment starts with #. A block comment sits between #= and =#, and block comments can nest.

Variables

You create a variable by assigning to it. There is no var, let or type keyword:

JULIA
name = "Ada"
age = 36
height = 1.68
is_student = false

typeof(name)      # String
typeof(age)       # Int64
typeof(height)    # Float64
typeof(is_student)  # Bool

A variable can later hold a value of a different type, because Julia is dynamically typed:

JULIA
x = 10
x = "ten"     # allowed

That said, code is faster and clearer when a variable keeps one type, a habit explained in Performance Tips.

Names may contain letters, digits, underscores and most Unicode characters. They cannot start with a digit. The convention is snake_case for variables and functions, CamelCase for types, and ALL_CAPS for constants. Because Unicode is fine, math code often uses real symbols:

JULIA
ฮฑ = 0.05
ฮธ = ฯ€ / 4
ฮ”t = 0.1

In the REPL, type \alpha and press Tab to get ฮฑ.

Julia also has built-in constants such as ฯ€ (also written pi), โ„ฏ and Inf. A global declared with const is promised never to change its type, so the compiler can rely on it:

JULIA
const GRAVITY = 9.81

String interpolation

Use $ inside a string to insert the value of a variable. For anything more than a name, wrap the expression in parentheses:

JULIA
name = "Ada"
age = 36

println("Hello, $name!")                 # Hello, Ada!
println("Next year: $(age + 1)")         # Next year: 37
println("Length of name: $(length(name))")  # Length of name: 3

To write a literal dollar sign, escape it: "Cost: \$5".

You can also join strings with *, not +. This looks odd at first, but * is the mathematical convention for concatenation as a product:

JULIA
"Hello, " * "world"      # "Hello, world"
"ab" ^ 3                 # "ababab"

String details come later in Strings and Characters.

The Python equivalent of interpolation is the f-string. This stand-in shows the same ideas; the syntax differs but the thinking is the same.

Python Interpolation, the Python way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Julia, the operators for strings are ^ (repeat) and * (join), where Python uses * and +.

Reading input

readline() reads a line from standard input and returns it as a string. parse converts it to a number:

JULIA
print("Your name: ")
name = readline()
print("Your age: ")
age = parse(Int, readline())
println("$name will be $(age + 1) next year.")

If a user types Ada and 36, the last line prints Ada will be 37 next year.

A first look at 1-based indexing

Julia arrays and strings start at index 1, as in mathematics, R, MATLAB and Fortran. The last element is at index length(x), and the keyword end stands for the last index:

JULIA
fruits = ["apple", "banana", "cherry"]

fruits[1]        # "apple"
fruits[3]        # "cherry"
fruits[end]      # "cherry"
fruits[0]        # BoundsError: attempt to access 3-element Vector{String} at index [0]
length(fruits)   # 3
1:length(fruits) # 1:3

Trying index 0 is an error, not "the one before the first". The full story, including slicing, is in Arrays and Vectors.

Counting in Julia

Starts at 1 The first element is x[1].
Ends at end x[end] is the last element.
Length The last index equals length(x).

Ranges include both ends, so 1:3 holds 1, 2 and 3.

1 / 2

The easiest way to feel the difference is a helper that converts between the two systems. This stand-in wraps a Python list so that you can index it the Julia way.

Python A 1-based list (analogy)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real Julia arrays are 1-based natively. The wrapper only imitates the behavior, and the error text is not Julia's own message.

Putting it together

Here is a short but complete program:

JULIA
# temperature.jl
celsius = 21.5
fahrenheit = celsius * 9 / 5 + 32

println("$celsius ยฐC is $fahrenheit ยฐF")
# 21.5 ยฐC is 70.7 ยฐF

readings = [18.0, 21.5, 19.25]
println("First reading: ", readings[1])
println("Last reading:  ", readings[end])
println("Count: ", length(readings))
# First reading: 18.0
# Last reading:  19.25
# Count: 3

Notice that / always returns a floating-point number in Julia, even for two integers: 7 / 2 is 3.5. For integer division use div(7, 2) or 7 รท 2, covered in Numbers and Math.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line prints text followed by a newline?

    println adds a newline after its arguments. print does not.
  2. 2. How do you insert age + 1 into a string?

    $name works for a plain variable, but any other expression needs parentheses: $(age + 1).
  3. 3. What is fruits[1] for fruits = ["apple", "banana"]?

    Julia indexing starts at 1, so the first element is at index 1.
  4. 4. Which operator joins two strings in Julia?

    Julia uses * for concatenation and ^ for repetition. + is not defined for strings.
  5. 5. What does 7 / 2 evaluate to?

    / always does floating-point division. Use div(7, 2) or 7 รท 2 for the integer quotient 3.

Summary

  • println prints with a newline, print without one.
  • Comments use # for one line and #= ... =# for blocks.
  • Variables are created by assignment; no type keyword is needed, and snake_case is the convention.
  • $name and $(expression) interpolate values into strings; * joins strings and ^ repeats them.
  • Indexing starts at 1, end is the last index, and index 0 is an error.
  • / gives a float; integer division is div or รท.

Next, explore the basic building blocks in Numbers and Math.