Skip to content

Julia Basic Syntax

This chapter introduces the basic syntax rules of Julia to help you get started quickly.

Comments

Single-Line Comments

Use # to start single-line comments:

julia
# This is a single-line comment
x = 10  # End-of-line comment

Multi-Line Comments

Use #= and =# to enclose multi-line comments:

julia
#=
This is a multi-line comment
It can span multiple lines
For detailed explanations
=#

Variables

Variable Naming

Julia variable names follow these rules:

  • Start with letter (A-Z, a-z), underscore (_), or Unicode character
  • Can contain digits (but cannot start with digit)
  • Case-sensitive
  • Cannot use reserved words
julia
# Valid variable names
x = 1
my_variable = 2
变量 = 3        # Chinese supported
α = 0.5         # Greek letters supported
_private = 4

# Invalid variable names
# 2nd = 5       # Cannot start with digit
# for = 6       # Cannot use reserved word

Variable Assignment

julia
# Single assignment
x = 10

# Multiple assignment
a, b, c = 1, 2, 3

# Swap variables
a, b = b, a

# Chained assignment
x = y = z = 0

Constants

Use const to declare constants:

julia
const PI = 3.14159
const MAX_SIZE = 100

# Attempting to modify constants produces warnings
# PI = 3.14  # Warning: redefining constant

Basic Data Types

Numeric Types

julia
# Integers
a = 42          # Int64 (on 64-bit systems)
b = Int32(42)   # Int32

# Floating point
c = 3.14        # Float64
d = Float32(3.14)  # Float32

# Boolean
e = true
f = false

Characters and Strings

julia
# Character (single quotes)
char = 'A'

# String (double quotes)
str = "Hello, Julia!"

# Multi-line string
multiline = """
This is a
multi-line string
"""

Output

julia
# print doesn't add newline
print("Hello")
print(" World")  # Output: Hello World

# println adds newline
println("Hello")
println("World")
# Output:
# Hello
# World

String Interpolation

Use $ for string interpolation:

julia
name = "Julia"
age = 10

println("$name is $age years old.")
# Output: Julia is 10 years old.

# Expression interpolation
println("2 + 3 = $(2 + 3)")
# Output: 2 + 3 = 5

Formatted Output

Use @printf macro:

julia
using Printf

@printf("Integer: %d\n", 42)
@printf("Float: %.2f\n", 3.14159)
@printf("String: %s\n", "Hello")
@printf("Zero-padded: %05d\n", 42)  # Output: 00042

Input

readline

julia
print("Enter your name: ")
name = readline()
println("Hello, $name!")

Reading Numbers

julia
print("Enter a number: ")
input = readline()
num = parse(Int, input)
println("You entered: $num")

# Or use Float64
num_float = parse(Float64, readline())

Code Blocks

Semicolons

Semicolons suppress output in REPL, or separate multiple statements on one line:

julia
# Suppress output
x = 10;

# Multiple statements on one line
a = 1; b = 2; c = 3

Code Blocks

Use begin...end to create code blocks:

julia
result = begin
    x = 10
    y = 20
    x + y  # Last expression value becomes block value
end
println(result)  # Output: 30

Can also use parentheses:

julia
result = (x = 1; y = 2; x + y)
println(result)  # Output: 3

Scope

Global Scope

Variables defined at module top level:

julia
global_var = 100

function show_global()
    println(global_var)
end

Local Scope

Inside functions, loops, conditionals:

julia
function local_example()
    local_var = 10  # Local variable
    println(local_var)
end

# local_var not accessible outside function

let Blocks

Create new local scope:

julia
let
    x = 10
    y = 20
    println(x + y)
end
# x and y not accessible outside let block

global Keyword

Access or modify global variables in local scope:

julia
counter = 0

function increment()
    global counter
    counter += 1
end

increment()
println(counter)  # Output: 1

Modules

Defining Modules

julia
module MyModule

export greet  # Exported function

const VERSION = "1.0"

function greet(name)
    println("Hello, $name!")
end

function internal_function()
    # Internal function, not exported
end

end  # module

Using Modules

julia
# Use all exported content from module
using MyModule
greet("Julia")

# Import only specific content
using MyModule: greet

# Import module itself
import MyModule
MyModule.greet("Julia")

Standard Library Modules

julia
using Statistics
using LinearAlgebra
using Random

Expressions and Statements

Compound Expressions

julia
# Using begin...end
z = begin
    x = 1
    y = 2
    x + y
end

# Using semicolon chain
z = (x = 1; y = 2; x + y)

Conditional Expression (Ternary Operator)

julia
x = 10
result = x > 5 ? "greater than 5" : "5 or less"
println(result)  # Output: greater than 5

Short-Circuit Evaluation

julia
# && - if first is true, execute second
x = 10
x > 5 && println("x is greater than 5")

# || - if first is false, execute second
x < 5 || println("x is not less than 5")

Nothing and Missing

Nothing

Represents "no value" or function has no return value:

julia
function no_return()
    println("This function returns nothing")
end

result = no_return()
println(result)        # Output: nothing
println(isnothing(result))  # Output: true

Missing

Represents missing data (similar to SQL NULL):

julia
data = [1, 2, missing, 4, 5]

println(ismissing(data[3]))  # Output: true

# Missing propagation
println(1 + missing)  # Output: missing

# Skip missing values
using Statistics
println(mean(skipmissing(data)))  # Output: 3.0

Type Annotations

Julia allows optional type annotations:

julia
# Variable type annotation
x::Int = 10

# Function parameter types
function add(a::Int, b::Int)
    return a + b
end

# Return type
function multiply(a, b)::Float64
    return a * b
end

Code Style Suggestions

  1. Variable names use lowercase letters and underscores

    julia
    my_variable = 10
  2. Type names use CamelCase

    julia
    struct MyCustomType
        field::Int
    end
  3. Function names use lowercase letters

    julia
    function calculate_sum(arr)
        return sum(arr)
    end
  4. Constants use uppercase letters

    julia
    const MAX_ITERATIONS = 1000
  5. Use appropriate spacing and indentation

    julia
    function example(x, y)
        if x > 0
            return x + y
        else
            return y
        end
    end

Next Steps

After mastering basic syntax, continue learning:

Content is for learning and research only.