Lesson 3
Lesson 3
Lesson III
At the core of any program are variables. Variables are used to store information which may
change depending on conditions or information passed to the program. Typically, a program will
consist of instructions that dedicate to the computer what to execute, the data the program uses
when it is running and ultimately the behaviour that. This lesson focuses on variable definition
and syntax, and concludes with the scope of a variable. These are the primitive variables that
are included in the Java Development Kit (JDK) i.e. they are built into the language.
Each variable in Java has a name and a value. The name remains the same, however, the
value can change. These values are not necessarily always numbers - they can be letters or
even text. However, once you create a variable of a certain type, you can only use it to store
values of that particular type. For example, if you wanted to keep track of the amount of funds
you have in your bank account - the type of values here would be natural numbers e.g. 0, 70,
120, and so on. Natural numbers in are also called integers. So, for example, if we wanted to
create a variable of type integer in Java, it would take the following form:
int amount;
Creating a variable like this allows the computer to allocate memory for the variable, this is
referred to as declaring a variable, we use the keyword: int to specify the variable type
followed by the name of the variable.
Every programming language has its own sets of rules and conventions for the kinds of names
you’re allowed to use, and variables in Java are no different. These variables can begin with
either a letter, dollar sign, or an underscore. However, it is discouraged to begin a variable
name with the two latter options. Subsequent characters may be letters, dollar signs,
underscores, or digits. Keep in mind not to use a keyword or a reserved word like int for
variable names and try to be as descriptive as possible, when creating your variables. For
example, a variable name called: age for storing your age is much more intuitive that storing
your age in a variable called a.
Property of Airos Education
Copyright 2018 Airos Education
www.airos.co.za
1
Our variable declaration above informs the computer to create an ‘empty box’ that can store
natural numbers inside and it’s name is amount. This variable can be used to store any integer
number which can easily change as more money comes into and goes out of your bank
account. Now, the next step would be to initialise our variable i.e. assign a value to it. Usually,
when we open a bank account, we are asked to make an initial deposit of R20, R50, or R100,
so our variable will initially have one of these two values:
amount = 100;
Variables in Java are an extremely simple concept to grasp - you just need to decide what value
you want to store and what the type of that value would be. For example, if you want to store
your name in a variable called firstName, you would use the String class to create it:
String firstName;
firstName = "John";
Strings, which are widely used in Java programming, are a sequence of characters. Strings are
enclosed by double quotes. Variable declaration and initialization may also occur on the same
line:
It is extremely important to define variable data types correctly i.e. you need to choose the
correct data type for the value you want to store. Computer programming languages can be
defined as being either strongly typed or weakly typed. These terms do not have a discrete
meaning, but are rather opposing end points on a continuum that defines the leniency with
which the programming language handles data types. Strongly typed languages are known to
generate errors or even refuse to compile if the argument passed to a function does not closely
Java is a strongly typed programming language. This means that you must pay extra attention
towards declaring your variables correctly. Variables in the Java programming language must
be declared with a data type. You need to think about the range of values you wish to entrust to
a variable and the future use of these variables. This will help you choose the right data types
for your variable.
Essentially, there are three types of variables in the Java programming language:
Java supports eight primitive (the most basic data types that come with Java) data types. A
variable's data type determines the type of value a variable can store. Primitive data types are
essentially ‘types of variables’ that are predefined by the Java Development Kit and are named
by a keyword. These data types are as follows:
boolean: In programming, you may need a data type that can only have one of two values,
such as, true/false, on/off, or yes/no. For this reason, Java supports the boolean data type,
which represents one of two values - either true or false. Booleans can be declared and
initialised as follows:
The boolean data is usually used for true/false conditions and the default value of a boolean is
false.
byte: The byte data type is used instead of the int or other integer data types to save memory.
The byte data type must have a value between -128 and 127. The default value of a byte is 0.
char: This is a 16-bit Unicode character. The minimum value of the char data type is ‘\u0000’
which is 0 and the maximum value is ‘\uffff’ - "\u" indicates that this is a unicode character. The
next four places are used to give the hexadecimal number associated with a specific character.
The letter variable here contains the value of “Q”. This is because the unicode value of “Q” is
‘\u0051’. You can read more on unicode characters here. However, the char data type can also
store letters:
short: The short data type can hold a value that ranges from -32768 to 32767 (16-bit signed
two’s complement integer). This type is used instead of other integer data types, such as long or
int, to save memory. Thus, if you’re certain that the value of the integer is between -32768 to
32767, then this is the data type to use.
int: The int data type can have values from -2 147 483 648 to +2 147 483 647 (32-bit signed
two's complement integer).
long: The long data type can have values from -9 223 372 036 854 775 808 to +9 223 372 036
854 775 807 (64-bit signed two's complement integer).
Notice, the use of “L” at the end of the value -42332200000L. This is an integral literal of the long
data type. An integral literal is of type long if it ends with the letter “ L” or “l” (lowercase L),
otherwise it is of type int.
Note: it is recommended to use the uppercase L at the end of longs, because the lowercase l is
difficult to distinguish from the number 1 (one).
The float and the double data types are complements of each other.
Operators in Java are special symbols that are used to perform operations on operands
(variables and values). For example, + is an operator that is used for addition. You are already
familiar with one type of operator, the assignment operator (=), which we used to assign values
to variables.
As you can see from the sample code, we’ve subtracted price from payment and stored the
result in a new variable called change. If you were to print out change to the screen, you will see
5. The remaining arithmetic operators, such as, addition (+), multiplication (*), and division (/)
can be used in a similar fashion.
Create a new class called Operators. In the main method, declare and initialise two strings to
store “Airos” and “Education,” respectively. Concatenate these strings and print the result.
When a variable is created during the running of your program, the computer allocates memory
for it on your computer. However, since programs can be very large and have several variables,
Java limits the lifespan of your primitive variables to the scope in which it is defined. The
scope of a variable is limited to the curly brackets in which it resides { }. Let’s consider some
examples to further elaborate on this concept.
The code snippets below are all based on a simple code that has two methods, the main
method and a method that computes the sum of two integers.
Note: Methods are a collection of statements grouped together to perform some action.
Methods will be discussed further in a later lesson of this course.
class Scope {
//this is the main() method of the program
public static void main(String[] args) {
int num1 = 2;
int num2 = 3;
}
//this is a method - variables defined within the curly braces here are local variables
public static int sum(int number1, int number2 ){
return number1 + number2;
}
}
Looking at the example above, the variables num1 and num2 in the main method are local to
the main method - they fall within the curly brackets of the main method. In code, what this
means is that these variables are created (allocated memory) when the code reaches them and
they are destroyed (memory deallocated) when the code reaches the closing curly bracket - }.
class Scope {
static int num1 = 2;
static int num2 = 3;
In example 2, we’re using the same code, however, the two variables are defined within the
curly braces of the class - these are known as global variables. Since all the methods are within
the class the variables are accessible from every method (global). When running the program
the computer allocates memory for these variables when the class is created and only destroys
them when the class object is destroyed. This means these variables are available in memory
for a longer period of time as opposed to example 1, so the obvious lesson here is you do not
want to use global variables unless they are absolutely necessary. Global variables are used
when you want to maintain data (this is why we put the static term when defining the variable) -
an example will be covered in the formative assessment at the end of the lesson.
Example 3: Precedence
class Scope {
static int num1 = 2;
static int num2 = 3;
In example 3, we have the same source code except now we’ve defined the two variables in
both scopes i.e. local and global. In Java, if you have two variables with the same name within
the same scope, you’ll get an error, for example:
int num1 = 5;
int num1 = 7;
However, if the variables are in two separate scopes, then your program will compile and
execute perfectly. In example 3, when the program runs, it is the main method that calls the
function to calculate the sum. In Java, the local variable always takes precedence over the
class Scope {
static int num1 = 2;
static int num2 = 3;
Exercise 2
In example 4, we took the code from example 3 and altered the sum method to add num1 at the
end. With that in mind, please complete the following for this exercise:
1. Run this code to see what answer comes up and write-up a short explanation on why the
answer is what you got - making reference to the variable lifecycle, local and global
variables.
2. Next, research the static keyword and why it is used on global variables and submit that
as a brief write-up to your tutor.
Lesson Summary
❖ Java has eight primitive data types, which are variable types that come prepackaged
with the JDK.
❖ These data types can be summarised, as follows:
To progress to the next lesson, you are required to complete the following:
1. In your own words, explain the concept of a variable.
2. How many primitive data types are there in Java?
3. Is the String class a primitive data type?
4. Differentiate between local and global variables.
5. Create a new class called Variables. In the main method, declare and initialise two
variables to store your first name and age.
a. Use two println( ) statements to print your age and name.
b. Declare and initialize a variable that stores your surname.
c. Concatenate your first name and surname and store the result in a new variable
called fullName.