Variables & Assignment Statements

Things To Do First

Things To Do Later

Variables

First, Read Chapters 2.4 and 2.5

Variables are an important part of programming. Variables are storage locations in the computer's memory; as programmers, we can put data into those storage locations and save them there for later use in the program. This storage, the computer's RAM (Random Access Memory) is only temporary - it's only available while the program is running. This makes it useful when we want to temporarily store things for use in our programs.

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.

In programming, we would call this a variable declaration, and it takes the general form:

dataType varName;

dataType defines the type of data that this variable will hold. This is necessary, particularly in Java. We learned earlier that data types are of varying sizes, so identifying the data type for a variable tells the computer how many bytes of memory to use.

varName is the symbolic name we decide to use for our variable. Variable names are a kind of identifier, and therefore follow the same rules discussed in chapter 2.3. The name should be self-documenting, meaning that another programmer can accurately guess what the variable is for just by reading its name.

Examples:

String strFirstName;
double dblSalary;
int intNumRecords;

In the first statement, we are creating a variable called strFirstName that will hold a string value (remember that technically, this means a string object!). The second statement is a variable called dblSalary that holds a double value, and the third is a variable called intNumRecords that holds an integer value (we use the keyword "int" when declaring an integer in Java).

Note that you can guess pretty well what each of these variables will end up storing, just by looking at the names. In addition, it's common to use a 3-letter lower-case prefix in front of the variable name to identify the type of data it contains. This is useful in large programs when you're reading code that is a few pages away from the data declarations section!

Common Data Type Prefixes
Data Type Prefix
intint
longlng
floatflt
doubledbl
Stringstr
booleanbln
charchr

In addition to specifying the data type and the variable name, a declaration statement should also include a modifier. So far we've used modifiers such as "public" and "private". We'll talk more about modifiers later in the course.

Rules for Variable Identifiers

In a previous session we talked about the rules for class identifiers. Variable identifiers also have a set of rules. You can find them in at the start of section 2.4. Be sure you are familiar with these rules as you will be expected to know them for your programs and on your quizzes and exams.

Exercises

Which of the following are valid variable identifiers? For the invalid ones, explain why they're invalid.

headingsheadings12headings 1212headings
point.xpointXXpointpoint^x

[solutions]

Variable Initialization

Sometimes when we declare a variable, we must give it a value. This is true of variables that we create inside a main() method or other method. These are called "local variables" and must be initialized with a value before we can use them. Usually we would just use a null value such as 0 (for numbers), "" (the null string, which is used for strings) or '\0' (for the char type). Otherwise, you can always use whatever initial value you require for your program. To initialize a variable in its declaration statement, we could do the following:

String strFirstName = "Kaluha";
double dblSalary = 0.0;
int intNumRecords = 0;
String strSearchKey = "";
Important!
Note that we prefer to use 0.0 as the floating-point literal value for 0. Why do we use 0.0 and not 0? Because 0 is considered an integer, and 0.0 is considered a floating-point. When you assign 0 to a floating-point variable (such as float or double), the computer has to do the extra work of converting the 0 into 0.0. You can make your program run more efficiently if you eliminate this extra step by using 0.0 as a floating-point literal value for 0.

Lastly, you can declare and/or initialize multiple variables of the same type in one statement. Each of the following is valid:

String strFirstName, strLastName;
int intXVal=0, intYVal=0, intZVal=0;
char chrInitial = 'S', chrKey;
Note
We often don't declare and/or initialize variables on the same line because they're harder to read, and harder to document.

Exercises

For each of the following statements below, declare a variable and initialize it to a null value. Use the most appropriate data types and identifier names.
a. to store a customer's last name
b. to record the number of customers
c. to record the customer's outstanding balance
d. to store the customer's phone number
bonus: to record a single keystroke made by the user

[solutions]

Assignment Statements

Chapter 2.6 talks about expressions and assignment statements. An expression is a statement that involves a calculation using literals, variables, and operators; an expression can be evaluated into a result. An assignment statement (or assignment expression) assigns a value/result to a variable. For example, each of these are assignment statements:

strFirstName = "Fred";
dblArea = 15.5 * 10.0;

When looking at an assignment statement, the equals sign (=) is the assignment operator, and it's job is to place the result of the expression on the right into the variable on the left. It's important to note that the direction of assignment goes from right to left, not left to right. If it helps, read the assignment operator as "gets" or "gets the value/result of". For example:

strFirstName = "Fred"; reads "the variable strFirstName gets the value Fred"
dblArea = 15.5 * 10.0; reads "the variable dblArea gets the result of the expression 15.5 * 10.0"

Examine the following code segment and the diagram below:

double dblSales = 2050.27;
double dblCommRate = .07;
double dblCommission = dblSales * dblCommRate;
All three variables in memory.

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.

Examine code listing 2.1 in textbook chapter 2.2. Lines 3 and 4 declare two variables: radius and area. Line 7 assigns the value 20 to the radius variable. Line 10 calculates the radius as radius * radius * 3.14159 and assigns the result of that calculation to the variable area.

Notice the chart below the code on page 36. It show the values of the variables at various stages in the program.

Exercise

Examine the program and its output in the listing below and answer the following questions:

  1. How many variables are used in this program?
  2. What are the names of the variables?
  3. Draw a diagram similar to the one above that shows the values in each of the variables.
public class  GradeCalculator
{
	public static void main(String[] args) 
	{
		int intAssignMark = 40;
		double dblActualMark = 32.5;
		int intBonus = 2;

		double dblPercent = (dblActualMark + intBonus) / 
			intAssignMark * 100;
		
		System.out.println("Assignment mark: " + dblActualMark + 
			"/" + intAssignMark + " (+" + intBonus + " bonus)");
		System.out.println("(" + dblPercent + "%)");
	}
}

The program's output:

Assignment mark: 32.5/40 (+2 bonus) (86.25%)

Solution:

  1. There are 4 variables used in this program.
  2. The 4 variables' names are: intAssignMark, dblActualMark, intBonus, and dblPercent.
  3. Your prof will do this during clas.

Exercises

1. Find the errors in each of the following code listings:

  1. Listing a)
    public class Qu2PartA
    {
        public static void main(String[] args)
        {
            width = 15
            area = length * width;
            System.out.println("The area is " + area);
        }
    }
  2. Listing b)
    public class Qu2PartB
    {
        public static void main(String[] args)
        {
            int length, width, area;
            area = length * width;
            length = 20;
            width = 15;
            System.out.println("The area is " + area);
        }
    }
  3. Listing c)
    public class Qu2PartC
    {
        public static void main(String[] args)
        {
            int length = 20, width = 15, area;
            length * width = area;
            System.out.println("The area is " + area);
        }
    }

2. Write a program that calculates the amount of money to tip a wait person by coding the following tasks:

  1. Define a variable for the bill amount and initialize it to 35.10.
  2. Define a variable for the tip percentage and initialize it to 15.
  3. Define a variable for the tip amount.
  4. Calculate the tip as the bill amount multiplied by the tip percentage (remember that 15% = 0.15) and assign and store the result in the tip amount variable.
  5. Display the output on the screen as shown below:
Bill Amount: 35.1    Tip%: 15.0
Tip Amount: $5.265

[solutions]