Variables can be seen as containers used to store data that the program can use over time and can be called at any point in the codebase. Unlike C and Java, Julia variables need not be written with a Datatype. It auto-assigns the data type automatically, like Python.
message = "Hello World"println(message)
One of the features of a powerful language is the ability to manipulate variables. In Julia, a variable can be overwritten (the content of a variable is replaced with a new one). Using the previous example we do the following:
message = "Hello World"println(message)message = "I love Julia"println(message)
See how the message was overwritten.
Variables can be given any name as long as it's meaningful to the codebase. Some of the rules in Python's naming convention apply here. That includes the following:
A variable cannot start with a number.
7letters = "some text"println(7letters)
A variable can start with uppercase, but it's conventional to begin variables with the lower case.
You use the underscore character "_" for variables with long names. Leaving a space would give an error.
your name = "Julia"println(your name)
Keywords cannot be used as variable names in Julia. For example, begin
is a keyword in Julia.
begin = "Exploration"println(begin)
Note: You do not need to memorize the keywords. Keywords are displayed in a different color in most development environments.
A statement is a piece of code that performs a specific task, such as creating a variable or displaying a value. The assignment of a value to a variable is written in a statement.
An assignment statement creates a new variable and gives it a value.
note = "random words"
Displaying the value of a variable is also done with a statement. From the previous example,
note = "random words"println(note)
A combination of values, variables, and operators is called an expression. A variable, like a value, is regarded as an expression by itself. Below is a practical representation of an expression using the Julia REPL.
Type julia
in the terminal below. The Julia REPL comes up immediately.
Type in 37
. When you type in an expression in the REPL, it gets evaluated immediately.
Then assign n = 10
.
Perform the sum of n with 25 (n + 25
). The result would be 35
.
In Julia, variables can be assigned globally or locally. A global variable is a variable that can be used throughout the program, while a local variable is a variable that is declared in a function and given a local scope.
Julia uses the global
inbuilt function to declare global variables. For example:
global b = 4function addNumber(a)return a + bendprintln(addNumber(3))
The result of this is 7
.
Like most other programming languages, Julia makes provision for creating variables, statements, and expressions, which makes writing readable and portable code easier. Getting the hang of how it is used is essential for all developers.