[go: up one dir, main page]

0% found this document useful (0 votes)
10 views50 pages

Chapter 2

Chapter 2 of 'Java Programming, 9E' covers the fundamentals of using data in Java, including declaring constants and variables, understanding different data types (integer, boolean, floating-point, and char), and using the Scanner class for input. It explains the characteristics of constants and variables, the importance of data types, and provides guidelines for variable declaration and initialization. Additionally, it discusses the use of relational operators and the significance of scope in programming.

Uploaded by

moekadi.molefe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views50 pages

Chapter 2

Chapter 2 of 'Java Programming, 9E' covers the fundamentals of using data in Java, including declaring constants and variables, understanding different data types (integer, boolean, floating-point, and char), and using the Scanner class for input. It explains the characteristics of constants and variables, the importance of data types, and provides guidelines for variable declaration and initialization. Additionally, it discusses the use of relational operators and the significance of scope in programming.

Uploaded by

moekadi.molefe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

JAVA

PROGRAMMING, 9E

CHAPTER 2

Using Data
OBJECTIVES
• Upon completion of this chapter you will be
able to:
• Declare and use constants and
variables
• Use integer data types
• Use the boolean data type
• Use floating-point data types
• Use the char data type
• Use the Scanner class to accept
keyboard input
• Use the JOptionPane class to accept
GUI input
• Perform arithmetic
• Understand type conversion

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-
protected website for classroom use.
DECLARING AND USING
CONSTANTS AND
VARIABLES (1 OF 4)
• Constant
• Cannot be changed while program
is running
• Literal constant
• Value taken literally at each use
• Numeric constant
• As opposed to a literal constant
• Unnamed constant
• No identifier is associated with it

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-
protected website for classroom use.
DECLARING AND USING
CONSTANTS AND VARIABLES (2 OF
4)
• Variable
• A named memory location
• Used to store a value
• Can hold only one value at a time
• Its value can change
• Data type
• A type of data that can be stored
• How much memory an item occupies
• What types of operations can be performed on data

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
DECLARING AND USING
CONSTANTS AND VARIABLES (3 OF
4)
• Primitive type
• A simple data type
• Reference types
• More complex data types

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Table 2-1: Java primitive
data types
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

DECLARING AND USING CONSTANTS


AND VARIABLES (4 OF 4)
© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
DECLARING VARIABLES (1 OF
3)
Name variables

• Use naming rules for legal class identifiers

Variable declaration

• A statement that reserves a named memory location


• Includes:
• Data type
• Identifier
• Optional assignment operator and assigned value
• Ending semicolon

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
DECLARING VARIABLES (2 OF
3)
Assignment • The equal sign (=)
• The value to the right is assigned to the variable on the left
operator

Initialization • An assignment made when declaring a variable

Assignment • An assignment made after a variable is declared

Associativity • The order in which operands are used with operators

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
DECLARING VARIABLES (3 OF
3)
• Declare multiple variables of the same type in
separate statements on different lines
int myAge = 25;
int yourAge = 19;
• When declaring variables of different types, you must
use a separate statement for each type

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• A named constant:
• Should not change during program
DECLARING execution
NAMED • Has a data type, name, and value
• Has a data type preceded by the
CONSTANTS keyword final
(1 OF 2) • Can be assigned a value only once
• Conventionally is given identifiers using
all uppercase letters

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• Reasons for using named constants:
• Make programs easier to read and
DECLARING understand
NAMED • Enable you to change a value at one
location within a program
CONSTANTS • Reduce typographical errors
(2 OF 2) • Stand out as separate from variables
• Eliminates magic numbers

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• Scope
THE SCOPE • The area in which a data item is visible
OF to a program, and in which you can refer
to it using its simple identifier
VARIABLES • A variable or constant is in scope from the
AND point it is declared
CONSTANTS • Until the end of the block of code
where the declaration lies

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• print() or println() statement
• Use alone or in combination with a
String
CONCATENATING • Concatenated
STRINGS TO • A numeric variable is concatenated to a
VARIABLES AND String using the plus sign
CONSTANTS (1 OF • The entire expression becomes a String
3)
• The println() method can accept a
number or String

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• Use a dialog box to display values
JOptionPane.showMessageDialog()
CONCATENATING • Does not accept a single numeric
STRINGS TO VARIABLES variable
AND CONSTANTS (2 OF
• Null String
3)
• An empty string: ""

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
CONCATENATING STRINGS TO
VARIABLES AND CONSTANTS (3 OF 3)

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as per
mitted in a license distributed with a certain product or service or otherwise on a password-protected
website for classroom use.
PITFALL:
FORGETTIN • Each constant can hold only one value for
G THAT A the duration of the program
VARIABLE • Switch values of two variables
• Use a third variable
HOLDS ONE
VALUE AT A
TIME

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• int data type
LEARNING • Stores an integer, or whole number
• Value from –2,147,483,648 to
ABOUT +2,147,483,647

INTEGER • Variations of the integer type


• byte
DATA TYPES • short

(1 OF 2) • long
• Choose appropriate types for variables

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Table 2-
2: Limits
on
integer
values
by type
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, 8
9,223,372,036,854,775,8 807
08
LEARNING ABOUT INTEGER
DATA TYPES (2 OF 2)
© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Boolean logic Based on true-or-false comparisons

Can hold only one of two values


boolean variable true or false
• boolean isItPayday = false;

Relational
operator Compares two items
(comparison
operator)

USING THE BOOLEAN DATA


TYPE (1 OF 2)
© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Table 2-3:
Relational
operators
Operator Description True False
Example Example
< 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 7 >= 3 1 >= 2
to
!= Not equal to 5 != 6 3 != 3

USING THE BOOLEAN DATA


TYPE (2 OF 2)
© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Floating-point number

LEARNING • Contains decimal positions

ABOUT Floating-point data


types
FLOATING- • float
POINT • double
DATA
Significant digits
TYPES (1
• Refers to mathematical
OF 2) accuracy

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for
classroom use.
Table 2-4:
Limits on
floating-
point
values
Type Minimum Maximu Size in
m Bytes
float –3.4 * 1038 3.4 * 1038 4
double –1.7 * 10308 1.7 * 10308 8

LEARNING ABOUT FLOATING-


POINT DATA TYPES (2 OF 2)
© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
char data
Holds any single character
type

USING THE Place


constant

CHAR DATA
character
values
char myMiddleInitial = 'M';
within

TYPE (1 OF
single
quotation
marks

3)
A built-in class
Stores and manipulates character strings
String
String constants are written between
double quotation marks

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for
classroom use.
USING THE CHAR DATA
TYPE (2 OF 3)

Begins with a backslash followed by a


character
Escape sequence Represents a single nonprinting character
• char aNewLine = '\n';

To produce console output on


multiple lines in the command Use the newline escape sequence
window, use one of these Use the println() method multiple times
options:

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Table 2-6: Common
escape sequences
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

USING THE CHAR DATA TYPE (3 OF


3)
© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING THE SCANNER
CLASS TO ACCEPT
KEYBOARD INPUT (1 OF 3)
• System.in object
• Standard input device
• Normally the keyboard
• Access using the Scanner
class
• Scanner object
• Breaks input into units called
tokens

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-
protected website for classroom use.
Table 2-7: Selected
Scanner class
methods
Method Description
nextDouble() Retrieves input as a double
USING THE nextInt() Retrieves input as an int

SCANNER nextLine() Retrieves the next line of data and


returns it as a String
CLASS TO next() Retrieves the next complete token as
a String
ACCEPT nextShort() Retrieves input as a short

KEYBOARD nextByte() Retrieves input as a byte

INPUT (2 OF
nextFloat() Retrieves input as a float. Note that
when you enter an input value that
will be stored as a float, you do not
3) type an F. The F is used only with
constants coded within a program.
nextLong() Retrieves input as a long. Note that
when you enter an input value that
will be stored as a long, you do not
type an L. The L is used only with
constants coded within a program.

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING THE SCANNER CLASS TO
ACCEPT KEYBOARD INPUT (3 OF
3)

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as per
mitted in a license distributed with a certain product or service or otherwise on a password-protected
website for classroom use.
PITFALL: USING NEXTLINE()
FOLLOWING ONE OF THE
OTHER SCANNER INPUT
METHODS
• There is a problem when using one
numeric Scanner class retrieval
method or next()method before using
the nextLine()method
• Keyboard buffer
• Location in memory that stores all
keystrokes, including Enter
• To avoid issues, add an extra
nextLine()method call to retrieve the
abandoned Enter key character after
numeric or next() inputs

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-
protected website for classroom use.
USING THE JOPTIONPANE
CLASS TO ACCEPT GUI INPUT
• Dialog boxes used to accept user input:
• Input dialog box
• Confirm dialog box

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING INPUT DIALOG
BOXES (1 OF 5)
• Input dialog box
• Asks a question
• Provides a text field in which the user can enter a
response
• showInputDialog() method
• Six overloaded versions
• Returns a String representing a user’s response
• Prompt
• A message requesting user input

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING INPUT
DIALOG BOXES
(2 OF 5)

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING INPUT
DIALOG BOXES
(3 OF 5)

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING INPUT DIALOG
BOXES (4 OF 5)
• showInputDialog()
• One version requires four arguments:
• Parent component
• Message
• Title
• Type of dialog box
• Convert String to int or double
• Use methods from the built-in Java classes Integer and
Double

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING INPUT DIALOG
BOXES (5 OF 5)
• Type-wrapper classes
• Each primitive type has a corresponding class contained
in the java.lang package
• Include methods to process primitive type values
Integer.parseInt()
Double.parseDouble()

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• Confirm dialog box
USING • Displays the options Yes, No, and Cancel
• showConfirmDialog() method in
CONFIRM JOptionPane class

DIALOG
• Four overloaded versions are available
• Returns integer containing either:

BOXES JOptionPane.YES_OPTION
JOptionPane.NO_OPTION
(1 OF 3) JOptionPane.CANCEL_OPTION

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING • You can create a confirm dialog box with five
arguments:

CONFIRM • Parent component


• Prompt message
DIALOG • Title
• Integer that indicates which option
BOXES button to show
• Integer that describes the kind of dialog
(2 OF 3) box

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
USING CONFIRM
DIALOG BOXES
(3 OF 3)

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
PERFORMING ARITHMETIC USING VARIABLES
AND CONSTANTS (1 OF 2)

• Standard arithmetic operators


• Perform calculations with values in programs
• Operand
• A value used on either side of an operator
• Integer division
• Involves integer constants or integer variables
• The result is an integer
• Any fractional part of the result is lost

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
PERFORMING ARITHMETIC USING
VARIABLES AND CONSTANTS (2 OF
2)

Table 2-8:
Arithmetic
operators
Operator Description Example
+ Addition 45 + 2, the result is 47
– Subtraction 45 – 2, the result is 43
* Multiplication 45 * 2, the result is 90
/ Division 45.0 / 2, the result is 22.5
45 / 2, the result is 22 (not 22.5)
% Remainder 45 % 2, the result is 1 (that is,
(modulus) 45/2 = 22 with a remainder of
1)

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• Operator precedence
• The rules for the order in which parts of
ASSOCIATIVITY mathematical expressions are evaluated
AND • First multiplication, division, and
PRECEDENCE remainder (modulus), then addition or
subtraction

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
WRITING ARITHMETIC
STATEMENTS EFFICIENTLY
• Avoid unnecessary repetition of arithmetic statements
• Example of inefficient calculation:
stateWithholding = hours * rate * STATE_RATE;
federalWithholding = hours * rate * FED_RATE;
• Example of efficient calculation:
grossPay = hours * rate;
stateWithholding = grossPay * STATE_RATE;
federalWithholding = grossPay * FED_RATE;

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
PITFALL: NOT UNDERSTANDING
IMPRECISION IN FLOATING-POINT
NUMBERS

• Integer values are exact


• But floating-point numbers
frequently are only
approximations
• Imprecision leads to several
problems
• Floating-point output might
not look like what you expect
or want
• Comparisons with floating-
point numbers might not be
what you expect or want

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-
protected website for classroom use.
UNDERSTANDING TYPE
CONVERSION
Arithmetic with • The result of arithmetic retains the same
variables or constants type
of the same type

Arithmetic operations • Java chooses the unifying type for the


with operands of result
unlike types
• The type to which all operands in an
Unifying type expression are converted for
compatibility

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as per
mitted in a license distributed with a certain product or service or otherwise on a password-protected
website for classroom use.
• Automatically converts nonconforming
operands to the unifying type
• Order for establishing unifying types
AUTOMATIC between two variables (highest to lowest):
TYPE 1. double
2. float
CONVERSION 3. long
4. int

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
• Type casting
• Forces a value of one data type to be
used as a value of another data type
• Cast operator
EXPLICIT TYPE
• Place desired result type in parentheses
CONVERSIONS
• Using a cast operator is an explicit
conversion
• You do not need to perform a cast when
assigning a value to a higher unifying type

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a
license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
DON’T DO IT (1 OF 2)
• Don’t mispronounce integer
• Don’t attempt to assign a literal constant floating-point
number
• Don’t forget precedence rules
• Don’t forget that integer division results in an integer
• Don’t attempt to assign a constant decimal value to an
integer using a leading 0
• Don’t use a single equal sign (=) in a Boolean comparison
for equality
• Don’t try to store a string of characters in a char variable

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
DON’T DO IT (2 OF 2)
• Don’t forget that when a String and a numeric value are
concatenated, the resulting expression is a string
• Don’t forget to consume the Enter key after numeric input
using the Scanner class when a nextLine()method call follows
• Don’t forget to use the appropriate import statement when
using the Scanner or JOptionPane class
• Don’t forget precedence rules
• Don’t forget that integer division results in an integer
• Don’t forget that floating—point numbers are imprecise
• Don’t use a single equal sign in a Boolean for comparison for
equality

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.
SUMMARY (1 OF
2)
• Variables
• Named memory locations
• Primitive data types
• Standard arithmetic operators
for integers:
+, _, *, /, and %
• Boolean type
– true or false value
• Relational operators:
>, <, ==, >=, <=, and !=

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-
protected website for classroom use.
SUMMARY (2 OF 2)
• Floating-point data types
• float
• double
• char data type
• Scanner class
• Access keyboard input
• JOptionPane
• Confirm dialog box
• Input dialog box

© 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use.

You might also like