2. What Are Variables?
All computer programs work with different
kinds of data such as numbers, texts, dates and
pictures. Although this is typical, compute
programs need places where data can be
stored. These storage places are called
variables. They are called as such because the
data stored in them may vary as the program
runs.
3. Data Types
Data type refers to the kind of data a
variable can contain. It may either be a
number, letter or a list of characters.
Most common data types:
• int- used to represent whole, non-decimal
numbers. Examples are 1,100 and 1000
• double- used to repesent numbers with
decimal points, examples of which are 1.75,
0.975 and 19.78
4. Data Types
• char- enclosed in single quotation marks, it is
used to represent a single character;
examples are ‘a’, ‘m’ and ‘c’
• boolean- used to represent a boolean value,
which can be either true or false
A variable may also be classified as a
String, although a String is not a primitive
data type. A String is a class that stores a list
of characters. It is enclosed in double
quotation marks. Examples are “anna” and
“my pet”.
5. Rules In Naming Variables
Rules in naming variables (in Java):
• Variables can be composed of letters, numbers,
underscores and dollar signs.
• Variables may not start with a number. Below are
some examples of valid and invalid variables.
Valid Variables: Invalid Variables:
○ surname ○ my*name
○ _cost ○ my name
○ score1 ○ 12myName
• You cannot use a word reserved by Java. For
example, you cannot have a variable named if
or while.
6. Rules In Naming Variables
• The variable names also follow a norm called
camel notation. It is not a must to adhere to the
notation but it is a standard of doing things in
Java. You start a name with a small letter. If it has
two or more words, start all the other words with
capital letters. For example:
myName
firstName
7. Rules In Naming Variables
• If possible, use variable names that are
meaningful. You should be able to identify the
value stored in a variable by looking at its name.
For example:
myName -to contain my name
myScore -to contain my score
totalScore -to contain my total score
8. Declaring Variables
Once you have named a variable and
determines what type you want it to be, you must
relay this information to your Java program. So you
need to state in your program that a particular
variable exists. In other words, you need to declare
your variables.
We need a declaration for all variables that we
will use in our Java programs. Proper variable
declaration makes programming easier, minimizes the
possibility of program errors, and makes program
modifications easier later on.