chapter 2 data and expressions [compatibility mode]

49
22-Sep-13 1 Chapter 2 Data and Expressions Java Software Solutions Foundations of Program Design Seventh Edition Copyright © 2012 Pearson Education, Inc. John Lewis William Loftus Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: character strings primitive data the declaration and use of variables expressions and operator precedence data conversions data conversions accepting input from the user Java applets introduction to graphics Copyright © 2012 Pearson Education, Inc.

Upload: muhammad-rizwan

Post on 14-Aug-2015

43 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

1

Chapter 2Data and Expressions

Java Software SolutionsFoundations of Program Design

Seventh Edition

Copyright © 2012 Pearson Education, Inc.

John LewisWilliam Loftus

Data and Expressions• Let's explore some other fundamental programming

concepts

• Chapter 2 focuses on:

– character strings– primitive data– the declaration and use of variables– expressions and operator precedence

data conversions– data conversions– accepting input from the user– Java applets– introduction to graphics

Copyright © 2012 Pearson Education, Inc.

Page 2: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

2

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Character Strings• A string literal is represented by putting double

quotes around the text

• Examples:

"This is a string literal.""123 Main Street""X"

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

• Every string literal represents a String object

Copyright © 2012 Pearson Education, Inc.

Page 3: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

3

The println Method• In the Lincoln program from Chapter 1, we

invoked the println method to print a character stringg

• The System.out object represents a destination (the monitor screen) to which we can send output

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

object methodname information provided to the method

(parameters)

Copyright © 2012 Pearson Education, Inc.

The print Method• The System.out object provides another service

as well

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

• Therefore anything printed after a printstatement will appear on the same linepp

• See Countdown.java

Copyright © 2012 Pearson Education, Inc.

Page 4: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

4

//********************************************************************// Countdown.java Author: Lewis/Loftus//// Demonstrates the difference between print and println.//********************************************************************

public class Countdownpublic class Countdown{

//-----------------------------------------------------------------// Prints two lines of output representing a rocket countdown.//-----------------------------------------------------------------public static void main (String[] args){

System.out.print ("Three... ");System.out.print ("Two... ");System.out.print ("One... ");System.out.print ("Zero... ");

i l ( if ff! ) // fi li

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Liftoff!"); // appears on first output lineSystem.out.println ("Houston, we have a problem.");

}}

//********************************************************************// Countdown.java Author: Lewis/Loftus//// Demonstrates the difference between print and println.//********************************************************************

public class Countdown

Output

Three... Two... One... Zero... Liftoff!Houston, we have a problem.

public class Countdown{

//-----------------------------------------------------------------// Prints two lines of output representing a rocket countdown.//-----------------------------------------------------------------public static void main (String[] args){

System.out.print ("Three... ");System.out.print ("Two... ");System.out.print ("One... ");System.out.print ("Zero... ");

i l ( if ff! ) // fi li

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Liftoff!"); // appears on first output lineSystem.out.println ("Houston, we have a problem.");

}}

Page 5: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

5

String Concatenation

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

"Peanut butter " + "and jelly"

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

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

See F t j• See Facts.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Facts.java Author: Lewis/Loftus//// Demonstrates the use of the string concatenation operator and the// automatic conversion of an integer to a string.//********************************************************************

public class Factspublic class Facts{

//-----------------------------------------------------------------// Prints various facts.//-----------------------------------------------------------------public static void main (String[] args){

// Strings can be concatenated into one long stringSystem.out.println ("We present the following facts for your "

+ "extracurricular edification:");

Copyright © 2012 Pearson Education, Inc.

System.out.println ();

// A string can contain numeric digitsSystem.out.println ("Letters in the Hawaiian alphabet: 12");

continue

Page 6: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

6

continue

// A numeric value can be concatenated to a stringSystem.out.println ("Dialing code for Antarctica: " + 672);

System.out.println ("Year in which Leonardo da Vinci invented "+ "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year");}

}

Copyright © 2012 Pearson Education, Inc.

continue

OutputWe present the following facts for your extracurricular edification:

// A numeric value can be concatenated to a stringSystem.out.println ("Dialing code for Antarctica: " + 672);

System.out.println ("Year in which Leonardo da Vinci invented "+ "the parachute: " + 1515);

System.out.println ("Speed of ketchup: " + 40 + " km per year");}

}

We present the following facts for your extracurricular edification:

Letters in the Hawaiian alphabet: 12Dialing code for Antarctica: 672Year in which Leonardo da Vinci invented the parachute: 1515Speed of ketchup: 40 km per year

Copyright © 2012 Pearson Education, Inc.

Page 7: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

7

String Concatenation• The + operator is also used for arithmetic addition

• The function that it performs depends on the type of the information on which it operatesinformation on which it operates

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

• If both operands are numeric, it adds them

• The + operator is evaluated left to right, but parentheses p g , pcan be used to force the order

• See Addition.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Addition.java Author: Lewis/Loftus//// Demonstrates the difference between the addition and string// concatenation operators.//********************************************************************

public class Addition{

//-----------------------------------------------------------------// Concatenates and adds two numbers and prints the results.//-----------------------------------------------------------------public static void main (String[] args){

System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45));

Copyright © 2012 Pearson Education, Inc.

}}

Page 8: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

8

//********************************************************************// Addition.java Author: Lewis/Loftus//// Demonstrates the difference between the addition and string// concatenation operators.//********************************************************************

Output

24 and 45 concatenated: 244524 and 45 added: 69

public class Addition{

//-----------------------------------------------------------------// Concatenates and adds two numbers and prints the results.//-----------------------------------------------------------------public static void main (String[] args){

System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45));

Copyright © 2012 Pearson Education, Inc.

}}

Quick Check

What output is produced by the following?

System.out.println ("X: " + 25);System.out.println ( X: 25);System.out.println ("Y: " + (15 + 50));System.out.println ("Z: " + 300 + 50);

Copyright © 2012 Pearson Education, Inc.

Page 9: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

9

Quick Check

What output is produced by the following?

System.out.println ("X: " + 25);System.out.println ( X: 25);System.out.println ("Y: " + (15 + 50));System.out.println ("Z: " + 300 + 50);

X: 25Y: 65

Copyright © 2012 Pearson Education, Inc.

Z: 30050

Escape Sequences• What if we wanted to print the quote character?

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

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

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

• An escape sequence begins with a backslash character (\)

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

Copyright © 2012 Pearson Education, Inc.

Page 10: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

10

Escape Sequences

• Some Java escape sequences:

Escape Sequence Meaningp q

\b\t\n\r\"\'\\

g

backspacetabnewlinecarriage returndouble quotesingle quotebackslash\\ backslash

Copyright © 2012 Pearson Education, Inc.

• See Roses.java

//********************************************************************// Roses.java Author: Lewis/Loftus//// Demonstrates the use of escape sequences.//********************************************************************

bli l Rpublic class Roses{

//-----------------------------------------------------------------// Prints a poem (of sorts) on multiple lines.//-----------------------------------------------------------------public static void main (String[] args){

System.out.println ("Roses are red,\n\tViolets are blue,\n" +"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +"So I'd rather just be friends\n\tAt this point in our " +"relationship.");

Copyright © 2012 Pearson Education, Inc.

}}

Page 11: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

11

//********************************************************************// Roses.java Author: Lewis/Loftus//// Demonstrates the use of escape sequences.//********************************************************************

bli l R

Output

Roses are red,Violets are blue,

Sugar is sweet,But I have "commitment issues",

public class Roses{

//-----------------------------------------------------------------// Prints a poem (of sorts) on multiple lines.//-----------------------------------------------------------------public static void main (String[] args){

System.out.println ("Roses are red,\n\tViolets are blue,\n" +"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +"So I'd rather just be friends\n\tAt this point in our " +"relationship.");

,So I'd rather just be friendsAt this point in our relationship.

Copyright © 2012 Pearson Education, Inc.

}}

Quick Check

Write a single println statement that produces the following output:

"Thank you all for coming to my hometonight," he said mysteriously.

Copyright © 2012 Pearson Education, Inc.

Page 12: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

12

Quick Check

Write a single println statement that produces the following output:

"Thank you all for coming to my hometonight," he said mysteriously.

System.out.println ("\"Thank you all for " +"coming to my home\ntonight,\" he said " +

Copyright © 2012 Pearson Education, Inc.

"mysteriously.");

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Page 13: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

13

Variables• A variable is a name for a location in memory that

holds a value

• A variable declaration specifies the variable's name and the type of information that it will hold

int total;

data type variable name

;

int count, temp, result;

Multiple variables can be created in one declaration

Copyright © 2012 Pearson Education, Inc.

Variable Initialization

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

int sum = 0;int base = 32, max = 149;

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

S Pi K j

Copyright © 2012 Pearson Education, Inc.

• See PianoKeys.java

Page 14: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

14

//********************************************************************// PianoKeys.java Author: Lewis/Loftus//// Demonstrates the declaration, initialization, and use of an// integer variable.//********************************************************************

public class PianoKeys{

//-----------------------------------------------------------------// Prints the number of keys on a piano.//-----------------------------------------------------------------public static void main (String[] args){

int keys = 88;System.out.println ("A piano has " + keys + " keys.");

}

Copyright © 2012 Pearson Education, Inc.

}

//********************************************************************// PianoKeys.java Author: Lewis/Loftus//// Demonstrates the declaration, initialization, and use of an// integer variable.//********************************************************************

Output

A piano has 88 keys.

public class PianoKeys{

//-----------------------------------------------------------------// Prints the number of keys on a piano.//-----------------------------------------------------------------public static void main (String[] args){

int keys = 88;System.out.println ("A piano has " + keys + " keys.");

}

Copyright © 2012 Pearson Education, Inc.

}

Page 15: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

15

Assignment• An assignment statement changes the value of a

variable

Th i t t i th i• The assignment operator is the = sign

total = 55;

• The value that was in total is overwritten

Copyright © 2012 Pearson Education, Inc.

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

• See Geometry.java

//********************************************************************// Geometry.java Author: Lewis/Loftus//// Demonstrates the use of an assignment statement to change the// value stored in a variable.//********************************************************************

public class Geometry{

//-----------------------------------------------------------------// Prints the number of sides of several geometric shapes.//-----------------------------------------------------------------public static void main (String[] args){

int sides = 7; // declaration with initializationSystem.out.println ("A heptagon has " + sides + " sides.");

Copyright © 2012 Pearson Education, Inc.

sides = 10; // assignment statementSystem.out.println ("A decagon has " + sides + " sides.");

sides = 12;System.out.println ("A dodecagon has " + sides + " sides.");

}}

Page 16: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

16

//********************************************************************// Geometry.java Author: Lewis/Loftus//// Demonstrates the use of an assignment statement to change the// value stored in a variable.//********************************************************************

Output

A heptagon has 7 sides.A decagon has 10 sides.a dodecagon has 12 sides.

public class Geometry{

//-----------------------------------------------------------------// Prints the number of sides of several geometric shapes.//-----------------------------------------------------------------public static void main (String[] args){

int sides = 7; // declaration with initializationSystem.out.println ("A heptagon has " + sides + " sides.");

Copyright © 2012 Pearson Education, Inc.

sides = 10; // assignment statementSystem.out.println ("A decagon has " + sides + " sides.");

sides = 12;System.out.println ("A dodecagon has " + sides + " sides.");

}}

Constants• A constant is an identifier that is similar to a

variable except that it holds the same value during its entire existence

• As the name implies, it is constant, not variable

• The compiler will issue an error if you try to change the value of a constant

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

final int MIN_HEIGHT = 69;

Copyright © 2012 Pearson Education, Inc.

Page 17: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

17

Constants• Constants are useful for three important reasons

• First, they give meaning to otherwise unclear literal values

– Example: MAX_LOAD means more than the literal 250

• Second, they facilitate program maintenance

– If a constant is used in multiple places, its value need only be set in one placeonly be set in one place

• Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers

Copyright © 2012 Pearson Education, Inc.

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Page 18: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

18

Primitive Data• There are eight primitive data types in Java

• Four of them represent integers:– byte, short, int, long

• Two of them represent floating point numbers:– float, double

• One of them represents characters:char– char

• And one of them represents boolean values:– boolean

Copyright © 2012 Pearson Education, Inc.

Numeric Primitive Data

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

Type

byteshortintlong

Storage

8 bits16 bits32 bits64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

Max Value

12732,7672,147,483,647> 9 x 1018

floatdouble

32 bits64 bits

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

Copyright © 2012 Pearson Education, Inc.

Fahim g
Highlight
Fahim g
Highlight
Fahim g
Highlight
Fahim g
Highlight
Fahim g
Highlight
Page 19: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

19

Characters• A char variable stores a single character

• Character literals are delimited by single quotes:

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

• Example declarations:

char topGrade = 'A';char terminator = ';', separator = ' ';

• Note the difference between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters

Copyright © 2012 Pearson Education, Inc.

Character Sets• A character set is an ordered list of characters,

with each character corresponding to a unique number

• A char variable in Java can store any character from the Unicode character set

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

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

Copyright © 2012 Pearson Education, Inc.

Page 20: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

20

Characters

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

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

uppercase letterslowercase letterspunctuation

A, B, C, …a, b, c, …period, semi-colon, …

digitsspecial symbolscontrol characters

0, 1, 2, …&, |, \, …carriage return, tab, ...

Copyright © 2012 Pearson Education, Inc.

Boolean• A boolean value represents a true or false

condition

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

boolean done = false;

• A boolean variable can also be used to represent t t t h li ht b lb b i ffany two states, such as a light bulb being on or off

Copyright © 2012 Pearson Education, Inc.

Page 21: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

21

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Expressions• An expression is a combination of one or more

operators and operands

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

AdditionSubtractionMultiplicationDivisionRemainder

+-*/%Remainder %

Copyright © 2012 Pearson Education, Inc.

• If either or both operands are floating point values, then the result is a floating point value

Page 22: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

22

Division and Remainder

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

14 / 3 equals 48 / 12 equals 0

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

Copyright © 2012 Pearson Education, Inc.

g p y

14 % 3 equals 28 % 12 equals 8

Quick Check

What are the results of the following expressions?

12 / 212 / 2

12.0 / 2.0

10 / 4

10 / 4.0

4 / 10

4.0 / 10

Copyright © 2012 Pearson Education, Inc.

12 % 3

10 % 3

3 % 10

Page 23: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

23

Quick Check

What are the results of the following expressions?

12 / 2 = 612 / 2

12.0 / 2.0

10 / 4

10 / 4.0

4 / 10

4.0 / 10

6

= 6.0

= 2

= 2.5

= 0

= 0.4

Copyright © 2012 Pearson Education, Inc.

12 % 3

10 % 3

3 % 10

= 0

= 1

= 0

Operator Precedence

• Operators can be combined into larger expressions

result = total + count / max - offset;

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

• Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenationconcatenation

• Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order

Copyright © 2012 Pearson Education, Inc.

Page 24: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

24

Quick Check

In what order are the operators evaluated in the following expressions?

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

a / (b + c) - d % e

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

Copyright © 2012 Pearson Education, Inc.

Quick Check

In what order are the operators evaluated in the following expressions?

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

a / (b + c) - d % e

1 432 3 241

2 341

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

Copyright © 2012 Pearson Education, Inc.

Page 25: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

25

Expression Trees

• The evaluation of a particular expression can be shown using an expression tree

• The operators lower in the tree have higher precedence for that expression

a + (b – c) / d

a

+

/

- d

b c

Copyright © 2012 Pearson Education, Inc.

Assignment Revisited• The assignment operator has a lower precedence

than the arithmetic operators

First the expression on the right handside of the = operator is evaluated

answer = sum / 4 + MAX * lowest;

14 3 2

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

Copyright © 2012 Pearson Education, Inc.

Page 26: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

26

Assignment Revisited

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

First, one is added to theoriginal value of count

count = count + 1;

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

Copyright © 2012 Pearson Education, Inc.

Increment and Decrement

• The increment (++) and decrement (--) operators use only one operand

• The statement

count++;

is functionally equivalent to

count = count + 1;

Copyright © 2012 Pearson Education, Inc.

Page 27: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

27

Increment and Decrement• The increment and decrement operators can be

applied in postfix form:

tcount++

• or prefix form:

++count

• When used as part of a larger expression the twoWhen used as part of a larger expression, the two forms can have different effects

• Because of their subtleties, the increment and decrement operators should be used with care

Copyright © 2012 Pearson Education, Inc.

Assignment Operators• Often we perform an operation on a variable, and

then store the result back into that variable

• Java provides assignment operators to simplify that process

• For example, the statement

num += count;

is equivalent to

num = num + count;

Copyright © 2012 Pearson Education, Inc.

Page 28: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

28

Assignment Operators

• There are many assignment operators in Java, including the following:

Operator

+=-=*=/=

Example

x += yx -= yx *= yx /= y

Equivalent To

x = x + yx = x - yx = x * yx = x / y/

%=x / yx %= y

x x / yx = x % y

Copyright © 2012 Pearson Education, Inc.

Assignment Operators• The right hand side of an assignment operator can

be a complex expression

• The entire right-hand expression is evaluated first, then the result is combined with the original variable

• Therefore

result /= (total-MIN) % num;

is equivalent to

result = result / ((total-MIN) % num);

Copyright © 2012 Pearson Education, Inc.

Page 29: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

29

Assignment Operators

• The behavior of some assignment operators depends on the types of the operands

• If the operands to the += operator are strings, the assignment operator performs string concatenation

• The behavior of an assignment operator (+=) is always consistent with the behavior of the

di t ( )corresponding operator (+)

Copyright © 2012 Pearson Education, Inc.

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Page 30: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

30

Data Conversion

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

• For example, in a particular situation we may want to treat an integer as a floating point value

• These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation

Copyright © 2012 Pearson Education, Inc.

Data Conversion• Widening conversions are safest because they tend

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

• Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)

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

– assignment conversion– promotion– casting

Copyright © 2012 Pearson Education, Inc.

Page 31: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

31

Data Conversion

Widening Conversions Narrowing Conversions

Copyright © 2012 Pearson Education, Inc.

Assignment Conversion• Assignment conversion occurs when a value of one

type is assigned to a variable of another

• Example:• Example:

int dollars = 20;double money = dollars;

• Only widening conversions can happen via assignment

• Note that the value or type of dollars did not change

Copyright © 2012 Pearson Education, Inc.

Page 32: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

32

Promotion• Promotion happens automatically when operators

in expressions convert their operands

• Example:

int count = 12;double sum = 490.27;result = sum / count;

• The value of count is converted to a floating point value to perform the division calculation

Copyright © 2012 Pearson Education, Inc.

Casting• Casting is the most powerful, and dangerous,

technique for conversion

B th id i d i i b• Both widening and narrowing conversions can be accomplished by explicitly casting a value

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

int total = 50;float result = (float) total / 6;

• Without the cast, the fractional part of the answer would be lost

Copyright © 2012 Pearson Education, Inc.

Page 33: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

33

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Interactive Programs• Programs generally need input on which to

operate

• The Scanner class provides convenient methods for reading input values of various types

• A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard

• Keyboard input is represented by the System.inobject

Copyright © 2012 Pearson Education, Inc.

Page 34: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

34

Reading Input• The following line creates a Scanner object that

reads from the keyboard:

S S (S t i )Scanner scan = new Scanner (System.in);

• The new operator creates the Scanner object

• Once created, the Scanner object can be used to invoke various input methods, such as:

answer = scan.nextLine();

Copyright © 2012 Pearson Education, Inc.

Reading Input

• The Scanner class is part of the java.util class library, and must be imported into a program to be usedused

• The nextLine method reads all of the input until the end of the line is found

• See Echo.java

• The details of object creation and class libraries are discussed further in Chapter 3

Copyright © 2012 Pearson Education, Inc.

Page 35: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

35

//********************************************************************// Echo.java Author: Lewis/Loftus//// Demonstrates the use of the nextLine method of the Scanner class// to read a string from the user.//********************************************************************

import java.util.Scanner;

public class Echo{

//-----------------------------------------------------------------// Reads a character string from the user and prints it.//-----------------------------------------------------------------public static void main (String[] args){

String message;Scanner scan = new Scanner (System.in);

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Enter a line of text:");

message = scan.nextLine();

System.out.println ("You entered: \"" + message + "\"");}

}

//********************************************************************// Echo.java Author: Lewis/Loftus//// Demonstrates the use of the nextLine method of the Scanner class// to read a string from the user.//********************************************************************

import java.util.Scanner;

Sample Run

Enter a line of text:You want fries with that?You entered: "You want fries with that?"

public class Echo{

//-----------------------------------------------------------------// Reads a character string from the user and prints it.//-----------------------------------------------------------------public static void main (String[] args){

String message;Scanner scan = new Scanner (System.in);

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Enter a line of text:");

message = scan.nextLine();

System.out.println ("You entered: \"" + message + "\"");}

}

Page 36: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

36

Input Tokens• Unless specified otherwise, white space is used to

separate the elements (called tokens) of the input

Whit i l d h t t b• White space includes space characters, tabs, new line characters

• The next method of the Scanner class reads the next input token and returns it as a string

• Methods such as nextInt and nextDoubleMethods such as nextInt and nextDoubleread data of particular types

• See GasMileage.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// GasMileage.java Author: Lewis/Loftus//// Demonstrates the use of the Scanner class to read numeric data.//********************************************************************

import java.util.Scanner;p j ;

public class GasMileage{

//-----------------------------------------------------------------// Calculates fuel efficiency based on values entered by the// user.//-----------------------------------------------------------------public static void main (String[] args){

int miles;double gallons mpg;

Copyright © 2012 Pearson Education, Inc.

double gallons, mpg;

Scanner scan = new Scanner (System.in);

continue

Page 37: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

37

continue

System out print ("Enter the number of miles: ");System.out.print ( Enter the number of miles: );miles = scan.nextInt();

System.out.print ("Enter the gallons of fuel used: ");gallons = scan.nextDouble();

mpg = miles / gallons;

System.out.println ("Miles Per Gallon: " + mpg);}

}

Copyright © 2012 Pearson Education, Inc.

continue

System out print ("Enter the number of miles: ");

Sample Run

Enter the number of miles: 328System.out.print ( Enter the number of miles: );miles = scan.nextInt();

System.out.print ("Enter the gallons of fuel used: ");gallons = scan.nextDouble();

mpg = miles / gallons;

System.out.println ("Miles Per Gallon: " + mpg);}

}

Enter the gallons of fuel used: 11.2Miles Per Gallon: 29.28571428571429

Copyright © 2012 Pearson Education, Inc.

Page 38: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

38

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Introduction to Graphics• The last few sections of each chapter of the textbook focus

on graphics and graphical user interfaces

A i t d i t b di iti d f t• A picture or drawing must be digitized for storage on a computer

• A picture is made up of pixels (picture elements), and each pixel is stored separately

• The number of pixels used to represent a picture is called the picture resolution

• The number of pixels that can be displayed by a monitor is called the monitor resolution

Copyright © 2012 Pearson Education, Inc.

Page 39: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

39

Representing Images• A digitized picture with a small portion magnified:

Copyright © 2012 Pearson Education, Inc.

Coordinate Systems• Each pixel can be identified using a two-dimensional

coordinate system

Wh f i t i l i J• When referring to a pixel in a Java program, we use a coordinate system with the origin in the top-left corner

X(0, 0) 112

Y

(112, 40)40

Copyright © 2012 Pearson Education, Inc.

Page 40: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

40

Representing Color

• A black and white picture could be stored using one bit per pixel (0 = white and 1 = black)

• A colored picture requires more information; there are several techniques for representing colors

• Every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue

• Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value

Copyright © 2012 Pearson Education, Inc.

The Color Class• A color in a Java program is represented as an

object created from the Color class

f• The Color class also contains several predefined colors, including the following:

Object

Color.blackColor.blue

RGB Value

0, 0, 00, 0, 255

Color.cyanColor.orangeColor.whiteColor.yellow

0, 255, 255255, 200, 0255, 255, 255255, 255, 0

Copyright © 2012 Pearson Education, Inc.

Page 41: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

41

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

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

• A Java applet is a program that is intended to be transported over the Web and executed using a web browser

• An applet also can be executed using the appletviewer tool of the Java SDK

• An applet doesn't have a main method

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

Copyright © 2012 Pearson Education, Inc.

Page 42: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

42

Applets• The paint method is executed automatically

whenever the applet’s contents are drawn

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

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

The G hi class has several methods for• The Graphics class has several methods for drawing shapes

Copyright © 2012 Pearson Education, Inc.

Applets• We create an applet by extending the JApplet

class

Th l i t f th• The JApplet class is part of the javax.swing package

• This makes use of inheritance, which is explored in more detail in Chapter 8

• See Einstein java• See Einstein.java

Copyright © 2012 Pearson Education, Inc.

Page 43: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

43

//********************************************************************// Einstein.java Author: Lewis/Loftus//// Demonstrates a basic applet.//********************************************************************

import javax.swing.JApplet;import java.awt.*;

public class Einstein extends JApplet{

//-----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes.//-----------------------------------------------------------------public void paint (Graphics page){

page.drawRect (50, 50, 40, 40); // squarepage.drawRect (60, 80, 225, 30); // rectanglepage.drawOval (75, 65, 20, 20); // circle

Copyright © 2012 Pearson Education, Inc.

page.drawOval (75, 65, 20, 20); // circlepage.drawLine (35, 60, 100, 120); // line

page.drawString ("Out of clutter, find simplicity.", 110, 70);page.drawString ("-- Albert Einstein", 130, 100);

}}

//********************************************************************// Einstein.java Author: Lewis/Loftus//// Demonstrates a basic applet.//********************************************************************

import javax.swing.JApplet;import java.awt.*;

public class Einstein extends JApplet{

//-----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes.//-----------------------------------------------------------------public void paint (Graphics page){

page.drawRect (50, 50, 40, 40); // squarepage.drawRect (60, 80, 225, 30); // rectanglepage.drawOval (75, 65, 20, 20); // circle

Copyright © 2012 Pearson Education, Inc.

page.drawOval (75, 65, 20, 20); // circlepage.drawLine (35, 60, 100, 120); // line

page.drawString ("Out of clutter, find simplicity.", 110, 70);page.drawString ("-- Albert Einstein", 130, 100);

}}

Page 44: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

44

The HTML applet Tag• An applet is embedded into an HTML file using a

tag that references the bytecode file of the applet

f

<html><head>

<title>The Einstein Applet</title>

• The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser

pp</head><body>

<applet code="Einstein.class" width=350 height=175></applet>

</body></html>

Copyright © 2012 Pearson Education, Inc.

Outline

Character Strings

Variables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Graphics

Applets

Drawing Shapes

Copyright © 2012 Pearson Education, Inc.

Page 45: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

45

Drawing Shapes

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

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

• The method parameters specify coordinates and sizes

• Shapes with curves like an oval are usually drawn• Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle

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

Copyright © 2012 Pearson Education, Inc.

Drawing a Line

X10 150

20

45

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

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

Copyright © 2012 Pearson Education, Inc.

Page 46: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

46

Drawing a Rectangle

X50

20

100

40

Y

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

Copyright © 2012 Pearson Education, Inc.

Drawing an Oval

X175

20

50

80

boundingrectangle

Y

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

50

Copyright © 2012 Pearson Education, Inc.

Page 47: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

47

Drawing an Arc• An arc is defined by an oval, a start angle, and an

arc angle:

Copyright © 2012 Pearson Education, Inc.

Drawing Shapes

• Every drawing surface has a background color

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

• Both can be set explicitly

• See Snowman.java

Copyright © 2012 Pearson Education, Inc.

Page 48: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

48

//********************************************************************// Snowman.java Author: Lewis/Loftus//// Demonstrates basic drawing methods and the use of color.//********************************************************************

import javax.swing.JApplet;import java.awt.*;

p blic class Sno man e tends JAppletpublic class Snowman extends JApplet{

//-----------------------------------------------------------------// Draws a snowman.//-----------------------------------------------------------------public void paint (Graphics page){

final int MID = 150;final int TOP = 50;

setBackground (Color.cyan);

Copyright © 2012 Pearson Education, Inc.

page.setColor (Color.blue);page.fillRect (0, 175, 300, 50); // ground

page.setColor (Color.yellow);page.fillOval (-40, -40, 80, 80); // sun

continued

continued

page.setColor (Color.white);page.fillOval (MID-20, TOP, 40, 40); // headpage.fillOval (MID-35, TOP+35, 70, 50); // upper torsopage.fillOval (MID-50, TOP+80, 100, 60); // lower torso

page.setColor (Color.black);page.fillOval (MID-10, TOP+10, 5, 5); // left eyepage.fillOval (MID+5, TOP+10, 5, 5); // right eye

page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile

page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left armpage.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm

page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat

Copyright © 2012 Pearson Education, Inc.

page.fillRect (MID-15, TOP-20, 30, 25); // top of hat}

}

Page 49: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

49

continued

page.setColor (Color.white);page.fillOval (MID-20, TOP, 40, 40); // headpage.fillOval (MID-35, TOP+35, 70, 50); // upper torsopage.fillOval (MID-50, TOP+80, 100, 60); // lower torso

page.setColor (Color.black);page.fillOval (MID-10, TOP+10, 5, 5); // left eyepage.fillOval (MID+5, TOP+10, 5, 5); // right eye

page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile

page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left armpage.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm

page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat

Copyright © 2012 Pearson Education, Inc.

page.fillRect (MID-15, TOP-20, 30, 25); // top of hat}

}

Summary

• Chapter 2 focused on:

– character strings– primitive data– the declaration and use of variables– expressions and operator precedence– data conversions– accepting input from the user– Java appletsJava applets– introduction to graphics

Copyright © 2012 Pearson Education, Inc.

Page 50: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

1

Chapter 3Using Classes and Objects

Java Software SolutionsFoundations of Program Design

Seventh Edition

Copyright © 2012 Pearson Education, Inc.

John LewisWilliam Loftus

Using Classes and Objects• We can create more interesting programs using predefined

classes and related objects

Ch t 3 f• Chapter 3 focuses on:

– object creation and object references– the String class and its methods

– the Java API class library– the Random and Math classes

– formatting output

– enumerated types

– wrapper classes

– graphical components and containers

– labels and images

Copyright © 2012 Pearson Education, Inc.

Page 51: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

2

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Creating Objects• A variable holds either a primitive value or a

reference to an object

A l b d t t d l• A class name can be used as a type to declare an object reference variable

String title;

• No object is created with this declaration

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

• The object itself must be created separately

Copyright © 2012 Pearson Education, Inc.

Page 52: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

3

Creating Objects

• Generally, we use the new operator to create an object

• Creating an object is called instantiation

• An object is an instance of a particular class

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

This calls the String constructor, which isa special method that sets up the object

Copyright © 2012 Pearson Education, Inc.

Invoking Methods

• We've seen that once an object has been instantiated, we can use the dot operator to invoke its methodsits methods

numChars = title.length()

• A method may return a value, which can be used in an assignment or expression

• A method invocation can be thought of as asking an object to perform a service

Copyright © 2012 Pearson Education, Inc.

Page 53: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

4

References• Note that a primitive variable contains the value

itself, but an object variable contains the address of the objectj

• An object reference can be thought of as a pointer to the location of the object

• Rather than dealing with arbitrary addresses, we often depict a reference graphically

"Steve Jobs"name1

num1 38

Copyright © 2012 Pearson Education, Inc.

Assignment Revisited• The act of assignment takes a copy of a value and

stores it in a variable

• For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Copyright © 2012 Pearson Education, Inc.

Page 54: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

5

Reference Assignment

• For object references, assignment copies the address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

Copyright © 2012 Pearson Education, Inc.

Aliases• Two or more references that refer to the same

object are called aliases of each other

• That creates an interesting situation: one object can be accessed using multiple reference variables

• Aliases can be useful, but should be managed carefully

• Changing an object through one reference• Changing an object through one reference changes it for all of its aliases, because there is really only one object

Copyright © 2012 Pearson Education, Inc.

Page 55: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

6

Garbage Collection• When an object no longer has any valid references

to it, it can no longer be accessed by the program

• The object is useless, and therefore is called garbage

• Java performs automatic garbage collectionperiodically, returning an object's memory to the system for future use

• In other languages, the programmer is responsible for performing garbage collection

Copyright © 2012 Pearson Education, Inc.

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Page 56: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

7

The String Class

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

title = "Java Software Solutions";

• This is special syntax that works only for strings

• Each string literal (enclosed in double quotes) t bj trepresents a String object

Copyright © 2012 Pearson Education, Inc.

String Methods

• Once a String object has been created, neither its value nor its length can be changed

• Therefore we say that an object of the Stringclass is immutable

• However, several methods of the String class return new String objects that are modified versions of the original

Copyright © 2012 Pearson Education, Inc.

Page 57: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

8

String Indexes• It is occasionally helpful to refer to a particular

character within a string

• This can be done by specifying the character's numeric index

• The indexes begin at zero in each string

• In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4index 0 and the o is at index 4

• See StringMutation.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// StringMutation.java Author: Lewis/Loftus//// Demonstrates the use of the String class and its methods.//********************************************************************

public class StringMutation{

////-----------------------------------------------------------------// Prints a string and various mutations of it.//-----------------------------------------------------------------public static void main (String[] args){

String phrase = "Change is inevitable";String mutation1, mutation2, mutation3, mutation4;

System.out.println ("Original string: \"" + phrase + "\"");System.out.println ("Length of string: " + phrase.length());

Copyright © 2012 Pearson Education, Inc.

mutation1 = phrase.concat (", except from vending machines.");mutation2 = mutation1.toUpperCase();mutation3 = mutation2.replace ('E', 'X');mutation4 = mutation3.substring (3, 30);

continued

Page 58: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

9

continued

// Print each mutated string// Print each mutated stringSystem.out.println ("Mutation #1: " + mutation1);System.out.println ("Mutation #2: " + mutation2);System.out.println ("Mutation #3: " + mutation3);System.out.println ("Mutation #4: " + mutation4);

System.out.println ("Mutated length: " + mutation4.length());}

}

Copyright © 2012 Pearson Education, Inc.

continued

// Print each mutated string

OutputOriginal string: "Change is inevitable"Length of string: 20Mutation #1: Change is inevitable, except from vending machines.Mutation #2: CHANGE IS INEVITABLE EXCEPT FROM VENDING MACHINES// Print each mutated string

System.out.println ("Mutation #1: " + mutation1);System.out.println ("Mutation #2: " + mutation2);System.out.println ("Mutation #3: " + mutation3);System.out.println ("Mutation #4: " + mutation4);

System.out.println ("Mutated length: " + mutation4.length());}

}

Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES.Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS.Mutation #4: NGX IS INXVITABLX, XXCXPT FMutated length: 27

Copyright © 2012 Pearson Education, Inc.

Page 59: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

10

Quick Check

What output is produced by the following?

String str = "Space, the final frontier.";String str Space, the final frontier. ;System.out.println (str.length());System.out.println (str.substring(7));System.out.println (str.toUpperCase());System.out.println (str.length());

Copyright © 2012 Pearson Education, Inc.

Quick Check

What output is produced by the following?

String str = "Space, the final frontier.";String str Space, the final frontier. ;System.out.println (str.length());System.out.println (str.substring(7));System.out.println (str.toUpperCase());System.out.println (str.length());

26

Copyright © 2012 Pearson Education, Inc.

26the final frontier.SPACE, THE FINAL FRONTIER.26

Page 60: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

11

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Class Libraries• A class library is a collection of classes that we can

use when developing programs

• The Java standard class library is part of any Java development environment

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

• Various classes we've already used (System , Scanner, String) are part of the Java standard class library

Copyright © 2012 Pearson Education, Inc.

Page 61: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

12

The Java API• The Java class library is sometimes referred to as

the Java API

• API stands for Application Programming Interface

• Clusters of related classes are sometimes referred to as specific APIs:

– The Swing API

– The Database API

Copyright © 2012 Pearson Education, Inc.

The Java API• Get comfortable navigating the online Java API

documentation

Copyright © 2012 Pearson Education, Inc.

Page 62: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

13

Packages• For purposes of accessing them, classes in the

Java API are organized into packages

Th ft l ith ifi API• These often overlap with specific APIs

• Examples:

Package

java.langjava.applet

Purpose

General supportCreating applets for the webj pp

java.awtjavax.swingjava.netjava.utiljavax.xml.parsers

g ppGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilitiesXML document processing

Copyright © 2012 Pearson Education, Inc.

The import Declaration• When you want to use a class from a package, you

could use its fully qualified name

j ijava.util.Scanner

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

import java.util.Scanner;

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

import java.util.*;

Copyright © 2012 Pearson Education, Inc.

Page 63: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

14

The import Declaration• All classes of the java.lang package are

imported automatically into all programs

• It's as if all programs contain the following line:

import java.lang.*;

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

• The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported

Copyright © 2012 Pearson Education, Inc.

The Random Class

• The Random class is part of the java.utilpackage

• It provides methods that generate pseudorandom numbers

• A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random valuesg y

• See RandomNumbers.java

Copyright © 2012 Pearson Education, Inc.

Page 64: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

15

//********************************************************************// RandomNumbers.java Author: Lewis/Loftus//// Demonstrates the creation of pseudo-random numbers using the// Random class.//********************************************************************

import java.util.Random;

public class RandomNumbers{

//-----------------------------------------------------------------// Generates random numbers in various ranges.//-----------------------------------------------------------------public static void main (String[] args){

Random generator = new Random();int num1;float num2;

Copyright © 2012 Pearson Education, Inc.

num1 = generator.nextInt();System.out.println ("A random integer: " + num1);

num1 = generator.nextInt(10);System.out.println ("From 0 to 9: " + num1);

continued

continued

num1 = generator.nextInt(10) + 1;System.out.println ("From 1 to 10: " + num1);

num1 = generator nextInt(15) + 20;num1 = generator.nextInt(15) + 20;System.out.println ("From 20 to 34: " + num1);

num1 = generator.nextInt(20) - 10;System.out.println ("From -10 to 9: " + num1);

num2 = generator.nextFloat();System.out.println ("A random float (between 0-1): " + num2);

num2 = generator.nextFloat() * 6; // 0.0 to 5.999999num1 = (int)num2 + 1;S t t i tl ("F 1 t 6 " + 1)

Copyright © 2012 Pearson Education, Inc.

System.out.println ("From 1 to 6: " + num1);}

}

Page 65: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

16

continued

num1 = generator.nextInt(10) + 1;System.out.println ("From 1 to 10: " + num1);

num1 = generator nextInt(15) + 20;

Sample RunA random integer: 672981683From 0 to 9: 0From 1 to 10: 3From 20 to 34: 30num1 = generator.nextInt(15) + 20;

System.out.println ("From 20 to 34: " + num1);

num1 = generator.nextInt(20) - 10;System.out.println ("From -10 to 9: " + num1);

num2 = generator.nextFloat();System.out.println ("A random float (between 0-1): " + num2);

num2 = generator.nextFloat() * 6; // 0.0 to 5.999999num1 = (int)num2 + 1;S t t i tl ("F 1 t 6 " + 1)

From 20 to 34: 30From -10 to 9: -4A random float (between 0-1): 0.18538326From 1 to 6: 3

Copyright © 2012 Pearson Education, Inc.

System.out.println ("From 1 to 6: " + num1);}

}

Quick CheckGiven a Random object named gen, what range of values are produced by the following expressions?

gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(100) + 10

gen.nextInt(50) + 100

Copyright © 2012 Pearson Education, Inc.

g ( )

gen.nextInt(10) – 5

gen.nextInt(22) + 12

Page 66: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

17

Quick CheckGiven a Random object named gen, what range of values are produced by the following expressions?

gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(100) + 10

gen.nextInt(50) + 100

Range0 to 24

1 to 6

10 to 109

100 to 149

Copyright © 2012 Pearson Education, Inc.

g ( )

gen.nextInt(10) – 5

gen.nextInt(22) + 12

-5 to 4

12 to 33

Quick CheckWrite an expression that produces a random integer in the following ranges:

Range0 to 12

1 to 20

15 to 20

10 to 0

Copyright © 2012 Pearson Education, Inc.

-10 to 0

Page 67: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

18

Quick CheckWrite an expression that produces a random integer in the following ranges:

gen.nextInt(13)

gen.nextInt(20) + 1

gen.nextInt(6) + 15

gen nextInt(11) 10

Range0 to 12

1 to 20

15 to 20

10 to 0

Copyright © 2012 Pearson Education, Inc.

gen.nextInt(11) – 10-10 to 0

The Math Class• The Math class is part of the java.lang package

• The Math class contains methods that perform various mathematical functions

• These include:– absolute value

– square root

exponentiation– exponentiation

– trigonometric functions

Copyright © 2012 Pearson Education, Inc.

Page 68: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

19

The Math Class• The methods of the Math class are static methods

(also called class methods)

• Static methods are invoked through the class name – no object of the Math class is needed

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

• We discuss static methods further in Chapter 7

• See Quadratic.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Quadratic.java Author: Lewis/Loftus//// Demonstrates the use of the Math class to perform a calculation// based on user input.//********************************************************************

import java.util.Scanner;

public class Quadratic{

//-----------------------------------------------------------------// Determines the roots of a quadratic equation.//-----------------------------------------------------------------public static void main (String[] args){

int a, b, c; // ax^2 + bx + cdouble discriminant root1 root2;

Copyright © 2012 Pearson Education, Inc.

double discriminant, root1, root2;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter the coefficient of x squared: ");a = scan.nextInt();

continued

Page 69: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

20

continued

System.out.print ("Enter the coefficient of x: ");b = scan.nextInt();

System.out.print ("Enter the constant: ");c = scan.nextInt();()

// Use the quadratic formula to compute the roots.// Assumes a positive discriminant.

discriminant = Math.pow(b, 2) - (4 * a * c);root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);System.out.println ("Root #2: " + root2);

}

Copyright © 2012 Pearson Education, Inc.

}}

continued

System.out.print ("Enter the coefficient of x: ");b = scan.nextInt();

System.out.print ("Enter the constant: ");c = scan.nextInt();

Sample RunEnter the coefficient of x squared: 3Enter the coefficient of x: 8Enter the constant: 4Root #1: -0.6666666666666666Root #2: -2.0()

// Use the quadratic formula to compute the roots.// Assumes a positive discriminant.

discriminant = Math.pow(b, 2) - (4 * a * c);root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);System.out.println ("Root #2: " + root2);

}

#

Copyright © 2012 Pearson Education, Inc.

}}

Page 70: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

21

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Formatting Output• It is often necessary to format output values in

certain ways so that they can be presented properly

• The Java standard class library contains classes that provide formatting capabilities

• The NumberFormat class allows you to format values as currency or percentages

• The DecimalFormat class allows you to format• The DecimalFormat class allows you to format values based on a pattern

• Both are part of the java.text package

Copyright © 2012 Pearson Education, Inc.

Page 71: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

22

Formatting Output

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

getCurrencyInstance()

getPercentInstance()

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

• See Purchase.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Purchase.java Author: Lewis/Loftus//// Demonstrates the use of the NumberFormat class to format output.//********************************************************************

import java.util.Scanner;p jimport java.text.NumberFormat;

public class Purchase{

//-----------------------------------------------------------------// Calculates the final price of a purchased item using values// entered by the user.//-----------------------------------------------------------------public static void main (String[] args){

final double TAX RATE = 0 06; // 6% sales tax

Copyright © 2012 Pearson Education, Inc.

final double TAX_RATE = 0.06; // 6% sales tax

int quantity;double subtotal, tax, totalCost, unitPrice;

Scanner scan = new Scanner (System.in);

continued

Page 72: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

23

continued

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print ("Enter the quantity: ");System.out.print ( Enter the quantity: );quantity = scan.nextInt();

System.out.print ("Enter the unit price: ");unitPrice = scan.nextDouble();

subtotal = quantity * unitPrice;tax = subtotal * TAX_RATE;totalCost = subtotal + tax;

// Print output with appropriate formattingSystem out println ("Subtotal: " + fmt1 format(subtotal));

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Subtotal: " + fmt1.format(subtotal));System.out.println ("Tax: " + fmt1.format(tax) + " at "

+ fmt2.format(TAX_RATE));System.out.println ("Total: " + fmt1.format(totalCost));

}}

continued

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print ("Enter the quantity: ");

Sample RunEnter the quantity: 5Enter the unit price: 3.87Subtotal: $19.35Tax: $1.16 at 6%System.out.print ( Enter the quantity: );

quantity = scan.nextInt();

System.out.print ("Enter the unit price: ");unitPrice = scan.nextDouble();

subtotal = quantity * unitPrice;tax = subtotal * TAX_RATE;totalCost = subtotal + tax;

// Print output with appropriate formattingSystem out println ("Subtotal: " + fmt1 format(subtotal));

Total: $20.51

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Subtotal: " + fmt1.format(subtotal));System.out.println ("Tax: " + fmt1.format(tax) + " at "

+ fmt2.format(TAX_RATE));System.out.println ("Total: " + fmt1.format(totalCost));

}}

Page 73: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

24

Formatting Output

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

• For example, you can specify that the number should be truncated to three decimal places

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

• See CircleStats.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// CircleStats.java Author: Lewis/Loftus//// Demonstrates the formatting of decimal values using the// DecimalFormat class.//********************************************************************

i j ilimport java.util.Scanner;import java.text.DecimalFormat;

public class CircleStats{

//-----------------------------------------------------------------// Calculates the area and circumference of a circle given its// radius.//-----------------------------------------------------------------public static void main (String[] args){

Copyright © 2012 Pearson Education, Inc.

int radius;double area, circumference;

Scanner scan = new Scanner (System.in);

continued

Page 74: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

25

continued

System.out.print ("Enter the circle's radius: ");radius = scan.nextInt();

area = Math PI * Math pow(radius 2);area = Math.PI * Math.pow(radius, 2);circumference = 2 * Math.PI * radius;

// Round the output to three decimal placesDecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The circle's area: " + fmt.format(area));System.out.println ("The circle's circumference: "

+ fmt.format(circumference));}

}

Copyright © 2012 Pearson Education, Inc.

continued

System.out.print ("Enter the circle's radius: ");radius = scan.nextInt();

area = Math PI * Math pow(radius 2);

Sample RunEnter the circle's radius: 5The circle's area: 78.54The circle's circumference: 31.416

area = Math.PI * Math.pow(radius, 2);circumference = 2 * Math.PI * radius;

// Round the output to three decimal placesDecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The circle's area: " + fmt.format(area));System.out.println ("The circle's circumference: "

+ fmt.format(circumference));}

}

Copyright © 2012 Pearson Education, Inc.

Page 75: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

26

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Enumerated Types• Java allows you to define an enumerated type,

which can then be used to declare variables

• An enumerated type declaration lists all possible values for a variable of that type

• The values are identifiers of your own choosing

• The following declaration creates an enumerated type called Seasontype called Season

enum Season {winter, spring, summer, fall};

• Any number of values can be listed

Copyright © 2012 Pearson Education, Inc.

Page 76: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

27

Enumerated Types• Once a type is defined, a variable of that type can

be declared:Season time;Season time;

• And it can be assigned a value:

time = Season.fall;

• The values are referenced through the name of the typeyp

• Enumerated types are type-safe – you cannot assign any value other than those listed

Copyright © 2012 Pearson Education, Inc.

Ordinal Values

• Internally, each value of an enumerated type is stored as an integer, called its ordinal value

• The first value in an enumerated type has an ordinal value of zero, the second one, and so on

• However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal valueordinal value

Copyright © 2012 Pearson Education, Inc.

Page 77: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

28

Enumerated Types

• The declaration of an enumerated type is a special type of class, and each variable of that type is an objectobject

• The ordinal method returns the ordinal value of the object

• The name method returns the name of the identifier corresponding to the object's value

• See IceCream.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// IceCream.java Author: Lewis/Loftus//// Demonstrates the use of enumerated types.//********************************************************************

public class IceCream{

Fl { ill h l t t b f d Ri l ffenum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee,rockyRoad, mintChocolateChip, cookieDough}

//-----------------------------------------------------------------// Creates and uses variables of the Flavor type.//-----------------------------------------------------------------public static void main (String[] args){

Flavor cone1, cone2, cone3;

cone1 = Flavor.rockyRoad;

Copyright © 2012 Pearson Education, Inc.

cone2 = Flavor.chocolate;

System.out.println ("cone1 value: " + cone1);System.out.println ("cone1 ordinal: " + cone1.ordinal());System.out.println ("cone1 name: " + cone1.name());

continued

Page 78: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

29

continued

System.out.println ();System.out.println ("cone2 value: " + cone2);System out println ("cone2 ordinal: " + cone2 ordinal());System.out.println ("cone2 ordinal: " + cone2.ordinal());System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println ();System.out.println ("cone3 value: " + cone3);System.out.println ("cone3 ordinal: " + cone3.ordinal());System.out.println ("cone3 name: " + cone3.name());

}}

Copyright © 2012 Pearson Education, Inc.

continued

System.out.println ();System.out.println ("cone2 value: " + cone2);System out println ("cone2 ordinal: " + cone2 ordinal());

Outputcone1 value: rockyRoadcone1 ordinal: 5cone1 name: rockyRoad

System.out.println ("cone2 ordinal: " + cone2.ordinal());System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println ();System.out.println ("cone3 value: " + cone3);System.out.println ("cone3 ordinal: " + cone3.ordinal());System.out.println ("cone3 name: " + cone3.name());

}}

cone2 value: chocolatecone2 ordinal: 1cone2 name: chocolatecone3 value: rockyRoadcone3 ordinal: 5cone3 name: rockyRoad

Copyright © 2012 Pearson Education, Inc.

Page 79: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

30

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Wrapper Classes• The java.lang package contains wrapper

classes that correspond to each primitive type:

Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Page 80: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

31

Wrapper Classes• The following declaration creates an Integer

object which represents the integer 40 as an object

I t I t (40)Integer age = new Integer(40);

• An object of a wrapper class can be used in any situation where a primitive value will not suffice

• For example, some objects serve as containers of other objectsother objects

• Primitive values could not be stored in such containers, but wrapper objects could be

Copyright © 2012 Pearson Education, Inc.

Wrapper Classes• Wrapper classes also contain static methods that

help manage the associated type

For example the I t class contains a• For example, the Integer class contains a method to convert an integer stored in a Stringto an int value:

num = Integer.parseInt(str);

• They often contain useful constants as welly

• For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values

Copyright © 2012 Pearson Education, Inc.

Page 81: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

32

Autoboxing• Autoboxing is the automatic conversion of a

primitive value to a corresponding wrapper object:

I t bjInteger obj;int num = 42;obj = num;

• The assignment creates the appropriate Integerobject

• The reverse conversion (called unboxing) also occurs automatically as needed

Copyright © 2012 Pearson Education, Inc.

Quick CheckAre the following assignments valid? Explain.

Double value = 15.75;Double value 15.75;

Character ch = new Character('T');

char myChar = ch;

Copyright © 2012 Pearson Education, Inc.

Page 82: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

33

Quick CheckAre the following assignments valid? Explain.

Double value = 15.75;Double value 15.75;

Character ch = new Character('T');

char myChar = ch;

Yes. The double literal is autoboxed into a Double object.

Copyright © 2012 Pearson Education, Inc.

Yes, the char in the object is unboxed before the assignment.

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Page 83: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

34

Graphical Applications• Except for the applets seen in Chapter 2, the

example programs we've explored thus far have been text-based

• They are called command-line applications, which interact with the user using simple text prompts

• Let's examine some Java applications that have graphical components

• These components will serve as a foundation to programs that have true graphical user interfaces (GUIs)

Copyright © 2012 Pearson Education, Inc.

GUI Components• A GUI component is an object that represents a

screen element such as a button or a text field

GUI l t d l d fi d i il i th• GUI-related classes are defined primarily in the java.awt and the javax.swing packages

• The Abstract Windowing Toolkit (AWT) was the original Java GUI package

• The Swing package provides additional and moreThe Swing package provides additional and more versatile components

• Both packages are needed to create a Java GUI-based program

Copyright © 2012 Pearson Education, Inc.

Page 84: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

35

GUI Containers• A GUI container is a component that is used to hold

and organize other components

A f i t i di l d t• A frame is a container displayed as a separate window with a title bar

• It can be repositioned and resized on the screen as needed

• A panel is a container that cannot be displayed onA panel is a container that cannot be displayed on its own but is used to organize other components

• A panel must be added to another container (like a frame or another panel) to be displayed

Copyright © 2012 Pearson Education, Inc.

GUI Containers• A GUI container can be classified as either

heavyweight or lightweight

• A heavyweight container is one that is managed by the underlying operating system

• A lightweight container is managed by the Java program itself

• Occasionally this distinction is important• Occasionally this distinction is important

• A frame is a heavyweight container and a panel is a lightweight container

Copyright © 2012 Pearson Education, Inc.

Page 85: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

36

Labels• A label is a GUI component that displays a line of

text and/or an image

• Labels are usually used to display information or identify other components in the interface

• Let's look at a program that organizes two labels in a panel and displays that panel in a frame

• This program is not interactive but the frame can• This program is not interactive, but the frame can be repositioned and resized

• See Authority.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Authority.java Author: Lewis/Loftus//// Demonstrates the use of frames, panels, and labels.//********************************************************************

import java.awt.*;import javax.swing.*;

public class Authority{

//-----------------------------------------------------------------// Displays some words of wisdom.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Authority");

Copyright © 2012 Pearson Education, Inc.

frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

JPanel primary = new JPanel();primary.setBackground (Color.yellow);primary.setPreferredSize (new Dimension(250, 75));

continued

Page 86: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

37

continued

JLabel label1 = new JLabel ("Question authority,");JLabel label2 = new JLabel ("but raise your hand first.");

primary.add (label1);primary.add (label2);

frame.getContentPane().add(primary);frame.pack();frame.setVisible(true);

}}

Copyright © 2012 Pearson Education, Inc.

continued

JLabel label1 = new JLabel ("Question authority,");JLabel label2 = new JLabel ("but raise your hand first.");

primary.add (label1);primary.add (label2);

frame.getContentPane().add(primary);frame.pack();frame.setVisible(true);

}}

Copyright © 2012 Pearson Education, Inc.

Page 87: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

38

Nested Panels• Containers that contain other components make up

the containment hierarchy of an interface

• This hierarchy can be as intricate as needed to create the visual effect desired

• The following example nests two panels inside a third panel – note the effect this has as the frame is resizedresized

• See NestedPanels.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// NestedPanels.java Author: Lewis/Loftus//// Demonstrates a basic componenet hierarchy.//********************************************************************

import java.awt.*;import javax.swing.*;

public class NestedPanels{

//-----------------------------------------------------------------// Presents two colored panels nested within a third.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Nested Panels");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

// Set p first s bpanel

Copyright © 2012 Pearson Education, Inc.

// Set up first subpanelJPanel subPanel1 = new JPanel();subPanel1.setPreferredSize (new Dimension(150, 100));subPanel1.setBackground (Color.green);JLabel label1 = new JLabel ("One");subPanel1.add (label1);

continued

Page 88: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

39

continued

// Set up second subpanelJPanel subPanel2 = new JPanel();subPanel2.setPreferredSize (new Dimension(150, 100));subPanel2.setBackground (Color.red);JLabel label2 = new JLabel ("Two");subPanel2.add (label2);

// Set up primary panelJPanel primary = new JPanel();primary.setBackground (Color.blue);primary.add (subPanel1);primary.add (subPanel2);

frame.getContentPane().add(primary);

Copyright © 2012 Pearson Education, Inc.

g () (p y);frame.pack();frame.setVisible(true);

}}

continued

// Set up second subpanelJPanel subPanel2 = new JPanel();subPanel2.setPreferredSize (new Dimension(150, 100));subPanel2.setBackground (Color.red);JLabel label2 = new JLabel ("Two");subPanel2.add (label2);

// Set up primary panelJPanel primary = new JPanel();primary.setBackground (Color.blue);primary.add (subPanel1);primary.add (subPanel2);

frame.getContentPane().add(primary);

Copyright © 2012 Pearson Education, Inc.

g () (p y);frame.pack();frame.setVisible(true);

}}

Page 89: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

40

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Images• Images can be displayed in a Java program in

various ways

As we've seen a JL b l object can be used to• As we've seen, a JLabel object can be used to display a line of text

• It can also be used to display an image

• That is, a label can be composed of text, an image, or both at the same timeor both at the same time

Copyright © 2012 Pearson Education, Inc.

Page 90: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

41

Images• The ImageIcon class is used to represent the

image that is stored in a label

• If text is also included, the position of the text relative to the image can be set explicitly

• The alignment of the text and image within the label can be set as well

• See LabelDemo java• See LabelDemo.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// LabelDemo.java Author: Lewis/Loftus//// Demonstrates the use of image icons in labels.//********************************************************************

import java.awt.*;import javax swing *;import javax.swing. ;

public class LabelDemo{

//-----------------------------------------------------------------// Creates and displays the primary application frame.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Label Demo");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

Copyright © 2012 Pearson Education, Inc.

ImageIcon icon = new ImageIcon ("devil.gif");

JLabel label1, label2, label3;

label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);

continued

Page 91: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

42

continued

label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);label2.setHorizontalTextPosition (SwingConstants.LEFT);label2.setVerticalTextPosition (SwingConstants.BOTTOM);

label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER);label3.setHorizontalTextPosition (SwingConstants.CENTER);label3.setVerticalTextPosition (SwingConstants.BOTTOM);

JPanel panel = new JPanel();panel.setBackground (Color.cyan);panel.setPreferredSize (new Dimension (200, 250));panel.add (label1);panel.add (label2);panel.add (label3);

Copyright © 2012 Pearson Education, Inc.

frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);

}}

continued

label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);label2.setHorizontalTextPosition (SwingConstants.LEFT);label2.setVerticalTextPosition (SwingConstants.BOTTOM);

label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER);label3.setHorizontalTextPosition (SwingConstants.CENTER);label3.setVerticalTextPosition (SwingConstants.BOTTOM);

JPanel panel = new JPanel();panel.setBackground (Color.cyan);panel.setPreferredSize (new Dimension (200, 250));panel.add (label1);panel.add (label2);panel.add (label3);

Copyright © 2012 Pearson Education, Inc.

frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);

}}

Page 92: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

43

Summary• Chapter 3 focused on:

– object creation and object references– the String class and its methods– the String class and its methods– the Java standard class library– the Random and Math classes– formatting output– enumerated types– wrapper classes– graphical components and containers– labels and images

Copyright © 2012 Pearson Education, Inc.

Page 93: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

1

Chapter 3Using Classes and Objects

Java Software SolutionsFoundations of Program Design

Seventh Edition

Copyright © 2012 Pearson Education, Inc.

John LewisWilliam Loftus

Using Classes and Objects• We can create more interesting programs using predefined

classes and related objects

Ch t 3 f• Chapter 3 focuses on:

– object creation and object references– the String class and its methods

– the Java API class library– the Random and Math classes

– formatting output

– enumerated types

– wrapper classes

– graphical components and containers

– labels and images

Copyright © 2012 Pearson Education, Inc.

Page 94: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

2

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Creating Objects• A variable holds either a primitive value or a

reference to an object

A l b d t t d l• A class name can be used as a type to declare an object reference variable

String title;

• No object is created with this declaration

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

• The object itself must be created separately

Copyright © 2012 Pearson Education, Inc.

Page 95: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

3

Creating Objects

• Generally, we use the new operator to create an object

• Creating an object is called instantiation

• An object is an instance of a particular class

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

This calls the String constructor, which isa special method that sets up the object

Copyright © 2012 Pearson Education, Inc.

Invoking Methods

• We've seen that once an object has been instantiated, we can use the dot operator to invoke its methodsits methods

numChars = title.length()

• A method may return a value, which can be used in an assignment or expression

• A method invocation can be thought of as asking an object to perform a service

Copyright © 2012 Pearson Education, Inc.

Page 96: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

4

References• Note that a primitive variable contains the value

itself, but an object variable contains the address of the objectj

• An object reference can be thought of as a pointer to the location of the object

• Rather than dealing with arbitrary addresses, we often depict a reference graphically

"Steve Jobs"name1

num1 38

Copyright © 2012 Pearson Education, Inc.

Assignment Revisited• The act of assignment takes a copy of a value and

stores it in a variable

• For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Copyright © 2012 Pearson Education, Inc.

Page 97: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

5

Reference Assignment

• For object references, assignment copies the address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

Copyright © 2012 Pearson Education, Inc.

Aliases• Two or more references that refer to the same

object are called aliases of each other

• That creates an interesting situation: one object can be accessed using multiple reference variables

• Aliases can be useful, but should be managed carefully

• Changing an object through one reference• Changing an object through one reference changes it for all of its aliases, because there is really only one object

Copyright © 2012 Pearson Education, Inc.

Page 98: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

6

Garbage Collection• When an object no longer has any valid references

to it, it can no longer be accessed by the program

• The object is useless, and therefore is called garbage

• Java performs automatic garbage collectionperiodically, returning an object's memory to the system for future use

• In other languages, the programmer is responsible for performing garbage collection

Copyright © 2012 Pearson Education, Inc.

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Page 99: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

7

The String Class

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

title = "Java Software Solutions";

• This is special syntax that works only for strings

• Each string literal (enclosed in double quotes) t bj trepresents a String object

Copyright © 2012 Pearson Education, Inc.

String Methods

• Once a String object has been created, neither its value nor its length can be changed

• Therefore we say that an object of the Stringclass is immutable

• However, several methods of the String class return new String objects that are modified versions of the original

Copyright © 2012 Pearson Education, Inc.

Page 100: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

8

String Indexes• It is occasionally helpful to refer to a particular

character within a string

• This can be done by specifying the character's numeric index

• The indexes begin at zero in each string

• In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4index 0 and the o is at index 4

• See StringMutation.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// StringMutation.java Author: Lewis/Loftus//// Demonstrates the use of the String class and its methods.//********************************************************************

public class StringMutation{

////-----------------------------------------------------------------// Prints a string and various mutations of it.//-----------------------------------------------------------------public static void main (String[] args){

String phrase = "Change is inevitable";String mutation1, mutation2, mutation3, mutation4;

System.out.println ("Original string: \"" + phrase + "\"");System.out.println ("Length of string: " + phrase.length());

Copyright © 2012 Pearson Education, Inc.

mutation1 = phrase.concat (", except from vending machines.");mutation2 = mutation1.toUpperCase();mutation3 = mutation2.replace ('E', 'X');mutation4 = mutation3.substring (3, 30);

continued

Page 101: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

9

continued

// Print each mutated string// Print each mutated stringSystem.out.println ("Mutation #1: " + mutation1);System.out.println ("Mutation #2: " + mutation2);System.out.println ("Mutation #3: " + mutation3);System.out.println ("Mutation #4: " + mutation4);

System.out.println ("Mutated length: " + mutation4.length());}

}

Copyright © 2012 Pearson Education, Inc.

continued

// Print each mutated string

OutputOriginal string: "Change is inevitable"Length of string: 20Mutation #1: Change is inevitable, except from vending machines.Mutation #2: CHANGE IS INEVITABLE EXCEPT FROM VENDING MACHINES// Print each mutated string

System.out.println ("Mutation #1: " + mutation1);System.out.println ("Mutation #2: " + mutation2);System.out.println ("Mutation #3: " + mutation3);System.out.println ("Mutation #4: " + mutation4);

System.out.println ("Mutated length: " + mutation4.length());}

}

Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES.Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS.Mutation #4: NGX IS INXVITABLX, XXCXPT FMutated length: 27

Copyright © 2012 Pearson Education, Inc.

Page 102: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

10

Quick Check

What output is produced by the following?

String str = "Space, the final frontier.";String str Space, the final frontier. ;System.out.println (str.length());System.out.println (str.substring(7));System.out.println (str.toUpperCase());System.out.println (str.length());

Copyright © 2012 Pearson Education, Inc.

Quick Check

What output is produced by the following?

String str = "Space, the final frontier.";String str Space, the final frontier. ;System.out.println (str.length());System.out.println (str.substring(7));System.out.println (str.toUpperCase());System.out.println (str.length());

26

Copyright © 2012 Pearson Education, Inc.

26the final frontier.SPACE, THE FINAL FRONTIER.26

Page 103: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

11

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Class Libraries• A class library is a collection of classes that we can

use when developing programs

• The Java standard class library is part of any Java development environment

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

• Various classes we've already used (System , Scanner, String) are part of the Java standard class library

Copyright © 2012 Pearson Education, Inc.

Page 104: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

12

The Java API• The Java class library is sometimes referred to as

the Java API

• API stands for Application Programming Interface

• Clusters of related classes are sometimes referred to as specific APIs:

– The Swing API

– The Database API

Copyright © 2012 Pearson Education, Inc.

The Java API• Get comfortable navigating the online Java API

documentation

Copyright © 2012 Pearson Education, Inc.

Page 105: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

13

Packages• For purposes of accessing them, classes in the

Java API are organized into packages

Th ft l ith ifi API• These often overlap with specific APIs

• Examples:

Package

java.langjava.applet

Purpose

General supportCreating applets for the webj pp

java.awtjavax.swingjava.netjava.utiljavax.xml.parsers

g ppGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilitiesXML document processing

Copyright © 2012 Pearson Education, Inc.

The import Declaration• When you want to use a class from a package, you

could use its fully qualified name

j ijava.util.Scanner

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

import java.util.Scanner;

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

import java.util.*;

Copyright © 2012 Pearson Education, Inc.

Page 106: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

14

The import Declaration• All classes of the java.lang package are

imported automatically into all programs

• It's as if all programs contain the following line:

import java.lang.*;

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

• The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported

Copyright © 2012 Pearson Education, Inc.

The Random Class

• The Random class is part of the java.utilpackage

• It provides methods that generate pseudorandom numbers

• A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random valuesg y

• See RandomNumbers.java

Copyright © 2012 Pearson Education, Inc.

Page 107: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

15

//********************************************************************// RandomNumbers.java Author: Lewis/Loftus//// Demonstrates the creation of pseudo-random numbers using the// Random class.//********************************************************************

import java.util.Random;

public class RandomNumbers{

//-----------------------------------------------------------------// Generates random numbers in various ranges.//-----------------------------------------------------------------public static void main (String[] args){

Random generator = new Random();int num1;float num2;

Copyright © 2012 Pearson Education, Inc.

num1 = generator.nextInt();System.out.println ("A random integer: " + num1);

num1 = generator.nextInt(10);System.out.println ("From 0 to 9: " + num1);

continued

continued

num1 = generator.nextInt(10) + 1;System.out.println ("From 1 to 10: " + num1);

num1 = generator nextInt(15) + 20;num1 = generator.nextInt(15) + 20;System.out.println ("From 20 to 34: " + num1);

num1 = generator.nextInt(20) - 10;System.out.println ("From -10 to 9: " + num1);

num2 = generator.nextFloat();System.out.println ("A random float (between 0-1): " + num2);

num2 = generator.nextFloat() * 6; // 0.0 to 5.999999num1 = (int)num2 + 1;S t t i tl ("F 1 t 6 " + 1)

Copyright © 2012 Pearson Education, Inc.

System.out.println ("From 1 to 6: " + num1);}

}

Page 108: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

16

continued

num1 = generator.nextInt(10) + 1;System.out.println ("From 1 to 10: " + num1);

num1 = generator nextInt(15) + 20;

Sample RunA random integer: 672981683From 0 to 9: 0From 1 to 10: 3From 20 to 34: 30num1 = generator.nextInt(15) + 20;

System.out.println ("From 20 to 34: " + num1);

num1 = generator.nextInt(20) - 10;System.out.println ("From -10 to 9: " + num1);

num2 = generator.nextFloat();System.out.println ("A random float (between 0-1): " + num2);

num2 = generator.nextFloat() * 6; // 0.0 to 5.999999num1 = (int)num2 + 1;S t t i tl ("F 1 t 6 " + 1)

From 20 to 34: 30From -10 to 9: -4A random float (between 0-1): 0.18538326From 1 to 6: 3

Copyright © 2012 Pearson Education, Inc.

System.out.println ("From 1 to 6: " + num1);}

}

Quick CheckGiven a Random object named gen, what range of values are produced by the following expressions?

gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(100) + 10

gen.nextInt(50) + 100

Copyright © 2012 Pearson Education, Inc.

g ( )

gen.nextInt(10) – 5

gen.nextInt(22) + 12

Page 109: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

17

Quick CheckGiven a Random object named gen, what range of values are produced by the following expressions?

gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(100) + 10

gen.nextInt(50) + 100

Range0 to 24

1 to 6

10 to 109

100 to 149

Copyright © 2012 Pearson Education, Inc.

g ( )

gen.nextInt(10) – 5

gen.nextInt(22) + 12

-5 to 4

12 to 33

Quick CheckWrite an expression that produces a random integer in the following ranges:

Range0 to 12

1 to 20

15 to 20

10 to 0

Copyright © 2012 Pearson Education, Inc.

-10 to 0

Page 110: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

18

Quick CheckWrite an expression that produces a random integer in the following ranges:

gen.nextInt(13)

gen.nextInt(20) + 1

gen.nextInt(6) + 15

gen nextInt(11) 10

Range0 to 12

1 to 20

15 to 20

10 to 0

Copyright © 2012 Pearson Education, Inc.

gen.nextInt(11) – 10-10 to 0

The Math Class• The Math class is part of the java.lang package

• The Math class contains methods that perform various mathematical functions

• These include:– absolute value

– square root

exponentiation– exponentiation

– trigonometric functions

Copyright © 2012 Pearson Education, Inc.

Page 111: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

19

The Math Class• The methods of the Math class are static methods

(also called class methods)

• Static methods are invoked through the class name – no object of the Math class is needed

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

• We discuss static methods further in Chapter 7

• See Quadratic.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Quadratic.java Author: Lewis/Loftus//// Demonstrates the use of the Math class to perform a calculation// based on user input.//********************************************************************

import java.util.Scanner;

public class Quadratic{

//-----------------------------------------------------------------// Determines the roots of a quadratic equation.//-----------------------------------------------------------------public static void main (String[] args){

int a, b, c; // ax^2 + bx + cdouble discriminant root1 root2;

Copyright © 2012 Pearson Education, Inc.

double discriminant, root1, root2;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter the coefficient of x squared: ");a = scan.nextInt();

continued

Page 112: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

20

continued

System.out.print ("Enter the coefficient of x: ");b = scan.nextInt();

System.out.print ("Enter the constant: ");c = scan.nextInt();()

// Use the quadratic formula to compute the roots.// Assumes a positive discriminant.

discriminant = Math.pow(b, 2) - (4 * a * c);root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);System.out.println ("Root #2: " + root2);

}

Copyright © 2012 Pearson Education, Inc.

}}

continued

System.out.print ("Enter the coefficient of x: ");b = scan.nextInt();

System.out.print ("Enter the constant: ");c = scan.nextInt();

Sample RunEnter the coefficient of x squared: 3Enter the coefficient of x: 8Enter the constant: 4Root #1: -0.6666666666666666Root #2: -2.0()

// Use the quadratic formula to compute the roots.// Assumes a positive discriminant.

discriminant = Math.pow(b, 2) - (4 * a * c);root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);System.out.println ("Root #2: " + root2);

}

#

Copyright © 2012 Pearson Education, Inc.

}}

Page 113: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

21

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Formatting Output• It is often necessary to format output values in

certain ways so that they can be presented properly

• The Java standard class library contains classes that provide formatting capabilities

• The NumberFormat class allows you to format values as currency or percentages

• The DecimalFormat class allows you to format• The DecimalFormat class allows you to format values based on a pattern

• Both are part of the java.text package

Copyright © 2012 Pearson Education, Inc.

Page 114: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

22

Formatting Output

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

getCurrencyInstance()

getPercentInstance()

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

• See Purchase.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Purchase.java Author: Lewis/Loftus//// Demonstrates the use of the NumberFormat class to format output.//********************************************************************

import java.util.Scanner;p jimport java.text.NumberFormat;

public class Purchase{

//-----------------------------------------------------------------// Calculates the final price of a purchased item using values// entered by the user.//-----------------------------------------------------------------public static void main (String[] args){

final double TAX RATE = 0 06; // 6% sales tax

Copyright © 2012 Pearson Education, Inc.

final double TAX_RATE = 0.06; // 6% sales tax

int quantity;double subtotal, tax, totalCost, unitPrice;

Scanner scan = new Scanner (System.in);

continued

Page 115: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

23

continued

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print ("Enter the quantity: ");System.out.print ( Enter the quantity: );quantity = scan.nextInt();

System.out.print ("Enter the unit price: ");unitPrice = scan.nextDouble();

subtotal = quantity * unitPrice;tax = subtotal * TAX_RATE;totalCost = subtotal + tax;

// Print output with appropriate formattingSystem out println ("Subtotal: " + fmt1 format(subtotal));

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Subtotal: " + fmt1.format(subtotal));System.out.println ("Tax: " + fmt1.format(tax) + " at "

+ fmt2.format(TAX_RATE));System.out.println ("Total: " + fmt1.format(totalCost));

}}

continued

NumberFormat fmt1 = NumberFormat.getCurrencyInstance();NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print ("Enter the quantity: ");

Sample RunEnter the quantity: 5Enter the unit price: 3.87Subtotal: $19.35Tax: $1.16 at 6%System.out.print ( Enter the quantity: );

quantity = scan.nextInt();

System.out.print ("Enter the unit price: ");unitPrice = scan.nextDouble();

subtotal = quantity * unitPrice;tax = subtotal * TAX_RATE;totalCost = subtotal + tax;

// Print output with appropriate formattingSystem out println ("Subtotal: " + fmt1 format(subtotal));

Total: $20.51

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Subtotal: " + fmt1.format(subtotal));System.out.println ("Tax: " + fmt1.format(tax) + " at "

+ fmt2.format(TAX_RATE));System.out.println ("Total: " + fmt1.format(totalCost));

}}

Page 116: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

24

Formatting Output

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

• For example, you can specify that the number should be truncated to three decimal places

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

• See CircleStats.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// CircleStats.java Author: Lewis/Loftus//// Demonstrates the formatting of decimal values using the// DecimalFormat class.//********************************************************************

i j ilimport java.util.Scanner;import java.text.DecimalFormat;

public class CircleStats{

//-----------------------------------------------------------------// Calculates the area and circumference of a circle given its// radius.//-----------------------------------------------------------------public static void main (String[] args){

Copyright © 2012 Pearson Education, Inc.

int radius;double area, circumference;

Scanner scan = new Scanner (System.in);

continued

Page 117: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

25

continued

System.out.print ("Enter the circle's radius: ");radius = scan.nextInt();

area = Math PI * Math pow(radius 2);area = Math.PI * Math.pow(radius, 2);circumference = 2 * Math.PI * radius;

// Round the output to three decimal placesDecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The circle's area: " + fmt.format(area));System.out.println ("The circle's circumference: "

+ fmt.format(circumference));}

}

Copyright © 2012 Pearson Education, Inc.

continued

System.out.print ("Enter the circle's radius: ");radius = scan.nextInt();

area = Math PI * Math pow(radius 2);

Sample RunEnter the circle's radius: 5The circle's area: 78.54The circle's circumference: 31.416

area = Math.PI * Math.pow(radius, 2);circumference = 2 * Math.PI * radius;

// Round the output to three decimal placesDecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The circle's area: " + fmt.format(area));System.out.println ("The circle's circumference: "

+ fmt.format(circumference));}

}

Copyright © 2012 Pearson Education, Inc.

Page 118: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

26

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Enumerated Types• Java allows you to define an enumerated type,

which can then be used to declare variables

• An enumerated type declaration lists all possible values for a variable of that type

• The values are identifiers of your own choosing

• The following declaration creates an enumerated type called Seasontype called Season

enum Season {winter, spring, summer, fall};

• Any number of values can be listed

Copyright © 2012 Pearson Education, Inc.

Page 119: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

27

Enumerated Types• Once a type is defined, a variable of that type can

be declared:Season time;Season time;

• And it can be assigned a value:

time = Season.fall;

• The values are referenced through the name of the typeyp

• Enumerated types are type-safe – you cannot assign any value other than those listed

Copyright © 2012 Pearson Education, Inc.

Ordinal Values

• Internally, each value of an enumerated type is stored as an integer, called its ordinal value

• The first value in an enumerated type has an ordinal value of zero, the second one, and so on

• However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal valueordinal value

Copyright © 2012 Pearson Education, Inc.

Page 120: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

28

Enumerated Types

• The declaration of an enumerated type is a special type of class, and each variable of that type is an objectobject

• The ordinal method returns the ordinal value of the object

• The name method returns the name of the identifier corresponding to the object's value

• See IceCream.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// IceCream.java Author: Lewis/Loftus//// Demonstrates the use of enumerated types.//********************************************************************

public class IceCream{

Fl { ill h l t t b f d Ri l ffenum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee,rockyRoad, mintChocolateChip, cookieDough}

//-----------------------------------------------------------------// Creates and uses variables of the Flavor type.//-----------------------------------------------------------------public static void main (String[] args){

Flavor cone1, cone2, cone3;

cone1 = Flavor.rockyRoad;

Copyright © 2012 Pearson Education, Inc.

cone2 = Flavor.chocolate;

System.out.println ("cone1 value: " + cone1);System.out.println ("cone1 ordinal: " + cone1.ordinal());System.out.println ("cone1 name: " + cone1.name());

continued

Page 121: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

29

continued

System.out.println ();System.out.println ("cone2 value: " + cone2);System out println ("cone2 ordinal: " + cone2 ordinal());System.out.println ("cone2 ordinal: " + cone2.ordinal());System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println ();System.out.println ("cone3 value: " + cone3);System.out.println ("cone3 ordinal: " + cone3.ordinal());System.out.println ("cone3 name: " + cone3.name());

}}

Copyright © 2012 Pearson Education, Inc.

continued

System.out.println ();System.out.println ("cone2 value: " + cone2);System out println ("cone2 ordinal: " + cone2 ordinal());

Outputcone1 value: rockyRoadcone1 ordinal: 5cone1 name: rockyRoad

System.out.println ("cone2 ordinal: " + cone2.ordinal());System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println ();System.out.println ("cone3 value: " + cone3);System.out.println ("cone3 ordinal: " + cone3.ordinal());System.out.println ("cone3 name: " + cone3.name());

}}

cone2 value: chocolatecone2 ordinal: 1cone2 name: chocolatecone3 value: rockyRoadcone3 ordinal: 5cone3 name: rockyRoad

Copyright © 2012 Pearson Education, Inc.

Page 122: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

30

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Wrapper Classes• The java.lang package contains wrapper

classes that correspond to each primitive type:

Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Page 123: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

31

Wrapper Classes• The following declaration creates an Integer

object which represents the integer 40 as an object

I t I t (40)Integer age = new Integer(40);

• An object of a wrapper class can be used in any situation where a primitive value will not suffice

• For example, some objects serve as containers of other objectsother objects

• Primitive values could not be stored in such containers, but wrapper objects could be

Copyright © 2012 Pearson Education, Inc.

Wrapper Classes• Wrapper classes also contain static methods that

help manage the associated type

For example the I t class contains a• For example, the Integer class contains a method to convert an integer stored in a Stringto an int value:

num = Integer.parseInt(str);

• They often contain useful constants as welly

• For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values

Copyright © 2012 Pearson Education, Inc.

Page 124: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

32

Autoboxing• Autoboxing is the automatic conversion of a

primitive value to a corresponding wrapper object:

I t bjInteger obj;int num = 42;obj = num;

• The assignment creates the appropriate Integerobject

• The reverse conversion (called unboxing) also occurs automatically as needed

Copyright © 2012 Pearson Education, Inc.

Quick CheckAre the following assignments valid? Explain.

Double value = 15.75;Double value 15.75;

Character ch = new Character('T');

char myChar = ch;

Copyright © 2012 Pearson Education, Inc.

Page 125: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

33

Quick CheckAre the following assignments valid? Explain.

Double value = 15.75;Double value 15.75;

Character ch = new Character('T');

char myChar = ch;

Yes. The double literal is autoboxed into a Double object.

Copyright © 2012 Pearson Education, Inc.

Yes, the char in the object is unboxed before the assignment.

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Page 126: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

34

Graphical Applications• Except for the applets seen in Chapter 2, the

example programs we've explored thus far have been text-based

• They are called command-line applications, which interact with the user using simple text prompts

• Let's examine some Java applications that have graphical components

• These components will serve as a foundation to programs that have true graphical user interfaces (GUIs)

Copyright © 2012 Pearson Education, Inc.

GUI Components• A GUI component is an object that represents a

screen element such as a button or a text field

GUI l t d l d fi d i il i th• GUI-related classes are defined primarily in the java.awt and the javax.swing packages

• The Abstract Windowing Toolkit (AWT) was the original Java GUI package

• The Swing package provides additional and moreThe Swing package provides additional and more versatile components

• Both packages are needed to create a Java GUI-based program

Copyright © 2012 Pearson Education, Inc.

Page 127: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

35

GUI Containers• A GUI container is a component that is used to hold

and organize other components

A f i t i di l d t• A frame is a container displayed as a separate window with a title bar

• It can be repositioned and resized on the screen as needed

• A panel is a container that cannot be displayed onA panel is a container that cannot be displayed on its own but is used to organize other components

• A panel must be added to another container (like a frame or another panel) to be displayed

Copyright © 2012 Pearson Education, Inc.

GUI Containers• A GUI container can be classified as either

heavyweight or lightweight

• A heavyweight container is one that is managed by the underlying operating system

• A lightweight container is managed by the Java program itself

• Occasionally this distinction is important• Occasionally this distinction is important

• A frame is a heavyweight container and a panel is a lightweight container

Copyright © 2012 Pearson Education, Inc.

Page 128: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

36

Labels• A label is a GUI component that displays a line of

text and/or an image

• Labels are usually used to display information or identify other components in the interface

• Let's look at a program that organizes two labels in a panel and displays that panel in a frame

• This program is not interactive but the frame can• This program is not interactive, but the frame can be repositioned and resized

• See Authority.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Authority.java Author: Lewis/Loftus//// Demonstrates the use of frames, panels, and labels.//********************************************************************

import java.awt.*;import javax.swing.*;

public class Authority{

//-----------------------------------------------------------------// Displays some words of wisdom.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Authority");

Copyright © 2012 Pearson Education, Inc.

frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

JPanel primary = new JPanel();primary.setBackground (Color.yellow);primary.setPreferredSize (new Dimension(250, 75));

continued

Page 129: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

37

continued

JLabel label1 = new JLabel ("Question authority,");JLabel label2 = new JLabel ("but raise your hand first.");

primary.add (label1);primary.add (label2);

frame.getContentPane().add(primary);frame.pack();frame.setVisible(true);

}}

Copyright © 2012 Pearson Education, Inc.

continued

JLabel label1 = new JLabel ("Question authority,");JLabel label2 = new JLabel ("but raise your hand first.");

primary.add (label1);primary.add (label2);

frame.getContentPane().add(primary);frame.pack();frame.setVisible(true);

}}

Copyright © 2012 Pearson Education, Inc.

Page 130: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

38

Nested Panels• Containers that contain other components make up

the containment hierarchy of an interface

• This hierarchy can be as intricate as needed to create the visual effect desired

• The following example nests two panels inside a third panel – note the effect this has as the frame is resizedresized

• See NestedPanels.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// NestedPanels.java Author: Lewis/Loftus//// Demonstrates a basic componenet hierarchy.//********************************************************************

import java.awt.*;import javax.swing.*;

public class NestedPanels{

//-----------------------------------------------------------------// Presents two colored panels nested within a third.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Nested Panels");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

// Set p first s bpanel

Copyright © 2012 Pearson Education, Inc.

// Set up first subpanelJPanel subPanel1 = new JPanel();subPanel1.setPreferredSize (new Dimension(150, 100));subPanel1.setBackground (Color.green);JLabel label1 = new JLabel ("One");subPanel1.add (label1);

continued

Page 131: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

39

continued

// Set up second subpanelJPanel subPanel2 = new JPanel();subPanel2.setPreferredSize (new Dimension(150, 100));subPanel2.setBackground (Color.red);JLabel label2 = new JLabel ("Two");subPanel2.add (label2);

// Set up primary panelJPanel primary = new JPanel();primary.setBackground (Color.blue);primary.add (subPanel1);primary.add (subPanel2);

frame.getContentPane().add(primary);

Copyright © 2012 Pearson Education, Inc.

g () (p y);frame.pack();frame.setVisible(true);

}}

continued

// Set up second subpanelJPanel subPanel2 = new JPanel();subPanel2.setPreferredSize (new Dimension(150, 100));subPanel2.setBackground (Color.red);JLabel label2 = new JLabel ("Two");subPanel2.add (label2);

// Set up primary panelJPanel primary = new JPanel();primary.setBackground (Color.blue);primary.add (subPanel1);primary.add (subPanel2);

frame.getContentPane().add(primary);

Copyright © 2012 Pearson Education, Inc.

g () (p y);frame.pack();frame.setVisible(true);

}}

Page 132: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

40

Outline

Creating Objects

The String ClassThe String Class

The Random and Math Classes

Formatting Output

Enumerated Types

Wrapper Classespp

Components and Containers

Images

Copyright © 2012 Pearson Education, Inc.

Images• Images can be displayed in a Java program in

various ways

As we've seen a JL b l object can be used to• As we've seen, a JLabel object can be used to display a line of text

• It can also be used to display an image

• That is, a label can be composed of text, an image, or both at the same timeor both at the same time

Copyright © 2012 Pearson Education, Inc.

Page 133: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

41

Images• The ImageIcon class is used to represent the

image that is stored in a label

• If text is also included, the position of the text relative to the image can be set explicitly

• The alignment of the text and image within the label can be set as well

• See LabelDemo java• See LabelDemo.java

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// LabelDemo.java Author: Lewis/Loftus//// Demonstrates the use of image icons in labels.//********************************************************************

import java.awt.*;import javax swing *;import javax.swing. ;

public class LabelDemo{

//-----------------------------------------------------------------// Creates and displays the primary application frame.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Label Demo");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

Copyright © 2012 Pearson Education, Inc.

ImageIcon icon = new ImageIcon ("devil.gif");

JLabel label1, label2, label3;

label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);

continued

Page 134: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

42

continued

label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);label2.setHorizontalTextPosition (SwingConstants.LEFT);label2.setVerticalTextPosition (SwingConstants.BOTTOM);

label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER);label3.setHorizontalTextPosition (SwingConstants.CENTER);label3.setVerticalTextPosition (SwingConstants.BOTTOM);

JPanel panel = new JPanel();panel.setBackground (Color.cyan);panel.setPreferredSize (new Dimension (200, 250));panel.add (label1);panel.add (label2);panel.add (label3);

Copyright © 2012 Pearson Education, Inc.

frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);

}}

continued

label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);label2.setHorizontalTextPosition (SwingConstants.LEFT);label2.setVerticalTextPosition (SwingConstants.BOTTOM);

label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER);label3.setHorizontalTextPosition (SwingConstants.CENTER);label3.setVerticalTextPosition (SwingConstants.BOTTOM);

JPanel panel = new JPanel();panel.setBackground (Color.cyan);panel.setPreferredSize (new Dimension (200, 250));panel.add (label1);panel.add (label2);panel.add (label3);

Copyright © 2012 Pearson Education, Inc.

frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);

}}

Page 135: Chapter 2   data and expressions [compatibility mode]

22-Sep-13

43

Summary• Chapter 3 focused on:

– object creation and object references– the String class and its methods– the String class and its methods– the Java standard class library– the Random and Math classes– formatting output– enumerated types– wrapper classes– graphical components and containers– labels and images

Copyright © 2012 Pearson Education, Inc.