Variables in Julia
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
These variable values can be of any datatype: String, Integer, float, array, etc. as per user needs. Julia will assign the datatype automatically to the variable.
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.
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:
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:
Above code generates an Error, because the scope of the variable b is limited to the for loop, while it is being accessed from the function Geeks(). To resolve this error, Julia provides a keyword global. This keyword makes the changes made to the variable, global. Use of global keyword: Above given code which was generating an Error because of the variable scope, can also be resolved with the use of a predefined keyword ‘global‘. This keyword is used to define a global variable and if any changes are being made to the variable then those changes will be effective globally. Example: