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.
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 |
int | int |
long | lng |
float | flt |
double | dbl |
String | str |
boolean | bln |
char | chr |
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.
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.
Which of the following are valid variable identifiers? For the invalid ones, explain why they're invalid.
headings | headings12 | headings 12 | 12headings |
point.x | pointX | Xpoint | point^x |
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 = "";
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;
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
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;
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.
Examine the program and its output in the listing below and answer the following questions:
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. Find the errors in each of the following code listings:
public class Qu2PartA { public static void main(String[] args) { width = 15 area = length * width; System.out.println("The area is " + area); } }
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); } }
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:
Bill Amount: 35.1 Tip%: 15.0 Tip Amount: $5.265