CPPROG2 - Lesson 2 Using Data
CPPROG2 - Lesson 2 Using Data
Reference Materials:
• Java Variables:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
• Primitive Data Types
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
• Operators
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
• Assignment, Arithmetic, and Unary Operators
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
• Scanning
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
• Input and Output
https://www.youtube.com/watch?v=JceW6zvmA_Q
• Variables
https://www.youtube.com/watch?v=7wWvSn_qiBc
• Primitive Data Types
https://www.youtube.com/watch?v=qUXbJziVs_o
• Scanner Input
https://www.youtube.com/watch?v=rqZ0Cp9Omp8
• Numeric Expressions and Operators
https://www.youtube.com/watch?v=RA7wkTV6z4k
System.out.println(459);
Every time an application containing the constant 459 is executed, the value 459 is displayed.
Programmers refer to the number 459 as a literal constant because its value is taken literally at
each use. The number 459 is also a numeric constant as opposed to a character or string
constant. Additionally, it is an unnamed constant as opposed to a named one, because no
identifier is associated with it.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
On the other hand, you can set up a data item as a variable. A variable is a named memory
location that you can use to store a value. A variable can hold only one value at a time, but the
value it holds can change. For example, if you create a variable named ovenTemperature, It
might hold 0 when the application starts, later be altered to hold 350, and still later be altered
to hold 400.
Whether a data item is variable or constant, in Java it always has a data type. An item’s data type
describes the type of data that can be stored there, how much memory the item occupies, and
what types of operations can be performed on the data. Java provides for eight primitive types
of data. A primitive type is a simple data type. The eight types are described in Table2-1.
Keyword Description
byte Byte-length integer
short Short integer
int Integer
long Long integer
float Single-precision floating point
double Double-precision floating point
char A single character
boolean A Boolean value (true or false)
Table 2-1 Java Primitive data Types
The eight primitive data types are called “primitive” because they are simple and uncomplicated.
Primitive types also serve as the building blocks for more complex data types, called reference
types. The value of a reference type is a memory address.
Declaring Variables
A variable declaration is a statement that reserves a named memory location and includes the
following:
• A data type that identifies the type of data that the variable will store
• An identifier that is the variable’s name
• An optional assignment operator and assigned value, if you want a variable to contain an
initial value
• An ending semicolon
You name variables using the same naming rules as you do for legal class identifiers. Basically,
variable names must start with a letter and cannot be a reserved keyword. You must declare all
variables you want to use in a class, and you must declare them before you can use them. Java
is a strongly typed language, or one in which all variables must be declared before they can be
used.
For example, the following declaration creates a variable of type int named myAge and assigns
it an initial value of 25:
This declaration is a complete statement that ends in a semicolon. The equal sign ( = ) is the
assignment operator. Any value to the right of the equal sign is assigned to the variable on the
left of the equal sign. An assignment made when you declare a variable is an initialization; an
assignment made later is simply an assignment. Thus, the first statement that follows is an
initialization, and the second is an assignment:
myAge = 42;
You declare a variable just once, but you might assign new values to it any number of times.
Note that an expression with a literal to the left of the assignment operator (such as 25=myAge)
is illegal. The assignment operator has right-to-left associativity. Associativity refers to the order
in which values are used with operators. The associativity of every operator is either right-to-left
or left-to-right.
The following variable declaration also declares a variable of type int named myAge, but no value
is assigned at the time of creation:
int myAge;
If you attempt to display a variable that has not been assigned a value, or use it as part of a
calculation, you receive an error message stating that the variable might not have been
initialized. Java protects you from inadvertently using the unknown value (known as a garbage
value) that is stored in an uninitialized variable.
You can declare multiple variables of the same type in separate statements. You also can declare
two (or more) variables of the same type in a single statement by separating the variable
declarations with a comma, as shown in the following statement:
By convention, programmers declare most variables in separate statements. You might declare
multiple variables in the same statement only if they are closely related. Remember that even if
a statement occupies multiple lines, the statement is not complete until the semicolon is
reached.
You can declare as many variables in a statement as you want, as long as the variables are the
same data type. However, if you want to declare variables of different types, you must use a
separate statement for each type.
A variable is a named memory location for which the contents can change. If a named location’s
value should not change during the execution of a program, you can create it to be a named
constant. A named constant is also known as a symbolic constant. A named constant is similar
to a variable in that it has a data type, a name, and a value. A named constant differs from a
variable in several ways:
• In its declaration statement, the data type of a named constant is preceded by the keyword
final.
• A named constant can be assigned a value only once, and then it can never be changed.
Usually you initialize a named constant when you declare it; if you do not initialize the
constant at declaration, it is known as a blank final, and you can assign a value later. You can
assign a value to a final variable only once, and you must assign a value before the variable
is used.
• Although it is not a requirement, named constants conventionally are given identifiers using
all uppercase letters, using underscores as needed to separate words.
You can use each of these named constants anywhere you can use a variable of the same type,
except on the left side of an assignment statement. In other words, after they receive their initial
values, named constants are values.
A constant always has the same value within a program, so you might wonder why you cannot
use the actual, literal value. For example, why not code 20 when you need the number of
departments instead of going to the trouble of creating the NUMBER_OF_DEPTS named
constant? There are several good reasons to use the named constant rather than the literal one:
A data item’s scope is the area in which it is visible to a program and in which you can refer to it
using its simple identifier. A variable or constant is in scope from the point it is declared until the
end of the block of code in which the declaration lies. Frequently, this means a variable or
constant can be used from its declaration until the end of the method in which it is declared.
However, if a method contains multiple sets of curly braces, then a data item is usable only until
the end of the block that holds the declaration.
Each constant can hold only one value for the duration of its program; each variable can hold
just one value at a time. Suppose you have two variables, x and y, and x holds 2 and y holds 10.
Suppose further that you want to switch their values so that x holds10and y holds2. You cannot
simply make an assignment such as x=y because then both variables will hold 10, and the 2 will
be lost. Similarly, if you make the assignment y=x, then both variables will hold 2, and the 10 will
be lost. The solution is to declare and use a third variable, as in the following sequence of events:
int x = 2, y = 10, z;
z = x;
x = y; y = z;
OBJECT-ORIENTED PROGRAMMING JAVA Programming
In this example, the third variable, z, is used as a temporary holding spot for one of the original
values. The variable z is assigned the value of x, so z becomes 2. Then the value of y, 10, is
assigned to x. Finally, the 2 held in z is assigned to y. The extra variable is used because as soon
as you assign a value to a variable, any value that was previously in the memory location is gone.
The int data type is the most commonly used integer type. A variable of type int can hold any
whole number value from –2,147,483,648 to +2,147,483,647. When you assign a value to an int
variable, you do not type any commas or periods; you type only digits and an optional plus or
minus sign to indicate a positive or negative integer.
The types byte, short, and long are all variations of the integer type. The byte and short types
occupy less memory and can hold only smaller values; the long type occupies more memory and
can hold larger values. Table 2-2 shows the upper and lower value limits for each of these types.
It is important to choose appropriate types for the variables you will use in an application. If you
attempt to assign a value that is too large for the data type of the variable, the compiler issues
an error message and the application does not execute.
If an application uses a literal constant integer, such as 932, the number is an int by default. If
you need to use a constant higher than 2,147,483,647, you must follow the number with the
letter L to indicate long. For example, the following statement stores a number that is greater
than the maximum limit for the int type.
You can type either an uppercase or lowercase L after the digits to indicate the long type, but
the uppercase L is preferred to avoid confusion with the number 1. You need no special notation
to store a numeric constant in a byte or a short.
You also can assign values based on the result of comparisons to Boolean variables. Java supports
six relational operators that are used to make comparisons. A relational operator compares two
items; it is sometimes called a comparison operator. An expression that contains a relational
operator has a Boolean value. Table 2-3 describes the relational operators.
When you use any of the operators that have two symbols ( ==, <=, >=, or != ), you cannot place
any whitespace between the two symbols. You also cannot reverse the order of the symbols.
That is, =<, =>, and =! are all invalid operators.
Legal declaration statements might include the following statements, which compare two values
directly:
The Boolean expressions are more meaningful when variables (that have been assigned values)
are used in the comparisons, as in the following examples. In the first statement, the hours
variable is compared to a constant value of 40. If the hours variable is not greater than 40, the
expression evaluates to false. In the second statement, the income variable must be greater than
100000 for the expression to evaluate to true. In the third statement, two variables are
compared to determine the value of isFirstScoreHigher.
Just as an integer constant, such as 178, is a value of type int by default, a floating-point constant,
such as 18.23, is a double by default. To store a value explicitly as a float, you can type the letter
F after the number, as in the following:
You can type either a lowercase or an uppercase F. You also can type D (or d) after a floating
point constant to indicate it is a double, but even without the D, the value will be stored as a
double by default.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
If you display each of these values using a println() statement, you see a 9. However, only
the numeric value, aNumValue, can be used to represent the value 9 in arithmetic statements.
A numeric constant can be stored in a character variable and a character that represents a
number can be stored in a numeric variable. For example, the following two statements are legal,
but unless you understand their meanings, they might produce undesirable results:
char aCharValue = 9;
int aNumValue = '9';
If these variables are used in the following println() statement, then the resulting output
produces a blank for aCharValue and the number 57 for aNumValue:
23 etb^W 55 7 87 W 119 w
24 can^X 56 8 88 X 120 x
25 em^Y 57 9 89 Y 121 y
26 sub^Z 58 : 90 Z 122 z
27 esc 59 ; 91 [ 123 {
28 fs 60 < 92 \ 124 |
29 gs 61 = 93 ] 125 }
30 rs 62 > 94 ^ 126 ~
31 us 63 ? 95 _ 127 del
Table 2-5 Unicode values 0 through 127 and their character equivalents
The unexpected values are Unicode values. Every computer stores every character it uses as a
number; every character is assigned a unique numeric code using Unicode. Table 2-5 shows some
Unicode decimal values and their character equivalents. For example, the character ‘A’ is stored
using the value 65 and the character ‘B’ is stored using the value 66. Appendix B contains more
information on Unicode.
A variable of type char can hold only one character. To store a string of characters, such as a
person’s name, you must use a data structure called a String. In Java, String is a built-in class that
provides you with the means for storing and manipulating character strings. Unlike single
characters, which use single quotation marks, string constants are written between double
quotation marks. For example, the expression that stores the name Audrey as a string in a
variable named firstName is:
You can store any character—including non-printing characters such as a backspace or a tab—
in a char variable. To store these characters, you can use an escape sequence, which always
begins with a backslash followed by a character—the pair represents a single character. For
example, the following code stores a newline character and a tab character in the char variables
aNewLine and aTabChar:
In the declarations of aNewLine and aTabChar, the backslash and character pair acts as a
single character; the escape sequence serves to give a new meaning to the character. That is, the
literal characters in the preceding code have different values from the “plain” characters ‘n’ or
‘t’. Table2-6 describes some common escape sequences that you can use with command window
output in Java.
When you want to produce console output on multiple lines in the command window, you have
two options: You can use the newline escape sequence, or you can use the println() method
multiple times. For example, Figures 2-1 and 2-2 both show classes that produce the same
output: “Hello” on one line and “there” on another. The version you choose to use is up to you.
The example in Figure 2-1 is more efficient—from a typist’s point of view because the text
OBJECT-ORIENTED PROGRAMMING JAVA Programming
System.out.println appears only once, and from the compiler’s point of view because the
println() method is called only once.
The program in Figure 2-3 uses the command line to display values, but you also can use a dialog
box. Recall from Lesson 1 that you can use the showMessageDialog() method with two
arguments: null, which indicates the box should appear in the center of the screen, and the
String to be displayed in the box. Figure 2-5 shows a NumbersDialog class that uses the
OBJECT-ORIENTED PROGRAMMING JAVA Programming
import javax.swing.JOptionPane;
public class NumbersDialog {
public static void main(String[] args) {
int creditDays = 30;
JOptionPane.showMessageDialog(null, "" + creditDays );
JOptionPane.showMessageDialog
(null, "Every bill is due in " + creditDays + " days");
}
}
Figure 2-5 NumbersDialog class
Performing Arithmetic
Table 2-7 describes the five standard arithmetic operators. You use arithmetic operators to
perform calculations with values in your programs. A value used on either side of an operator is
an operand. For example, in the expression 45 + 2, the numbers 45 and 2 are operands. The
arithmetic operators are examples of binary operators, so named because they require two
operands.
• Floating-point division occurs when either or both of the operands are floating-point values.
For example, 45.0 / 2 is 22.5.
• Integer division occurs when both of the operands are integers. The result is an integer, and
any fractional part of the result is lost. For example, the result of 45 / 2 is 22. As another
example, 39 / 5 is 7 because 5 goes into 39 seven whole times; 38 / 5, 37 / 5, 36 / 5, and 35
/ 5 all evaluate to 7.
The percent sign is the remainder operator. The remainder operator is most often used with two
integers, and the result is an integer with the value of the remainder after division takes place.
For example, the result of 45 % 2 is 1 because 2 goes into 45 twenty-two times with a remainder
of 1. Other examples of remainder operations include the following:
When you combine mathematical operations in a single statement, you must understand both
associativity and precedence. The associativity of arithmetic operators with the same
precedence is left to right. In a statement such as answer = x + y + z;, the x and y are added
first, producing a temporary result, and then z is added to the temporary sum. After the sum is
computed, the result is assigned to answer.
Operator precedence refers to the rules for the order in which parts of a mathematical
expression are evaluated. The multiplication, division, and remainder operators have the same
precedence. Their precedence is higher than that for the addition and subtraction operators.
Addition and subtraction have the same precedence. In other words, multiplication, division, and
remainder always take place from left to right prior to addition or subtraction in an expression.
For example, the following statement assigns 14 to result:
int result = 2 + 3 * 4;
The multiplication operation (3 * 4) occurs before adding 2. You can override normal operator
precedence by putting the operation to perform first in parentheses. The following statement
assigns 20 to result:
int result = (2 + 3) * 4;
The addition within the parentheses takes place first, and then the intermediate result (5) is
multiplied by 4. When multiple pairs of parentheses are used in a statement, the innermost
expression surrounded by parentheses is evaluated first. For example, the value of the following
expression is 46:
2 * (3 + (4 * 5))
First, 4 * 5 evaluates to 20, and then 3 is added, giving 23. Finally, the value is multiplied by 2,
giving 46.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
Remembering that *, /, and % have the same precedence is important in arithmetic calculations.
These operations are performed from left to right, regardless of the order in which they appear.
For example, the value of the following expression is 9:
25 / 8 * 3
First, 25 is divided by 8. The result is 3 because with integer division, you lose any remainder.
Then 3 is multiplied by 3, giving 9. If you assumed that * was performed before /, you would
calculate an incorrect answer.
You can make your programs operate more efficiently if you avoid unnecessary repetition of
arithmetic statements. For example, suppose you know the values for an employee’s hourly pay
and pay rate and you want to compute state and federal withholding tax based on known rates.
You could write two statements as follows:
With this approach, you perform the multiplication of hours * rate twice. It is more efficient to
perform the calculation once, as follows:
The time saved is very small, but these savings would be more important if the calculation was
more complicated or if it was repeated many times in a program. As you think about the
programs you write, remain on the lookout for ways to improve efficiency by avoiding
duplication of operations.
Integer values are exact, but floating-point numbers frequently are only approximations. For
example, when you divide 1.0 by 3.0, the mathematical result is 0.3333333..., with the 3s
continuing infinitely. No matter how many decimal places you can store, the result is only an
approximation. Even values that don’t repeat indefinitely in our usual numbering system, such
as 0.1, cannot be represented precisely in the binary format used by computers. Imprecision
leads to several problems:
• When you produce floating-point output, it might not look like what you expect or want.
• When you make comparisons with floating-point numbers, the comparisons might not be
what you expect or want.
For example, Figure 2-8 shows a class in which an answer is computed as 2.20 – 2.00.
Mathematically, the result should be 0.20. But, as the output in Figure 2-9 shows, the result is
calculated as a value that is slightly more than 0.20, and when answer is compared to 0.20, the
result is false.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
For now, you might choose to accept the slight imprecisions generated when you use floating-
point numbers. However, if you want to eliminate the imprecisions, you can use one of several
techniques to round values.
When you perform arithmetic operations with operands of unlike types, Java chooses a unifying
type for the result. The unifying type is the type to which all operands in an expression are
converted so that they are compatible with each other. Java performs an implicit conversion;
that is, it automatically converts nonconforming operands to the unifying type. Implicit
conversions also are called promotions.
The following list shows the order for establishing unifying types between values:
1. double
2. float
3. long
4. int
When two unlike types are used in an expression, the unifying type is the one with the lower
number in this list. In other words, the operand that is a type with a higher number in this list is
converted to the type of the one that has a lower number. For example, the addition of a double
and an int results in a double, and the subtraction of a long from a float results in a float.
For example, assume that an int, hoursWorked, and a double, payRate, are defined and
then multiplied as follows:
The result of the multiplication is a double because when a double and an int are multiplied, the
int is promoted to the higher-ranking unifying type double—the type with the lower number in
the preceding list. Therefore, assigning the result to grossPay is legal. The following code will
not compile because Java does not allow the loss of precision that occurs if you try to store the
calculated double result in an int.
You can explicitly (or purposely) override the unifying type imposed by Java by performing a type
cast. Type casting forces a value of one data type to be used as a value of another type. To
perform a type cast, you use a cast operator, which is created by placing the desired result type
in parentheses. Using a cast operator is an explicit conversion. The cast operator is followed by
the variable or constant to be cast. For example, a type cast is performed in the following code:
In this example, the double value bankBalance is divided by the integer 4, and the result is a
double. Then the double result is converted to a float before it is stored in weeklyBudget.
Without the conversion, the statement that assigns the result to weeklyBudget would not
compile. Similarly, a cast from a float to an int occurs in this code segment:
In this example, the float value myMoney is converted to an int before it is stored in the
integer variable named dollars. When the float value is converted to an int, the decimal
place values are lost. The cast operator does not permanently alter any variable’s data type; the
alteration is only for the duration of the current operation.
You do not need to perform a cast when assigning a value to a higher unifying type. For example,
when you write a statement such as the following, Java automatically promotes the integer
constant 10 to be a double so that it can be stored in the payRate variable:
However, for clarity, if you want to assign 10 to payRate, you might prefer to write the
following:
The result is identical to the result when you assign the literal integer 10 to the double variable.
You can use the print() and println() methods to display many data types; for example,
you can use them to display a double, int, or String. The System.in object is not as flexible;
it is designed to read only bytes. That’s a problem, because you often want to accept data of
OBJECT-ORIENTED PROGRAMMING JAVA Programming
other types. Fortunately, the designers of Java have created a class named Scanner that makes
System.in more flexible. To create a Scanner object and connect it to the System.in object,
you write a statement similar to the following:
The portion of the statement to the left of the assignment operator, Scanner inputDevice,
declares an object of type Scanner with the programmer-chosen name inputDevice, in
exactly the same way that int x; declares an integer with the programmer-chosen name x.
The portion of the statement to the right of the assignment operator, new Scanner
(System.in), creates a Scanner object that is connected to the System.in property. In
other words, the created Scanner object is connected to the default input device. The keyword
new is required by Java; you will use it whenever you create objects that are more complex than
the simple data types.
The assignment operator in the Scanner declaration statement assigns the value of the new
object—that is, its memory address—to the inputDevice object in the program.
A Scanner object breaks its input into units called tokens, separating them when it encounters
whitespace. The resulting tokens can then be converted into values of different types using the
various class methods. Table 2-8 summarizes some of the most useful methods that read
different data types from the default input device. Each retrieves a value from the keyboard and
returns it as the appropriate data type. The appropriate method executes, retrieving data when
a user presses an appropriate whitespace key at the keyboard. The nextLine() method does
not retrieve data until the user presses Enter; the other methods retrieve data when the user
presses Enter, the spacebar, or the tab key.
Method Description
nextDouble() Retrieves input as a double
nextInt() Retrieves input as an int
nextLine() Retrieves the next line of data and returns it as a String
next() Retrieves the next complete token as a String
Table 2-8 Selected Scanner class methods
Figure 2-10 contains a program that uses two of the Scanner class methods. The program reads
a string and an integer from the keyboard and displays them. The Scanner class is used in the
four shaded statements in the figure.
• The first shaded statement is import java.util.Scanner;. This statement imports the
package necessary to use the Scanner class.
• The second shaded statement declares a Scanner object named inputDevice.
• The third shaded statement uses the nextLine() method to retrieve a line of text from
the keyboard and store it in the name variable.
• The last shaded statement uses the nextInt() method to retrieve an integer from the
keyboard and store it in the age variable.
The print() statements that appear before each input statement in the program in Figure 2-
10 are examples of prompts. A prompt is a message displayed for the user that requests and
describes input. Interactive programs would work without prompts, but they would not be as
user-friendly. Each prompt in the GetUserInfo class ends with two greater-than signs and a
space. This punctuation is not required; it just separates the words in the prompt from the user’s
input value on the screen, improving readability.
Pitfall: Using nextLine() Following One of the Other Scanner Input Methods
You can encounter a problem when you use one of the numeric Scanner class retrieval methods
or the next() method before you use the nextLine() method. Consider the program in Figure
2-12. It is identical to the one in Figure 2-10, except that the user is asked for an age before being
asked for a name. (See shading.) Figure 2-13 shows a typical execution.
OBJECT-ORIENTED PROGRAMMING JAVA Programming
In Figure 2-13, the user is prompted correctly for an age. However, after the user enters an age
and the prompt for the name is displayed, the program does not pause to let the user enter a
name. Instead, the program proceeds directly to the output statement, which does not contain
a valid name, as you can see in Figure 2-13.
When you type characters using the keyboard, they are stored temporarily in a location in
memory called the keyboard buffer. The keyboard buffer sometimes is called the type-ahead
buffer. All keystrokes are stored in the keyboard buffer, including the Enter key. The problem
occurs because of a difference in the way the nextLine() method and the other Scanner
retrieval methods work:
• The Scanner methods next(), nextInt(), and nextDouble() retrieve the next token
in the buffer up to the next whitespace, which might be a space, tab, or Enter key.
• The nextLine() method reads all data up to the Enter key character.
So, in the execution of the program in Figure 2-13, the user is prompted for an age, types 22, and
presses Enter. The call to the nextInt() method retrieves the 22 and leaves the Enter key press
in the input buffer. Then the name prompt is displayed and the call to nextLine() retrieves
the waiting Enter key before the user can type a name.
The solution to the problem is simple. After any next(), nextInt(), or nextDouble() call,
you can add an extra nextLine() method call that will retrieve the abandoned Enter key
character. Then, no matter what type of input follows, the program will execute smoothly. Figure
2-14 shows a program that contains just one change from Figure 2-12—the addition of the
shaded statement that retrieves the abandoned Enter key character from the input buffer.
Although you could assign the Enter key to a character variable, there is no need to do so. When
you accept an entry and discard it without using it, programmers say that the entry is consumed.
Figure 2-14 shows that the call to nextInt() accepts the integer, the first call to nextLine()
accepts the Enter key that follows the integer entry, and the second nextLine() call accepts
both the entered name and the Enter key that follows it. Figure 2-15 shows that the revised
program executes correctly.
OBJECT-ORIENTED PROGRAMMING JAVA Programming