• No results found

Chapter 2: Objects and Chapter 2: Objects and Primitive Data Primitive Data

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 2: Objects and Chapter 2: Objects and Primitive Data Primitive Data"

Copied!
47
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 2: Objects and Chapter 2: Objects and

Primitive Data Primitive Data

Presentation slides for Presentation slides for

Java Software Solutions Java Software Solutions

Foundations of Program Design Foundations of Program Design

Second Edition Second Edition

by John Lewis and William Loftus by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

(2)

2

Objects and Primitive Data Objects and Primitive Data

We can now explore some more fundamental programming We can now explore some more fundamental programming concepts

concepts

Chapter 2 focuses on: Chapter 2 focuses on:

predefined objectspredefined objects

primitive dataprimitive data

the declaration and use of variablesthe declaration and use of variables

expressions and operator precedenceexpressions and operator precedence

class librariesclass libraries

Java appletsJava applets

drawing shapesdrawing shapes

(3)

Introduction to Objects Introduction to Objects

Initially, we can think of an Initially, we can think of an object object as a collection of services as a collection of services that we can tell it to perform for us

that we can tell it to perform for us

The services are defined by methods in a class that defines The services are defined by methods in a class that defines the object

the object

In the Lincoln program, we invoked the In the Lincoln program, we invoked the println println method method of the

of the System.out System.out object: object:

System.out.println ("Whatever you are, be a good one.");

object

object methodmethod

Information provided to the method Information provided to the method

(parameters) (parameters)

(4)

4

The println and print Methods The println and print Methods

The The System.out System.out object provides another service as well object provides another service as well

The The print print method is similar to the method is similar to the println println method, method, except that it does not advance to the next line

except that it does not advance to the next line

Therefore anything printed after a Therefore anything printed after a print statement will print statement will appear on the same line

appear on the same line

See See Countdown.java Countdown.java (page 53) (page 53)

(5)

Abstraction Abstraction

An An abstraction abstraction hides (or ignores) the right details at the hides (or ignores) the right details at the right time

right time

An object is abstract in that we don't really have to think An object is abstract in that we don't really have to think about its internal details in order to use it

about its internal details in order to use it

We don't have to know how the We don't have to know how the println println method works in method works in order to invoke it

order to invoke it

A human being can only manage seven (plus or minus 2) A human being can only manage seven (plus or minus 2) pieces of information at one time

pieces of information at one time

But if we group information into chunks (such as objects) But if we group information into chunks (such as objects) we can manage many complicated pieces at once

we can manage many complicated pieces at once

Therefore, we can write complex software by organizing it Therefore, we can write complex software by organizing it

(6)

6

The String Class The String Class

Every character string is an object in Java, defined by the Every character string is an object in Java, defined by the String

String class class

Every string literal, delimited by double quotation marks, Every string literal, delimited by double quotation marks, represents a

represents a String String object object

The The string concatenation operator string concatenation operator (+) is used to append one (+) is used to append one string to the end of another

string to the end of another

It can also be used to append a number to a string It can also be used to append a number to a string

A string literal cannot be broken across two lines in a A string literal cannot be broken across two lines in a program

program

See Facts.java (page 56) See Facts.java (page 56)

(7)

String Concatenation String Concatenation

The plus operator (+) is also used for arithmetic addition The plus operator (+) is also used for arithmetic addition

The function that the + operator performs depends on the The function that the + operator performs depends on the type of the information on which it operates

type of the information on which it operates

If both operands are strings, or if one is a string and one is If both operands are strings, or if one is a string and one is a number, it performs string concatenation

a number, it performs string concatenation

If both operands are numeric, it adds them If both operands are numeric, it adds them

The + operator is evaluated left to right The + operator is evaluated left to right

Parentheses can be used to force the operation order Parentheses can be used to force the operation order

See Addition.java (page 58) See Addition.java (page 58)

(8)

8

Escape Sequences Escape Sequences

What if we wanted to print a double quote character? What if we wanted to print a double quote character?

The following line would confuse the compiler because it The following line would confuse the compiler because it would interpret the second quote as the end of the string would interpret the second quote as the end of the string

System.out.println ("I said "Hello" to you.");

An An escape sequence escape sequence is a series of characters that represents is a series of characters that represents a special character

a special character

An escape sequence begins with a backslash character ( An escape sequence begins with a backslash character ( \ \ ), ), which indicates that the character(s) that follow should be which indicates that the character(s) that follow should be

treated in a special way treated in a special way

System.out.println ("I said \"Hello\" to you.");

(9)

Escape Sequences Escape Sequences

Some Java escape sequences: Some Java escape sequences:

See Roses.java (page 59) See Roses.java (page 59)

Escape Sequence

\b

\t

\n

\r

\"

\'

\\

Meaning backspace

tab newline carriage return

double quote single quote

backslash

(10)

10

Variables Variables

A A variable variable is a name for a location in memory is a name for a location in memory

A variable must be A variable must be declared declared , specifying the variable's name , specifying the variable's name and the type of information that will be held in it

and the type of information that will be held in it

int total;

int count, temp, result;

Multiple variables can be created in one declaration Multiple variables can be created in one declaration data type

data type variable namevariable name

(11)

Variables Variables

A variable can be given an initial value in the declaration A variable can be given an initial value in the declaration

When a variable is referenced in a program, its current When a variable is referenced in a program, its current value is used

value is used

See PianoKeys.java (page 60) See PianoKeys.java (page 60)

int sum = 0;

int base = 32, max = 149;

(12)

12

Assignment Assignment

An An assignment statement assignment statement changes the value of a variable changes the value of a variable

The assignment operator is the The assignment operator is the = sign = sign

total = 55;

You can only assign a value to a variable that is consistent You can only assign a value to a variable that is consistent with the variable's declared type

with the variable's declared type

The expression on the right is evaluated and the result is The expression on the right is evaluated and the result is stored in the variable on the left

stored in the variable on the left

The value that was in The value that was in total is overwritten total is overwritten

See Geometry.java (page 62) See Geometry.java (page 62)

(13)

Constants Constants

A constant is an identifier that is similar to a variable A constant is an identifier that is similar to a variable except that it holds one value for its entire existence except that it holds one value for its entire existence

The compiler will issue an error if you try to change a The compiler will issue an error if you try to change a constant

constant

In Java, we use the In Java, we use the final final modifier to declare a constant modifier to declare a constant

final int MIN_HEIGHT = 69;

Constants: Constants:

give names to otherwise unclear literal valuesgive names to otherwise unclear literal values

facilitate changes to the codefacilitate changes to the code

prevent inadvertent errorsprevent inadvertent errors

(14)

Primitive Data Primitive Data

There are exactly eight primitive data types in Java There are exactly eight primitive data types in Java

Four of them represent integers: Four of them represent integers:

bytebyte, , shortshort, , intint, , longlong

Two of them represent floating point numbers: Two of them represent floating point numbers:

float, float, doubledouble

One of them represents characters: One of them represents characters:

charchar

And one of them represents boolean values: And one of them represents boolean values:

booleanboolean

(15)

Numeric Primitive Data Numeric Primitive Data

The difference between the various numeric primitive types The difference between the various numeric primitive types is their size, and therefore the values they can store:

is their size, and therefore the values they can store:

Type byte short int long float double

Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits

Min Value -128

-32,768

-2,147,483,648

< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits

Max Value 127

32,767

2,147,483,647

> 9 x 1018

(16)

16

Characters Characters

A A char char variable stores a single character from the variable stores a single character from the Unicode character set

Unicode character set

A A character set character set is an ordered list of characters, and each is an ordered list of characters, and each character corresponds to a unique number

character corresponds to a unique number

The Unicode character set uses sixteen bits per character, The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters

allowing for 65,536 unique characters

It is an international character set, containing symbols and It is an international character set, containing symbols and characters from many world languages

characters from many world languages

Character literals are delimited by single quotes: Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n'

'a' 'X' '7' '$' ',' '\n'

(17)

Characters Characters

The The ASCII character set ASCII character set is older and smaller than Unicode, is older and smaller than Unicode, but is still quite popular

but is still quite popular

The ASCII characters are a subset of the Unicode The ASCII characters are a subset of the Unicode character set, including:

character set, including:

uppercase letters lowercase letters punctuation

digits

special symbols control characters

A, B, C, … a, b, c, …

period, semi-colon, … 0, 1, 2, …

&, |, \, …

carriage return, tab, ...

(18)

18

Boolean Boolean

A A boolean boolean value represents a true or false condition value represents a true or false condition

A boolean can also be used to represent any two states, such A boolean can also be used to represent any two states, such as a light bulb being on or off

as a light bulb being on or off

The reserved words The reserved words true true and and false false are the only valid are the only valid values for a boolean type

values for a boolean type

boolean done = false;

boolean done = false;

(19)

Arithmetic Expressions Arithmetic Expressions

An An expression expression is a combination of operators and operands is a combination of operators and operands

Arithmetic expressions Arithmetic expressions compute numeric results and make compute numeric results and make use of the arithmetic operators:

use of the arithmetic operators:

Addition +

Subtraction -

Multiplication *

Division /

Remainder %

If either or both operands to an arithmetic operator are If either or both operands to an arithmetic operator are floating point, the result is a floating point

floating point, the result is a floating point

(20)

Division and Remainder Division and Remainder

If both operands to the division operator ( If both operands to the division operator ( /) are integers, / ) are integers, the result is an integer (the fractional part is discarded) the result is an integer (the fractional part is discarded)

The remainder operator (%) returns the remainder after The remainder operator (%) returns the remainder after dividing the second operand into the first

dividing the second operand into the first

14 / 3 equals?

8 / 12 equals?

4 0

14 % 3 equals?

8 % 12 equals?

2 8

(21)

Operator Precedence Operator Precedence

Operators can be combined into complex expressions Operators can be combined into complex expressions

result = total + count / max - offset;

Operators have a well-defined precedence which Operators have a well-defined precedence which determines the order in which they are evaluated determines the order in which they are evaluated

Multiplication, division, and remainder are evaluated prior Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation

to addition, subtraction, and string concatenation

Arithmetic operators with the same precedence are Arithmetic operators with the same precedence are evaluated from left to right

evaluated from left to right

Parentheses can always be used to force the evaluation Parentheses can always be used to force the evaluation order

order

(22)

Operator Precedence Operator Precedence

What is the order of evaluation in the following What is the order of evaluation in the following expressions?

expressions?

a + b + c + d + e

1 2 3 4

a + b * c - d / e

3 1 4 2

a / (b + c) - d % e

2 1 4 3

a / (b * (c + (d - e)))

4 3 2 1

(23)

Assignment Revisited Assignment Revisited

The assignment operator has a lower precedence than the The assignment operator has a lower precedence than the arithmetic operators

arithmetic operators

First the expression on the right hand First the expression on the right hand

side of the = operator is evaluated side of the = operator is evaluated

Then the result is stored in the Then the result is stored in the variable on the left hand side variable on the left hand side

answer = sum / 4 + MAX * lowest;

1

4 3 2

(24)

Assignment Revisited Assignment Revisited

The right and left hand sides of an assignment statement The right and left hand sides of an assignment statement can contain the same variable

can contain the same variable

First, one is added to the First, one is added to the

original value of

original value of countcount

Then the result is stored back into

Then the result is stored back into countcount (overwriting the original value)

(overwriting the original value) count = count + 1;

(25)

Data Conversions Data Conversions

Sometimes it is convenient to convert data from one type to Sometimes it is convenient to convert data from one type to another

another

For example, we may want to treat an integer as a floating For example, we may want to treat an integer as a floating point value during a computation

point value during a computation

Conversions must be handled carefully to avoid losing Conversions must be handled carefully to avoid losing information

information

Widening conversions Widening conversions are safest because they tend to go are safest because they tend to go from a small data type to a larger one (such as a

from a small data type to a larger one (such as a short short to to an an int int ) )

Narrowing conversions Narrowing conversions can lose information because they can lose information because they

tend to go from a large data type to a smaller one (such as

tend to go from a large data type to a smaller one (such as

an an int to a to a short ) )

(26)

Data Conversions Data Conversions

In Java, data conversions can occur in three ways: In Java, data conversions can occur in three ways:

assignment conversionassignment conversion

arithmetic promotionarithmetic promotion

castingcasting

Assignment conversion Assignment conversion occurs when a value of one type is occurs when a value of one type is assigned to a variable of another

assigned to a variable of another

Only widening conversions can happen via assignment Only widening conversions can happen via assignment

Arithmetic promotion Arithmetic promotion happens automatically when happens automatically when

operators in expressions convert their operands

operators in expressions convert their operands

(27)

Data Conversions Data Conversions

Casting Casting is the most powerful, and dangerous, technique for is the most powerful, and dangerous, technique for conversion

conversion

Both widening and narrowing conversions can be Both widening and narrowing conversions can be accomplished by explicitly casting a value

accomplished by explicitly casting a value

To cast, the type is put in parentheses in front of the value To cast, the type is put in parentheses in front of the value being converted

being converted

For example, if For example, if total total and and count count are integers, but we are integers, but we want a floating point result when dividing them, we can want a floating point result when dividing them, we can

cast

cast total total : :

result = (float) total / count;

(28)

Creating Objects Creating Objects

A variable either holds a primitive type, or it holds a A variable either holds a primitive type, or it holds a reference

reference to an object to an object

A class name can be used as a type to declare an A class name can be used as a type to declare an object object reference variable

reference variable

String title;

No object has been created with this declaration No object has been created with this declaration

An object reference variable holds the address of an object An object reference variable holds the address of an object

The object itself must be created separately The object itself must be created separately

(29)

Creating Objects Creating Objects

We use the We use the new new operator to create an object operator to create an object

title = new String ("Java Software Solutions");

This calls the

This calls the StringString constructorconstructor, which is, which is a special method that sets up the object a special method that sets up the object

Creating an object is called Creating an object is called instantiation instantiation

An object is an An object is an instance instance of a particular class of a particular class

(30)

Creating Objects Creating Objects

Because strings are so common, we don't have to use the Because strings are so common, we don't have to use the new new operator to create a operator to create a String String object object

title = "Java Software Solutions";

This is special syntax that only works for strings This is special syntax that only works for strings

Once an object has been instantiated, we can use the Once an object has been instantiated, we can use the dot dot operator

operator to invoke its methods to invoke its methods

title.length()

(31)

String Methods String Methods

The The String class has several methods that are useful for String class has several methods that are useful for manipulating strings

manipulating strings

Many of the methods Many of the methods return a value return a value , such as an integer or a , such as an integer or a new new String String object object

See the list of See the list of String methods on page 75 and in Appendix String methods on page 75 and in Appendix M M

See StringMutation.java (page 77) See StringMutation.java (page 77)

(32)

Class Libraries Class Libraries

A A class library class library is a collection of classes that we can use when is a collection of classes that we can use when developing programs

developing programs

There is a There is a Java standard class library Java standard class library that is part of any that is part of any Java development environment

Java development environment

These classes are not part of the Java language per se, but These classes are not part of the Java language per se, but we rely on them heavily

we rely on them heavily

The The System class and the System class and the String class are part of the String class are part of the Java standard class library

Java standard class library

Other class libraries can be obtained through third party Other class libraries can be obtained through third party vendors, or you can create them yourself

vendors, or you can create them yourself

(33)

Packages Packages

The classes of the Java standard class library are organized The classes of the Java standard class library are organized into packages

into packages

Some of the packages in the standard class library are: Some of the packages in the standard class library are:

Package

java.lang java.applet java.awt

javax.swing java.net

java.util

Purpose

General support

Creating applets for the web

Graphics and graphical user interfaces

Additional graphics capabilities and components Network communication

Utilities

(34)

The import Declaration The import Declaration

When you want to use a class from a package, you could When you want to use a class from a package, you could use its

use its fully qualified name fully qualified name

java.util.Random

Or you can Or you can import import the class, then just use the class name the class, then just use the class name

import java.util.Random;

To import all classes in a particular package, you can use To import all classes in a particular package, you can use the * wildcard character

the * wildcard character

import java.util.*;

(35)

The import Declaration The import Declaration

All classes of the All classes of the java.lang java.lang package are automatically package are automatically imported into all programs

imported into all programs

That's why we didn't have to explicitly import the That's why we didn't have to explicitly import the System System or or String String classes in earlier programs classes in earlier programs

The The Random class is part of the Random class is part of the java.util java.util package package

It provides methods that generate pseudo-random numbers It provides methods that generate pseudo-random numbers

We often have to We often have to scale scale and and shift shift a number into an a number into an appropriate range for a particular purpose

appropriate range for a particular purpose

See RandomNumbers.java (page 82) See RandomNumbers.java (page 82)

(36)

Class Methods Class Methods

Some methods can be invoked through the class name, Some methods can be invoked through the class name, instead of through an object of the class

instead of through an object of the class

These methods are called These methods are called class methods class methods or or static methods static methods

The The Math Math class contains many static methods, providing class contains many static methods, providing various mathematical functions, such as absolute value, various mathematical functions, such as absolute value,

trigonometry functions, square root, etc.

trigonometry functions, square root, etc.

temp = Math.cos(90) + Math.sqrt(delta);

(37)

The Keyboard Class The Keyboard Class

The The Keyboard class is NOT part of the Java standard Keyboard class is NOT part of the Java standard class library

class library

It is provided by the authors of the textbook to make It is provided by the authors of the textbook to make reading input from the keyboard easy

reading input from the keyboard easy

Details of the Details of the Keyboard Keyboard class are explored in Chapter 8 class are explored in Chapter 8

For now we will simply make use of it For now we will simply make use of it

The The Keyboard class is part of a package called Keyboard class is part of a package called cs1 cs1 , and , and contains several static methods for reading particular types contains several static methods for reading particular types

of data of data

See Echo.java (page 86) See Echo.java (page 86)

See Quadratic.java (page 87) See Quadratic.java (page 87)

(38)

Formatting Output Formatting Output

The The NumberFormat NumberFormat class has static methods that return a class has static methods that return a formatter object

formatter object

getCurrencyInstance() getPercentInstance()

Each formatter object has a method called Each formatter object has a method called format format that that returns a string with the specified information in the

returns a string with the specified information in the appropriate format

appropriate format

See Price.java (page 89) See Price.java (page 89)

(39)

Formatting Output Formatting Output

The The DecimalFormat class can be used to format a DecimalFormat class can be used to format a floating point value in generic ways

floating point value in generic ways

For example, you can specify that the number be printed to For example, you can specify that the number be printed to three decimal places

three decimal places

The constructor of the The constructor of the DecimalFormat DecimalFormat class takes a class takes a string that represents a pattern for the formatted number string that represents a pattern for the formatted number

See CircleStats.java (page 91) See CircleStats.java (page 91)

(40)

Applets Applets

A Java application is a stand-alone program with a A Java application is a stand-alone program with a main main method (like the ones we've seen so far)

method (like the ones we've seen so far)

An An applet applet is a Java program that is intended to transported is a Java program that is intended to transported over the web and executed using a web browser

over the web and executed using a web browser

An applet can also be executed using the appletviewer tool An applet can also be executed using the appletviewer tool of the Java Software Development Kit

of the Java Software Development Kit

An applet doesn't have a An applet doesn't have a main main method method

Instead, there are several special methods that serve Instead, there are several special methods that serve specific purposes

specific purposes

The The paint paint method, for instance, is automatically executed method, for instance, is automatically executed and is used to draw the applets contents

and is used to draw the applets contents

(41)

Applets Applets

The paint method accepts a parameter that is an object of The paint method accepts a parameter that is an object of the the Graphics Graphics class class

A A Graphics Graphics object defines a object defines a graphics context graphics context on which we on which we can draw shapes and text

can draw shapes and text

The The Graphics Graphics class has several methods for drawing class has several methods for drawing shapes

shapes

The class that defines the applet The class that defines the applet extends extends the Applet class the Applet class

This makes use of This makes use of inheritance inheritance , an object-oriented concept , an object-oriented concept explored in more detail in Chapter 7

explored in more detail in Chapter 7

See Einstein.java (page 93)

(42)

Applets Applets

An applet is embedded into an HTML file using a tag that An applet is embedded into an HTML file using a tag that references the bytecode file of the applet class

references the bytecode file of the applet class

It is actually the bytecode version of the program that is It is actually the bytecode version of the program that is transported across the web

transported across the web

The applet is executed by a Java interpreter that is part of The applet is executed by a Java interpreter that is part of the browser

the browser

(43)

Drawing Shapes Drawing Shapes

Let's explore some of the methods of the Let's explore some of the methods of the Graphics class Graphics class that draw shapes in more detail

that draw shapes in more detail

A shape can be filled or unfilled, depending on which A shape can be filled or unfilled, depending on which method is invoked

method is invoked

The method parameters specify coordinates and sizes The method parameters specify coordinates and sizes

Recall from Chapter 1 that the Java coordinate system has Recall from Chapter 1 that the Java coordinate system has the origin in the upper left corner

the origin in the upper left corner

Many shapes with curves, like an oval, are drawn by Many shapes with curves, like an oval, are drawn by specifying its

specifying its bounding rectangle bounding rectangle

An arc can be thought of as a section of an oval An arc can be thought of as a section of an oval

(44)

Drawing a Line Drawing a Line

X

Y

10 20

150

45

page.drawLine (10, 20, 150, 45);

page.drawLine (150, 45, 10, 20);

oror

(45)

Drawing a Rectangle Drawing a Rectangle

X

Y

page.drawRect (50, 20, 100, 40);

50 20

100

40

(46)

Drawing an Oval Drawing an Oval

X

Y

page.drawOval (175, 20, 50, 80);

175 20

50

80

bounding bounding rectangle rectangle

(47)

The Color Class The Color Class

A color is defined in a Java program using an object A color is defined in a Java program using an object created from the

created from the Color Color class class

The The Color Color class also contains several static predefined class also contains several static predefined colors

colors

Every graphics context has a current foreground color Every graphics context has a current foreground color

Every drawing surface has a background color Every drawing surface has a background color

See Snowman.java (page 99-100) See Snowman.java (page 99-100)

References

Related documents

The Engineering schools are School of Chemical Engineering, School of Civil Engineering, School of Information Technology and Electrical Engineering, and School of Mechanical

This chapter has introduced a basic problem class, discussing along the way practi- cal algorithmic strategies, but steadily introducing issues that address the richness

The Ministry of Defence, more specifically, the Department of Pensions of the said Ministry and the Personnel Services Directorate of the Army Headquarters,

 Business objects and rules document -- in a structured way -- a class diagram.  Such a documentation is also called

CAPS decision, engine-out plan, investigations, flightaware data, slow flight training, low-key, high-key, accident rates, spins, recovery, spin training.. Partner

Prevalence and Predictors of Low Serum 25-Hydroxyvitamin D Prevalence and Predictors of Low Serum 25-Hydroxyvitamin D among Female African-American Breast Cancer Survivors

Positive olfaction involves a conscious awareness of odours as located in time and space, while olfactory experience of absence involves making perceptual contact with those

Based on these facts, the major role of human capital in the formation of the National Innovation System, is materialized as a solution to speed up implementation