In this lesson we'll learn about variables in Java:
what are they, how to create them, and how and why we use them.
Variables are a very important part of every programming
language. Variables allow
you to store pieces of data that you can use throughout
your application. Variables are used in many
expressions
and statements.
Pre-Requisites
Before doing this tutorial, make sure you've gone through the
tutorial Data Types.
What are Variables?
A variable is a storage location in
the computer's memory or
RAM - you assign a name
to your variable so that you can access that memory location whenever
you want in your program code.
RAM is temporary storage:
it's only available to your application while the application
is running. That's fine, though because we often need to store
things temporarily while the program runs. When you want to store
things more permanently, you would use a file, database, or
other storage mechanism, which is beyond the
scope of this tutorial.
One problem with working with storage locations in memory
is that the memory addresses aren't easy to remember.
They're not symbolic at all and consist of address such
as "13A4:0170". In addition, because programs and files
are always being loaded in and out of memory, different
areas of memory become available each time you run a
program. You might run a program now and store a value
in address 13A4:0170, but if you run the same program an
hour from now, that address may no longer be available.
To overcome these problems, we define variables in our
program to refer to storage locations with symbolic names
that are easier to remember. Imagine you live in residence
this term and are given a mailbox where you can pick up
your mail. You know which box is yours because it probably
has your room number on it, or your name. When you come
back after summer vacation, you most likely get a different
room. Will you have trouble finding your mailbox?
Probably not, as it will have your new room number or
your name on it. Memory can work the same way. We can
tell the program to go grab a location in memory, and we
can give it a name to stick on that location so that it's
easy to refer back to it later.
Declaring and Initializing Variables
When you want to use a variable in your code, you have to
declare or define it using a variable declaration
statement. The syntax varies from language to
language, but here's how you do it in Java:
dataType variableIdentifier;
dataType refers to the type of data this variable
will hold.
This must be one of Java's 8 primitive types (byte, short,
int, long, float, double, boolean, or char) or a valid
class/reference type (e.g. String).
Some languages, like Python or JavaScript, don't require that
you specify a data type, but in Java, this is mandatory!
variableIdentifier refers to the identifier you
create for the variable.
We use the term "identifier" in programming for any made-up
name. You will make up lots of identifiers for variables,
methods, classes, and other things. Each thing has its own set
of rules and standards for identifiers.
In Java, all variable identifiers must have the correct syntax:
The identifier may not start with a digit.
The identifier may not contain a space.
The identifier may not be any of
Java's
reserved keywords,
nor can it be named true, false,
or null because these are all values in Java.
Except for the previous rules mentioned above, a variable
identifier can contain any other letters and digits, and
is also allowed to include the _ (underscore) character, and the
$ (dollar sign) character, and the identifier can be of any
length (number of characters).
Industry
standards for Java also state that a variable identifier
should have the following characteristics:
It must start with a lower-case letter.
It must be self-documenting,
meaning that another developer should be able to accurately
guess the purpose or contents of the variable.
If the variable identifer contains more than one word, we
use camel casing on the second
and subsequent words. For example, a variable that stores a
customer first name might be called custFirstName,
with the first letter in lower-case and the first letters of
"First" and "Name" in upper-case.
Avoid ambiguous abbreviations in an identifier. For example,
what would a variable called stat be for? Does it
contain a status? Is it state? Statistic? When using abbreviations,
make sure they are obvious. For example, custFirstName
works in an application that manages customer data, and
empDepartment makes sense in an application that manages
employees.
Somehow, you have to follow all these rules and not make your
variable identifier too long. It's difficult sometimes, but
try your best. It's very annoying to have to keep typing
customerEndOfYearBalance in thousands of lines of
code than it is to type custYearBalance or
custYearEndBal.
Examples
Here are some examples of variables that you might use in a program:
A variable that contains an employee's annual salary:
float empSalary;
// or you could also use
double empSalary;
In a later lesson, we'll discuss why you might choose float
over double and vice versa.
A variable that holds the number of records in a file:
int numRecords;
"num" is a common prefix/abbreviation for "number" or
"number of".
A variable that holds a song title:
String songTitle;
// or you could also use
String songName;
You can even declare multiple variables in a single statement as long
as they all have the same data type:
int n1, n2, n3;
However, this makes it harder to read and document variables
so we don't do it often.
Where Do We Declare Variables?
In Java, there are a few places where you can declare
variables. To start with, we'll declare our variables
inside the main() method. Any time you declare a variable
inside any method, that creates a local
variable. When you declare variables outside of a
method, that increases the level of scope
of the variable. Variable scope
refers to the accessibility or visibility of a variable.
For example, local variables are only available inside the
code block in which they are declared.
We will discuss more about variable scope and how you can
declare variables with larger scope as we go through
the course.
public class TestVariables {
public static void main(String[] args) {
double empSalary;
int numRecords
String songName;
}
}
Exercises
Which of the following are syntactically valid variable
identifiers? For the invalid ones, explain why
they're invalid.
headings
headings12
headings 12
12headings
point.x
pointX
Xpoint
point^x
headings - valid
headings12 - valid
headings 12 - invalid: contains a space
12headings - invalid: starts with a digit
point.x - invalid: contains a period/decimal (note
that if you've done object oriented programming before,
this might be valid if you had an object called
"point" and it contained a property called "x" but
for a regular variable as we've described in this lesson,
point.x is invalid)
pointX - valid
Xpoint - valid (although note that industry standards
state it should not start with an upper-case X, but
syntactically the variable is fine)
point^x - invalid: contains the ^ (caret) character
For each of the following statements below,
declare a variable. Use the most appropriate
data types and identifier names.
to store a customer's last name
to record the number of customers
to record the cost of a product
to store an employee's phone number
to record a single keystroke made by the user
Note that these have several correct answers.
If you aren't sure about your own answer, ask your professor.
String custLastName;
int numCustomers;
double productCost; or float productCost;
String empPhone; (or in some cases long empPhone; you'd have to
use long if you store as digits because many phone
numbers would be too large a value for the int type
- but this issue is why most developers will use String)
char keyInput;
Using Variables
Variables need to be assigned a value. This is often done at the same
time a variable is declared, but not always. When you give the variable
a value for the very first time, that's called
variable initialization.
Here are some examples of declaring and initializing variables
at the same time:
You can even declare and initialize multiple variables in a
single statement as long as they all have the same data type:
int n1 = 2, n2 = 4, n3 = 5;
This does make the code harder to read and document, so
we don't do this often.
You can initialize a variable with its first value
after you declare it:
String custFirstName;
... other code here ...
custFirstName = "Fred";
However, note that you can't "use" a variable until it has first
been initialized, either when you declare it or some time after:
public class UseVariables {
public static void main(String[] args) {
int num;
// this won't work:
System.out.println(num);
}
}
This program will give you a compile error: "The local variable num may
not have been initialized." This is why many programmers prefer to
initialize a variable to a default value. If you don't have a default
value that makes sense, you can usually use the type's null value.
In this case, the null value for an integer is 0, but feel free to use
any positive or negative whole number you like:
public class UseVariables {
public static void main(String[] args) {
int num = 0;
// this won't work:
System.out.println(num);
}
}
Note also that you can't use a variable if it has never
been declared or defined:
public class UseVariables {
public static void main(String[] args) {
// this won't work:
System.out.println(num);
}
}
This program won't work because the variable num
was never declared. Most editors will give you a "cannot resolve symbol" or
"variable not defined" type of error.
Note that we use the = (equals) sign to assign a value or result
to a variable. This is typical in programming so you'll see this a lot.
Specifically, this is called an assignment statement.
We'll learn more about assignment statements in the
next lesson, but this should be enough to allow you to start
creating and working with variables.
Example
Examine the following code segment and the diagram below:
This diagram illustrates the results of the three assignment statements
above the diagram. Each variable is a location in memory, and each memory
location or variable is given a value to store. The first two statements
store literal values or hard-coded values into the variables
dblSales and dblCommRate. The third statement calculates the value of
dblSales multiplied by dblCommRate, and stores the result in the variable
dblCommission.
Exercise
How many variables are used in the program below?
What is the name and type of each variable?
public class GradeCalculator {
public static void main(String[] args) {
int assignGrade = 40;
double assignMax = 32.5;
double assignWeight = assignGrade / assignMax * 100;
System.out.println("Assignment grade: " + assignWeight + "%");
}
}
There are three variables being used in this program:
assignGrade, which is an int (integer)
assignMax, which is a double
assignWeight, which is also a double
Why do you think I used double instead of float
for the assignMax variable? Try it and see what happens. We will discuss
this in an upcoming lesson.