0% found this document useful (0 votes)
12 views

CPPROG2 - Lesson 2 Using Data

JAVA Data

Uploaded by

person.111420
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

CPPROG2 - Lesson 2 Using Data

JAVA Data

Uploaded by

person.111420
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

OBJECT-ORIENTED PROGRAMMING JAVA Programming

LESSON 2 USING DATA

In this lesson, you will:

 Use constant and variables


 Use integer data types
 Use the boolean data type
 Use floating-point data types
 Use the char data type
 Display data and perform arithmetic
 Understand numeric type conversion
 Use the Scanner class to accept keyboard input
 Use the JOptionPane class for GUI input

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

USING CONSTANTS AND VARIABLES


You can categorize data items as constant or variable. A data item is constant when its value
cannot be changed while a program is running; a data item is variable when its value might
change. For example, when you include the following statement in a Java class, the number 459
is a constant:

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:

int myAge = 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:

int myAge = 25;


OBJECT-ORIENTED PROGRAMMING JAVA Programming

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:

int myAge = 25, yourAge = 19;

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.

Declaring Names Constants

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.

For example, each of the following defines a named constant:

final int NUMBER_OF_DEPTS = 20;


OBJECT-ORIENTED PROGRAMMING JAVA Programming

final double PI = 3.14159;


final double TAX_RATE = 0.015;
final string COMPANY = "ABC Manufacturing";

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:

• The number 20 is more easily recognized as the number of departments if it is associated


with an identifier. Using named constants makes your programs easier to read and
understand.
• If the number of departments in your organization changes, you would change the value of
NUMBER_OF_DEPTS at one location within your program—where the constant is defined—
rather than searching for every use of 20 to change it to a different number. Being able to
make the change at one location saves you time, and prevents you from missing a reference
to the number of departments.
• Even if you are willing to search for every instance of 20 in a program to change it to the new
department number value, you might inadvertently change the value of one instance of 20
that is being used for something else, such as a payroll deduction value.
• Using named constants reduces typographical errors. For example, if you must include 20 at
several places within a program, you might inadvertently type 10 for one of the instances.
• When you use a named constant in an expression, it stands out as separate from a variable.
For example, in the following arithmetic statement, it is easy to see which elements are
variable and which are constant because the constants have been named conventionally:

double payAmount = hoursWorked * STD_PAY_RATE – numDependents * DEDUCTION;

The Scope of Variables and Constants

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.

Pitfall: Forgetting That a Variable Holds One Value at a Time

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.

LEARNING ABOUT INTEGER DATA TYPES


In Java, you can use variables of types byte, short, int, and long to store (or hold) integers; an
integer is a whole number without decimal places.

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.

Type Minimum Value Maximum Value Size in Bytes


byte -128 127 1
short -32,768 32,767 2
int -2,147,483,648 2,147,483,647 4
long -9,223,372,036,854,775,808 9,223,372,036,854,775,804 8
Table 2-2 Limits on integer values by type

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.

long mosquitosInTheNorthWoods = 2444555888L;

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.

USING THE BOOLEAN DATA TYPE


Boolean logic is based on true-or-false comparisons. Whereas an int variable can hold millions of
different values (at different times), a boolean variable can hold only one of two values—true or
false. The following statements declare and assign appropriate values to Boolean variables:

boolean isItPayday = false;


boolean areYouBroke = true;

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.

Operator Description True Example False Example


OBJECT-ORIENTED PROGRAMMING JAVA Programming

< Less than 3<8 8<3


> Greater than 4>2 2>4
== Equal to 7 == 7 3 == 9
<= Less than or equal to 5 <= 5 8 <=6
>= Greater than or equal to 7 >= 3 1 >= 2
!= Not equal to 5 != 6 3 != 3
Table 2-3 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:

boolean isSixBigger = (6 > 5);


// Value stored would be true
boolean isSevenSmallerOrEqual = (7 <= 4);
// Value stored would be false

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.

boolean isOvertimePay = (hours > 40);


boolean isTaxBracketHigh = (income > 100000);
boolean isFirstScoreHigher = (score1 > score2);

LEARNING ABOUT FLOATING-POINT DATA TYPES


A floating-point number contains decimal positions. Java supports two floating-point data types:
float and double. A float data type can hold floating-point values of up to six or seven significant
digits of accuracy. A double data type requires more memory than a float, and can hold 14 or 15
significant digits of accuracy. The term significant digits refers to the mathematical accuracy of
a value. For example, a float given the value 0.324616777 displays as 0.324617 because the value
is accurate only to the sixth decimal position. Table 2-4 shows the minimum and maximum values
for each floating-point data type.

Type Minimum Value Maximum Value Size in Bytes


float -3.4 * 1038 3.4 * 1038 4
double -1.7 * 10308 1.7 * 10308 8
Table 2-4 Limits on floating-point values

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:

float pocketChange = 4.87F;

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

WORKING WITH THE char DATA TYPE


You use the char data type to hold any single character. You place constant character values
within single quotation marks because the computer stores characters and integers differently.
For example, the following are typical character declarations:

char middleInitial = 'M';


char gradeInChemistry = 'A';
char aStar = '*';

A character can be any letter—uppercase or lowercase. It might also be a punctuation mark or


digit. A character that is a digit is represented in computer memory differently than a numeric
value represented by the same digit. For example, the following two statements are legal:

char aCharValue = '9';


int aNumValue = 9;

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:

System.out.println("aCharValue is " + aCharValue + "aNumValue is " + aNumValue);

Dec Char Dec Char Dec Char Dec Char


0 nul 32 64 @ 96 `
1 soh^A 33 ! 65 A 97 a
2 stx^B 34 “ 66 B 98 b
3 etx^C 35 # 67 C 99 c
4 eot^D 36 $ 68 D 100 d
5 enq^E 37 % 69 E 101 e
6 ask^F 38 & 70 F 102 f
7 bel^G 39 ‘ 71 G 103 g
8 bs^H 40 ( 72 H 104 h
9 ht^I 41 ) 73 I 105 i
10 lf^J 42 * 74 J 106 j
11 vt^K 43 + 75 K 107 k
12 vt^K 44 ‘ 76 L 108 l
13 cr^M 45 - 77 M 109 m
14 so^N 46 . 78 N 110 n
15 si^O 47 / 79 O 111 o
16 dle^P 48 0 80 P 112 p
17 dc1^Q 49 1 81 Q 113 q
18 dc2^R 50 2 82 R 114 r
19 dc3^S 51 3 83 S 115 s
20 dc4^T 52 4 84 T 116 t
21 nak^U 53 5 85 U 117 u
22 syn^V 54 6 86 V 118 v
OBJECT-ORIENTED PROGRAMMING JAVA Programming

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:

String firstName = "Audrey";

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:

char aNewLine = '\n';


char aTabChar = '\t';

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.

Escape Sequence Description


\b Backspace; moves the cursor one space to the left
\t Tab; moves the cursor to the next tab stop
\n Newline or linefeed; moves the cursor to the beginning of the next line
\r Carriage return; moves the cursor to the beginning of the current line
\” Double quotation mark; displays a double quotation mark
\’ Single quotation mark; displays a single quotation mark
\\ Backslash; displays a backslash character
Table 2-6 Common escape sequences

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.

public class HelloThereNewLine {


public static void main(String[] args) {
System.out.println("Hello\nThere");
}
}
Figure 2-1 HelloThereNewLine class

public class HelloTherePrintlnTwice {


public static void main(String[] args) {
System.out.println("Hello");
System.out.println("There");
}
}
Figure 2-2 HelloTherePrintlnTwice class

DISPLAYING DATA AND PERFORMING ARITHMETIC


You can display a variable or a constant in a print() or println() statement alone or in
combination with a string. For example, the NumbersPrintln class shown in Figure 2-3 declares
an integer billingDate, which is initialized to 5. In the first shaded statement, the value of
billingDate is sent alone to the print() method; in the second shaded statement,
billingDate is combined with, or concatenated to, a String. In Java, when a numeric variable
is concatenated to a String using the plus sign, the entire expression becomes a String. The
println() method can accept either a number or a String, so both statements work. The
output of the application shown in Figure 2-3 appears in Figure 2-4.

public class NumbersPrintln {


public static void main(String[] args) {
int billingDate = 5;
System.out.println("Bills are sent on day ");
System.out.println(billingDate);
System.out.println(" of the month");
System.out.println("Next bill: October " + billingDate);
}
}

Figure 2-3 NumbersPrintln class

Figure 2-4 Output of NumbersPrintln application

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

showMessageDialog() method twice to display an integer declared as creditDays and


initialized to 30. In each shaded statement in the class, the numeric variable is concatenated to
a String, making the entire second argument a String. In the first shaded statement, the
concatenated String is an empty String (or null String), created by typing a set of quotes with
nothing between them. The application produces the two dialog boxes shown in Figures 2-6 and
2-7. The first dialog box shows just the value 30; after it is dismissed by clicking OK, the second
dialog box appears.

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

Figure 2-6 First dialog box created by NumbersDialog application

Figure 2-7 Second dialog created by NumbersDialog application

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.

Operator Description Example


+ Addition 45 + 2, the result is 47
- Subtraction 45-2, the result is 43
* Multiplication 45 * 2, the result is 90
OBJECT-ORIENTED PROGRAMMING JAVA Programming

/ Division 45.0 / 2, the result is 22.5


45 / 2, the result is 22 (not 22.5)
% Remainder (modulus) 45 % 2, the result is 1 (that is, 45 / 2 = 22
with a remainder of 1)
Table 2-7 Arithmetic operators

Java supports two types of division:

• 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:

• 39 % 5 is 4 because 5 goes into 39 seven times with a remainder of 4.


• 20 % 3 is 2 because when 20 is divided by 3, the remainder is 2. 36 % 4 is 0 because there is
no remainder when 4 is divided into 36.

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.

Writing Arithmetic Statements Efficiently

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:

stateWithholding = hours * rate * STATE_RATE;


federalWithholding = hours * rate * FED_RATE;

With this approach, you perform the multiplication of hours * rate twice. It is more efficient to
perform the calculation once, as follows:

grossPay = hours * rate;


stateWithholding = grossPay * STATE_RATE;
federalWithholding = grossPay * FED_RATE;

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.

Pitfall: Not Understanding Imprecision in Floating-Point Numbers

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

public class ImprecissionDemo {


public static void main(String[] args) {
double answer = 2.20 - 2.0;
boolean isEqual = answr == 0.20;
System.out.println("answer is " + answer);
System.out.println("isEqual is " + isEqual);
}
}
Figure 2-8 The ImprecisionDemo program

Figure 2-9 Execution of the ImprecisionDemo program

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.

UNDERSTANDING NUMERIC TYPE CONVERSION


When you perform arithmetic with variables or constants of the same type, the result of the
operation retains the same type. For example, when you divide two ints, the result is an int, and
when you subtract two doubles, the result is a double. Often, however, you might want to
perform mathematical operations on operands with unlike types.

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:

int hoursWorked = 37;


double payRate = 6.73;
double grossPay = hoursWorked * payRate;
OBJECT-ORIENTED PROGRAMMING JAVA Programming

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.

int hoursWorked = 37;


double payRate = 6.73;
int grossPay = hoursWorked * payRate;

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:

double bankBalance = 189.66;


float weeklyBudget = (float) (bankBalance / 4);
// weeklyBudget is 47.415, one-fourth of bankBalance

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:

float myMoney = 47.82f;


int dollars = (int) myMoney;
// dollars is 47, the integer part of myMoney

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:

double payRate = 10;

However, for clarity, if you want to assign 10 to payRate, you might prefer to write the
following:

double payRate = 10.0;

The result is identical to the result when you assign the literal integer 10 to the double variable.

USING THE SCANNER CLASS FOR KEYBOARD INPUT


In Lesson 1, you learned how to display output on the monitor using the System.out property.
System.out refers to the standard output device, which usually is the monitor. Frequently you
also want to create interactive programs that accept input from a user. To do so, you can use
System.in, which refers to the standard input device (normally the keyboard).

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:

Scanner inputDevice = new Scanner(System.in);

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.

Figure 2-11 shows a typical execution of the program.


OBJECT-ORIENTED PROGRAMMING JAVA Programming

Figure 2-10 The GetUserInfo class

Figure 2-11 Typical execution of the GetUserInfo program

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

Figure 2-12 The GetUserInfo2 class

Figure 2-13 Typical execution of the GetUserInfo2 program

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

Figure 2-14 The GetUsaerInfo3 class

Figure 2-15 Typical execution of the GetUserInfo3 program

You might also like