CodeToLive

Julia Programming Basics

Learn the fundamentals of the Julia programming language for scientific computing and data analysis.

Basic Syntax

# Hello World
println("Hello, World!")

# Variables and types
x = 10          # Int64
y = 3.14        # Float64
name = "Julia"  # String
flag = true     # Bool

# Type annotations
age::Int32 = 25

Julia has dynamic typing but allows type annotations for performance.

Control Flow

# If-else statement
if x > 0
    println("Positive")
elseif x < 0
    println("Negative")
else
    println("Zero")
end

# For loop
for i in 1:5
    println(i)
end

# While loop
n = 0
while n < 3
    println(n)
    n += 1
end

Julia's control structures are similar to other languages but end with end.

Functions

# Basic function
function greet(name)
    return "Hello, $name!"
end

# Shorthand syntax
square(x) = x^2

# Multiple dispatch
function calculate(x::Number, y::Number)
    x + y
end

function calculate(x::String, y::String)
    string(x, y)
end

Julia supports multiple dispatch for polymorphic functions.

Arrays and Matrices

# Creating arrays
arr1 = [1, 2, 3]           # 1D array
arr2 = [1 2; 3 4]          # 2x2 matrix
arr3 = rand(3, 3)          # Random 3x3 matrix

# Array operations
sum_arr = arr1 .+ 5        # Broadcast addition
mat_prod = arr2 * arr2     # Matrix multiplication

# Comprehensions
squares = [x^2 for x in 1:5]

Julia provides powerful array operations with concise syntax.

Type System

# Defining custom types
struct Point
    x::Float64
    y::Float64
end

# Methods for custom types
function distance(p1::Point, p2::Point)
    sqrt((p1.x - p2.x)^2 + (p1.y - p2.y)^2)
end

# Using the type
p1 = Point(1.0, 2.0)
p2 = Point(4.0, 6.0)
println(distance(p1, p2))
← Back to Tutorials