Variables are some names given to the memory location to which they are assigned. These memory locations are used to store values that can be accessed by using the name of the location, i.e. Variable. Unlike C and Java, variables in Julia need not to be written with a Datatype. Julia auto-assigns the variable type by analyzing the type of value assigned to it.
Declaring and Initializing Variables:
Variables in Julia can be declared by just writing their name. There’s no need to define a datatype with it. Initializing variables can be done at the time of declaring variables. This can be done by simply assigning a value to the named variable.
variable_name = value
Rules for naming a variable in Julia
- Variable names in Julia must start with an underscore, a letter(A-Z or a-z) or a Unicode character greater than 00A0(nbsp).
- Variable names can also contain digits(0-9) or !, but must not begin with these.
- Operators like (+, ^, etc.) can also be used to name a variable.
- Variable names can also be written as words separated by underscore, but that is not a good practice and must be avoided unless necessary.
Example:
# Julia program to define variables # Assigning Integer x = 10
# Assigning String y = "Hello World"
# Assigning Float Value z = - 15
# Using Operator as variable name + = "a"
# Using Unicode as variable name ∀ = 30
println(x) println(y) println(z) println( + )
println(∀) |
Output:
How to get Variable datatype?
Julia assigns the variable datatype by itself at the time of initializing a variable, but what if there is a need to check what datatype a particular variable is?. Julia takes care of such things as well, if there is a need to check variable datatype, Julia provides a predefined function typeof(). This typeof() function takes the variable name as a parameter and will return its datatype. This typeof() function can be used inside a println() statement to show the datatype on the console. Example:
# Julia program to use typeof() function # Assigning Integer x = 10
# Assigning String y = "Hello World"
# Using typeof() function println(typeof(x)) println(typeof(y)) |
Output:
Scope of a Variable
The scope of a variable means that which variable can be accessed from which block of the code. Julia allows assigning different values to the same variable name if it is not defined in the same scope block. Scope block of a variable can be a for loop, a while loop, or a function(). Example:
# Julia program to define # Scope of a Variable # Declaring a function function Geeks(a) # Performing operation
return a + b
end # Defining for loop for i in 5 : 10
# Initializing variable
b = i
println(Geeks( 1 ))
end |
# Julia program to define # Scope of a Variable # Declaring a function function Geeks(a) # Performing operation
return a + b
end # Defining for loop for i in 5 : 10
# Initializing variable globally
global b = i
println(Geeks( 1 ))
end |