copyright 2006 by pearson education 1 building java programs chapter 3: introduction to parameters...

70
1 Copyright 2006 by Pearson Education Building Java Building Java Programs Programs Chapter 3: Introduction to Parameters and Objects

Upload: gladys-gibbs

Post on 31-Dec-2015

227 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

1Copyright 2006 by Pearson Education

Building Java Building Java ProgramsPrograms

Chapter 3: Introduction to Parameters and Objects

Page 2: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

2Copyright 2006 by Pearson Education

Chapter outline parameters

passing parameters to static methods writing methods that accept parameters

methods that return values calling methods that return values (e.g. the Math class) writing methods that return values

using objects String objects Point objects console input with Scanner objects

Page 3: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

3Copyright 2006 by Pearson Education

reading: 3.1

ParametersParameters

Page 4: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

4Copyright 2006 by Pearson Education

Reminder: class constants In the last chapter, we used class constants to fix

"magic number" redundancy problems:

public static final int FIGURE_WIDTH = 5;

public static void drawFigure1() { drawPlusLine(); drawBarLine(); drawPlusLine(); }

public static void drawPlusLine() { System.out.print("+"); for (int i = 1; i <= FIGURE_WIDTH; i++) { System.out.print("/\\"); } System.out.println("+"); }

public static void drawBarLine() { System.out.print("|"); for (int i = 1; i <= 2 * FIGURE_WIDTH; i++) { System.out.print(" "); } System.out.println("|"); }

Page 5: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

5Copyright 2006 by Pearson Education

Another repetitive figure Now consider the task of drawing the following figures:

*************

*******

***********************************

*********** ***********

****** ** ******

The lines and figures are similar, but not exactly the same.

Page 6: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

6Copyright 2006 by Pearson Education

A redundant solutionpublic class Stars1 { public static void main(String[] args) { drawLineOf13Stars(); drawLineOf7Stars(); drawLineOf35Stars(); draw10x3Box(); draw5x4Box(); }

public static void drawLineOf13Stars() { for (int i = 1; i <= 13; i++) { System.out.print("*"); } System.out.println(); }

public static void drawLineOf7Stars() { for (int i = 1; i <= 7; i++) { System.out.print("*"); } System.out.println(); }

public static void drawLineOf35Stars() { for (int i = 1; i <= 35; i++) { System.out.print("*"); } System.out.println(); } ...

The methods at left are redundant.

Would constants help us solve this problem?

What would be a better solution?

drawLine - A method to draw a line of any number of stars.

drawBox - A method to draw a box of any size.

Page 7: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

7Copyright 2006 by Pearson Education

Parameterization parameterized method: One that is given extra

information (e.g. number of stars to draw) when it is called.

parameter: A value passed to a method by its caller.

Writing parameterized methods requires 2 steps: write the method to accept the parameter call the method and pass the parameter value(s) desired

main

drawLine

*******

7

drawLine

*************

13

Page 8: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

8Copyright 2006 by Pearson Education

Writing parameterized methods Parameterized method declaration syntax:

public static void <name> ( <type> <name> ) { <statement(s)> ;}

Example:public static void printSpaces(int count) {

for (int i = 1; i <= count; i++) {

System.out.print(" ");

}

}

Whenever printSpaces is called, the caller must specify how many spaces to print.

Page 9: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

9Copyright 2006 by Pearson Education

Calling parameterized methods passing a parameter: Calling a parameterized method

and specifying a value for its parameter(s).

Parameterized method call syntax:

<name> ( <expression> );

Example:System.out.print("*");printSpaces(7);System.out.print("**");int x = 3 * 5;printSpaces(x + 2);System.out.println("***");

Output:

* ** ***

Page 10: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

10Copyright 2006 by Pearson Education

How parameters are passed When the parameterized method call executes:

the value written is copied into the parameter variable the method's code executes using that value

public static void main(String[] args) { printSpaces(7); printSpaces(13);}

public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); }}

713

Page 11: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

11Copyright 2006 by Pearson Education

Value semantics value semantics: When primitive variables (int, double)

are passed as parameters, their values are copied. Modifying the parameter inside the method will not affect the

variable passed in.

public static void main(String[] args) {

int x = 23;

strange(x);

System.out.println("2. x = " + x); // unchanged

...

}

public static void strange(int x) {

x = x + 1;

System.out.println("1. x = " + x);

}

Output:

1. x = 242. x = 23

Page 12: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

12Copyright 2006 by Pearson Education

Common errors If a method accepts a parameter, it is illegal to call it

without passing any value for that parameter.printSpaces(); // ERROR: parameter value required

The value passed to a method must be of the correct type, matching the type of its parameter variable.

printSpaces(3.7); // ERROR: must be of type int

Exercise: Change the Stars program to use a parameterized static method for drawing lines of stars.

Page 13: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

13Copyright 2006 by Pearson Education

Stars solution// Prints several lines of stars.// Uses a parameterized method to remove redundancy.

public class Stars2 { public static void main(String[] args) { drawLine(13); drawLine(7); drawLine(35); } // Prints the given number of stars plus a line break. public static void drawLine(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); } System.out.println(); }}

Page 14: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

14Copyright 2006 by Pearson Education

Multiple parameters Methods can accept multiple parameters.

The parameters are separated by commas. When the method is called, it must be passed values for each of

its parameters.

Multiple parameters declaration syntax:

public static void <name> ( <type> <name> , <type> <name> , ..., <type> <name> ) { <statement(s)> ;}

Multiple parameters call syntax:<name> ( <expression>, <expression>, ..., <expression> );

Page 15: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

15Copyright 2006 by Pearson Education

Multiple parameters examplepublic static void main(String[] args) { printNumber(4, 9); printNumber(17, 6); printNumber(8, 0); printNumber(0, 8);}

public static void printNumber(int number, int count) { for (int i = 1; i <= count; i++) { System.out.print(number); } System.out.println();}

Output:

444444444171717171717

00000000

Exercise: Write an improved Stars program that draws boxes of stars using parameterized static methods.

Page 16: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

16Copyright 2006 by Pearson Education

Stars solution// Prints several lines and boxes made of stars.// Third version with multiple parameterized methods.

public class Stars3 { public static void main(String[] args) { drawLine(13); drawLine(7); drawLine(35); System.out.println(); drawBox(10, 3); drawBox(5, 4); drawBox(20, 7); }

// Prints the given number of stars plus a line break. public static void drawLine(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); } System.out.println(); } ...

Page 17: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

17Copyright 2006 by Pearson Education

Stars solution, cont'd. ...

// Prints a box of stars of the given size. public static void drawBox(int width, int height) { drawLine(width);

for (int i = 1; i <= height - 2; i++) { System.out.print("*"); printSpaces(width - 2); System.out.println("*"); }

drawLine(width); }

// Prints the given number of spaces. public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } } }

Page 18: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

18Copyright 2006 by Pearson Education

Parameter "mystery" problem What is the output of the following program?

public class Mystery { public static void main(String[] args) { int x = 5, y = 9, z = 2; mystery(z, y, x); System.out.println(x + " " + y + " " + z); mystery(y, x, z); System.out.println(x + " " + y + " " + z); }

public static void mystery(int x, int z, int y) { x++; y = x - z * 2; x = z + 1; System.out.println(x + " " + y + " " + z); }}

Page 19: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

19Copyright 2006 by Pearson Education

Parameter question Rewrite the following program to use parameterized methods:

// Draws triangular figures of stars.

public class Loops { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i - 1; j++) { System.out.print(" "); } for (int j = 1; j <= 10 - 2 * i + 1; j++) { System.out.print("*"); } System.out.println(); }

for (int i = 1; i <= 12; i++) { for (int j = 1; j <= i - 1; j++) { System.out.print(" "); } for (int j = 1; j <= 25 - 2 * i; j++) { System.out.print("*"); } System.out.println(); } }}

Page 20: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

20Copyright 2006 by Pearson Education

Parameter answer Rewrite the following program to use parameterized methods:

// Draws triangular figures using parameterized methods.

public class Loops { public static void main(String[] args) { triangle(5); triangle(12); } // Draws a triangle figure of the given size. public static void triangle(int height) { for (int i = 1; i <= height; i++) { printSpaces(i - 1); drawLine(2 * height + 1 - 2 * i); } }

...}

Page 21: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

21Copyright 2006 by Pearson Education

Parameter questions Write a method named printDiamond that accepts a

height as a parameter and prints a diamond figure: * ******** *** *

Write a method named multiplicationTable that accepts a maximum integer as a parameter and prints a table of multiplication from 1 x 1 up to that integer times itself.

Write a method named bottlesOfBeer that accepts an integer as a parameter and prints the "XX Bottles of Beer" song with that many verses.

Page 22: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

22Copyright 2006 by Pearson Education

reading: 3.2

Methods that return Methods that return valuesvalues

Page 23: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

23Copyright 2006 by Pearson Education

Java's Math class Java has a class named Math with useful static methods

and constants for performing calculations.Method name Description

abs(value) absolute value

ceil(value) rounds up

cos(value) cosine, in radians

floor(value) rounds down

log(value) logarithm, base e

log10(value) logarithm, base 10

max(value1, value2) larger of two values

min(value1, value2) smaller of two values

pow(base, exponent)

base to the exponent power

random() random double between 0 and 1

round(value) nearest whole number

sin(value) sine, in radians

sqrt(value) square root

Constant Description

E 2.7182818...

PI 3.1415926...

Page 24: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

24Copyright 2006 by Pearson Education

Methods that return values return: To send a value out as the result of a method,

which can be used in an expression. A return is like the opposite of a parameter:

Parameters pass information in from the caller to the method. Return values pass information out from a method to its caller.

The Math methods do not print results to the console.Instead, each method evaluates to produce (or return) a numeric result, which can be used in an expression.

main

Math.abs

-42

Math.round

2.71

42

3

Page 25: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

25Copyright 2006 by Pearson Education

Math method examples Math method call syntax:

Math. <method name> ( <parameter(s)> )

Examples:double squareRoot = Math.sqrt(121.0);System.out.println(squareRoot); // 11.0

int absoluteValue = Math.abs(-50);System.out.println(absoluteValue); // 50

System.out.println(Math.min(3, 7) + 2); // 5

Notice that the preceding calls are used in expressions; they can be printed, stored into a variable, etc.

Page 26: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

26Copyright 2006 by Pearson Education

Math method questions Evaluate the following expressions:

Math.abs(-1.23) Math.pow(3, 2) Math.pow(10, -2) Math.sqrt(121.0) - Math.sqrt(256.0) Math.round(Math.PI) + Math.round(Math.E) Math.ceil(6.022) + Math.floor(15.9994) Math.abs(Math.min(-3, -5))

Math.max and Math.min can be used to bound numbers.Consider an int variable named age. What statement would replace negative ages with 0? What statement would cap the maximum age to 40?

Page 27: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

27Copyright 2006 by Pearson Education

Methods that return values Syntax for methods that return a value:

public static <type> <name> ( < parameter(s)> ) { < statement(s)> ;}

Returning a value from a method:

return <expression> ;

Example:

// Returns the slope of the line between the given points.public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1;

double dx = x2 - x1; return dy / dx ;}

Page 28: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

28Copyright 2006 by Pearson Education

Return examples// Converts Fahrenheit to Celsius.public static double fToC(double degreesF) { double degreesC = 5.0 / 9.0 * (degreesF - 32); return degreesC;}

// Computes length of triangle hypotenuse given its side lengths.public static double hypotenuse(int a, int b) { double c = Math.sqrt(a * a + b * b); return c;}

// Rounds the given number to two decimal places.// Example: round(2.71828183) returns 2.72.public static double round2(double value) { double result = value * 100; // upscale the number result = Math.round(result); // round to nearest integer result = result / 100; // downscale the number return result;}

Page 29: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

29Copyright 2006 by Pearson Education

Return examples shortened// Converts Fahrenheit to Celsius.public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 32);}

// Computes length of triangle hypotenuse given its side lengths.public static double hypotenuse(int a, int b) { return Math.sqrt(a * a + b * b);}

// Rounds the given number to two decimal places.// Example: round(2.71828183) returns 2.72.public static double round2(double value) { return Math.round(value * 100) / 100;}

Page 30: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

30Copyright 2006 by Pearson Education

Return questions Write a method named area that accepts a circle's

radius as a parameter and returns its area. You may wish to use the constant Math.PI in your solution.

Write a method named distanceFromOrigin that accepts x and y coordinates as parameters and returns the distance between that (x, y) point and the origin.

Write a method named attendance that accepts a number of lectures attended by a student, and returns how many points a student receives for attendance. The student receives 2 points for each of the first 5 lectures and 1 point for each subsequent lecture.

Page 31: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

31Copyright 2006 by Pearson Education

How to comment: params If your method accepts parameters and/or returns a

value, write a brief description of what the parameters are used for and what kind of value will be returned.

In your comments, you can also write your assumptions about the values of the parameters.

You may wish to give examples of what values your method returns for various input parameter values.

Example:// This method returns the factorial of the given integer n.// The factorial is the product of all integers up to that number.// Assumes that the parameter value is non-negative.// Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120.public static int factorial(int n) { ...}

Page 32: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

32Copyright 2006 by Pearson Education

reading: 3.3

Using objectsUsing objects

Page 33: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

33Copyright 2006 by Pearson Education

Objects So far, we have seen:

methods, which represent behavior variables, which represent data (categorized by types)

It is possible to create new types that are combinations of the existing types.

Such types are called object types or reference types. Languages such as Java in which you can do this are called

object-oriented programming languages.

We will learn how to use some of Java's objects. In Chapter 8 we will learn to create our own types of objects.

Page 34: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

34Copyright 2006 by Pearson Education

Objects and classes object: An entity that contains data and behavior.

There are variables inside the object, representing its data. There are methods inside the object, representing its behavior.

class: A program, or a template for a type of objects.

Examples: The class String represents objects that store text characters. The class Point represents objects that store (x, y) data. The class Scanner represents objects that read information from

the keyboard, files, and other sources.

Page 35: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

35Copyright 2006 by Pearson Education

Constructing objects construct: To create a new object.

Objects are constructed with the new keyword. Most objects must be constructed before they can be used.

Constructing objects, general syntax:<type> <name> = new <type> ( <parameters> );

Examples:Point p = new Point(7, -4);DrawingPanel window = new DrawingPanel(300, 200);Color orange = new Color(255, 128, 0);

Classes' names are usually uppercase (e.g. Point, Color).

Strings are also objects, but are constructed without new :String name = "Amanda Ann Camp";

Page 36: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

36Copyright 2006 by Pearson Education

Calling methods of objects Objects contain methods that can be called by your program.

For example, a String's methods manipulate or process the text of that String in useful ways.

When we call an object's method, we are sending a message to it.

We must specify which object we are talking to, and then write the method's name.

Calling a method of an object, general syntax:<variable> . <method name> ( <parameters> )

The results will be different from one object to another.

Examples:String gangsta = "G., Ali";System.out.println(gangsta.length()); // 7

Point p1 = new Point(3, 4);Point p2 = new Point(0, 0);System.out.println(p1.distance(p2)); // 5.0

Page 37: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

37Copyright 2006 by Pearson Education

Point objects Java has a class of objects named Point.

To use Point, you must write: import java.awt.*;

Constructing a Point object, general syntax:

Point <name> = new Point(<x>, <y>);

Point <name> = new Point(); // the origin, (0, 0)

Examples:Point p1 = new Point(5, -2);

Point p2 = new Point();

Point objects are useful for several reasons: They store two values, an (x, y) pair, in a single variable. They have useful methods we can call in our programs.

Page 38: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

38Copyright 2006 by Pearson Education

Point data and methods Data stored in each Point object:

Useful methods of each Point object:

Point objects can also be printed using println statements:Point p = new Point(5, -2);

System.out.println(p); // java.awt.Point[x=5,y=-2]

Method name Description

distance(p) how far away the point is from point p

setLocation(x, y) sets the point's x and y to the given values

translate(dx, dy) adjusts the point's x and y by the given amounts

Field name Description

x the point's x-coordinate

y the point's y-coordinate

Page 39: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

39Copyright 2006 by Pearson Education

Using Point objects An example program that uses Point objects:

import java.awt.*;

public class PointMain { public static void main(String[] args) { // construct two Point objects Point p1 = new Point(7, 2); Point p2 = new Point(4, 3);

// print each point and their distance apart System.out.println("p1 is " + p1); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2));

// translate the point to a new location p2.translate(1, 7); System.out.println("p2: (" + p2.x + ", " + p2.y + ")"); System.out.println("distance = " + p1.distance(p2)); }}

Page 40: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

40Copyright 2006 by Pearson Education

Point objects question Write a program that computes a right triangle's perimeter.

The perimeter is the sum of the triangle's side lengths a+b+c. Read values a and b and compute side length c as the distance

between the points (0, 0) and (a, b).

side a? 12side b? 5perimeter is 30.0

Page 41: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

41Copyright 2006 by Pearson Education

Point objects answerimport java.awt.*; // for Pointimport java.util.*; // for Scanner

public class TrianglePerimeter { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("side a? "); int a = console.nextInt(); System.out.print("side b? "); int b = console.nextInt(); Point p1 = new Point(); // 0, 0 Point p2 = new Point(a, b); double c = p1.distance(p2); double perimeter = a + b + c; System.out.println("perimeter is " + perimeter); }}

Page 42: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

42Copyright 2006 by Pearson Education

reading: 3.3

Objects as Objects as parameters:parameters:

value vs. reference value vs. reference semanticssemantics

Page 43: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

43Copyright 2006 by Pearson Education

Swapping primitive values Consider the following code to swap two int variables:

public static void main(String[] args) { int a = 7; int b = 35; System.out.println(a + " " + b);

// swap a with b a = b; b = a;

System.out.println(a + " " + b);}

What is wrong with this code? What is its output?

Page 44: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

44Copyright 2006 by Pearson Education

Swapping, corrected When swapping, you should set aside one variable's

value into a temporary variable, so it won't be lost.

Better code to swap two int variables:

public static void main(String[] args) { int a = 7; int b = 35; System.out.println(a + " " + b);

// swap a with b int temp = a; a = b; b = temp;

System.out.println(a + " " + b);}

Page 45: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

45Copyright 2006 by Pearson Education

A swap method? Swapping is a common operation, so we might want to

make it into a method. Does the following swap method work? Why or why not?

public static void main(String[] args) { int a = 7; int b = 35; System.out.println(a + " " + b);

// swap a with b swap(a, b);

System.out.println(a + " " + b);}

public static void swap(int a, int b) { int temp = a; a = b; b = temp;}

Page 46: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

46Copyright 2006 by Pearson Education

Value semantics value semantics: Behavior where variables are copied

when assigned to each other or passed as parameters. Primitive types in Java use value semantics. When one variable is assigned to another, the value is copied. Modifying the value of one variable does not affect others.

Example:int x = 5;

int y = x; // x = 5, y = 5

y = 17; // x = 5, y = 17

x = 8; // x = 8, y = 17

x y

Page 47: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

47Copyright 2006 by Pearson Education

Modifying primitive parameters When we call a method and pass primitive variables' values as

parameters, we can assign new values to the parameters inside the method.

But this does not affect the value of the variable that was passed; its value was copied, and the two variables are otherwise distinct.

Example:

public static void main(String[] args) { int x = 1; foo(x); System.out.println(x); // output: 1}

public static void foo(int x) { x = 2;}

value 1 is copied into parameter

parameter's value is changed to 2(variable x in main is unaffected)

x 1

x 1 2

Page 48: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

48Copyright 2006 by Pearson Education

Reference semantics reference semantics: Behavior where variables refer

to a common value when assigned to each other or passed as parameters.

Objects in Java use reference semantics. Object variables do not actually store an object; they store the

address of an object's location in the computer memory. Variables for objects are called reference variables. We often draw reference variables as small boxes that point an

arrow toward the object they refer to.

Example:Point p1 = new Point(3, 8);

x 3 y 8p1

Page 49: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

49Copyright 2006 by Pearson Education

Multiple references If two reference variables are assigned to refer to the

same object, the object is not copied. Both variables literally share the same object. Calling a method on either variable will modify the same object.

Point p1 = new Point(3, 8);Point p2 = new Point(2, -4);Point p3 = p2;

Here 3 variables refer to 2 objects. If we change p3, will p2 change? If we change p2, will p3 change?

x 3 y 8p1

x 2 y -4p2

p3

Page 50: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

50Copyright 2006 by Pearson Education

Multiple references If two variables refer to the same object, modifying one

of them will also make a change in the other:p3.translate(5, 1);System.out.println("(" + p2.x + " " + p2.y + ")");

OUTPUT:(7, -3)

x 3 y 8p1

x 7 y -3p2

p3

Page 51: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

51Copyright 2006 by Pearson Education

Why references? The fact that objects are passed by reference was done

for several reasons:

efficiency. Objects can be large, bulky things. Having to copy them every time they are passed as parameters would slow down the program.

sharing. Since objects hold important state and have behavior that modifies that state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object.

Page 52: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

52Copyright 2006 by Pearson Education

Objects as parameters When an object is passed as a parameter, the object is not copied.

The same object is shared by the original variable and parameter. If a method is called on the parameter, it will affect the original

object that was passed to the method. Since the variable p1 and the parameter p refer to the same

object, modifying one will also make a change in the other:

public static void main(String[] args) { Point p1 = new Point(2, 3); example(p1);}

public static void example(Point p) { p.setLocation(-1, -2);}

x -1 y -2p1

p

Page 53: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

53Copyright 2006 by Pearson Education

String objects string: A sequence of text characters.

One of the most common types of objects. In Java, strings are represented as objects of class String.

String variables can be declared and assigned, just like primitive values:

String <name> = "<text>";

String <name> = <expression that produces a String>;

Unlike most other objects, a String is not created with new. Examples:

String name = "Marla Singer";

int x = 3, y = 5;String point = "(" + x + ", " + y + ")";

Page 54: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

54Copyright 2006 by Pearson Education

Indexes The characters in a String are each internally

numbered with an index, starting with 0: Example:String name = "P. Diddy";

Individual characters are represented inside the String by values of a primitive type called char.

Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4'.

An escape sequence can be represented as a char, such as '\n' (new-line character) or '\'' (apostrophe).

index 0 1 2 3 4 5 6 7

character

'P' '.' ' ' 'D' 'i' 'd' 'd' 'y'

Page 55: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

55Copyright 2006 by Pearson Education

String methods Useful methods of each String object:

These methods are called using the dot notation:String example = "speak friend and enter";

System.out.println(example.toUpperCase());

Method name Description

charAt(index) character at a specific index

indexOf(str) index where the start of the given string appears in this string (-1 if it is not there)

length() number of characters in this string

substring(index1, index2) the characters in this string from index1 (inclusive) to index2 (exclusive)

toLowerCase() a new string with all lowercase letters

toUpperCase() a new string with all uppercase letters

Page 56: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

56Copyright 2006 by Pearson Education

String method examples// index 012345678901String s1 = "Stuart Reges";String s2 = "Marty Stepp";System.out.println(s1.length()); // 12System.out.println(s1.indexOf("e")); // 8System.out.println(s1.substring(1, 4)); // tua

String s3 = s2.toUpperCase();System.out.println(s3.substring(6, 10)); // STEP

String s4 = s1.substring(0, 6);System.out.println(s4.toLowerCase()); // stuart

Page 57: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

57Copyright 2006 by Pearson Education

Modifying Strings The methods that appear to modify a string (substring, toLowerCase, toUpperCase, etc.) actually create and return a new string.

String s = "lil bow wow";

s.toUpperCase();

System.out.println(s); // output: lil bow wow

If you want to modify the variable, you must reassign it to store the result of the method call:

String s = "lil bow wow";

s = s.toUpperCase();

System.out.println(s); // output: LIL BOW WOW

Page 58: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

58Copyright 2006 by Pearson Education

String methods Given the following string:

String book = "Building Java Programs"; How would you extract the word "Java" ? How would you change book to store:"BUILDING JAVA PROGRAMS" ?

How would you extract the first word from any general string?

Method name Description

charAt(index) character at a specific index

indexOf(str) index where the start of the given string appears in this string (-1 if it is not there)

length() number of characters in this string

substring(index1, index2) the characters in this string from index1 (inclusive) to index2 (exclusive)

toLowerCase() a new string with all lowercase letters

toUpperCase() a new string with all uppercase letters

Page 59: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

59Copyright 2006 by Pearson Education

reading: 3.4

Interactive programs Interactive programs using Scanner objectsusing Scanner objects

Page 60: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

60Copyright 2006 by Pearson Education

Interactive programs We have written programs that print console output.

It is also possible to read input from the console. The user types the input into the console. We can capture the input and use it in our program. Such a program is called an interactive program.

Interactive programs can be challenging: Computers and users think in very different ways. Users tend to misbehave.

Page 61: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

61Copyright 2006 by Pearson Education

Input and System.in We print output using an object named System.out

This object has methods named println and print.

We read input using an object named System.in System.in is not intended to be used directly. We will use a second object, from a class called Scanner, to help

us read input from System.in.

Constructing a Scanner object to read console input:Scanner <name> = new Scanner(System.in);

Example:Scanner console = new Scanner(System.in);

Once we have constructed the Scanner, we call various methods on it to read the input from the user.

Page 62: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

62Copyright 2006 by Pearson Education

Scanner methods Methods of Scanner that we will use in this chapter:

Each of these methods pauses your program until the user types input and presses Enter.

Then the value typed is returned to your program.

prompt: A message printed to the user, telling them what input to type, before we read from the Scanner.

Example:System.out.print("How old are you? "); // promptint age = console.nextInt();System.out.println("You'll be 40 in " + (40 - age)

+ " years.");

Method Description

nextInt() reads and returns user input as an int

nextDouble() reads and returns user input as a double

next() reads and returns user input as a String

Page 63: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

63Copyright 2006 by Pearson Education

Java class libraries, import Java class libraries: A large set of Java classes

available for you to use (part of the JDK). These objects are organized into groups named packages. To use the objects from a package, you must include an

import declaration at the top of your program.

Import declaration, general syntax:import <package name> .*;

Scanner is in a package named java.util To use Scanner, put this at the start of your program:

import java.util.*;

Page 64: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

64Copyright 2006 by Pearson Education

Input tokens token: A unit of user input, as read by the Scanner.

Tokens are separated by whitespace (spaces, tabs, new lines). How many tokens appear on the following line of input?23 John Smith 42.0 "Hello world"

When the token doesn't match the type the Scanner tries to read, the program crashes.

Example:

System.out.print("What is your age? ");int age = console.nextInt();

Output (user's input is underlined):

What is your age? Timmyjava.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) ...

Page 65: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

65Copyright 2006 by Pearson Education

Example Scanner usageimport java.util.*; // so that I can use Scanner

public class ReadSomeInput { public static void main(String[] args) { Scanner console = new Scanner(System.in);

System.out.print("What is your first name? "); String name = console.next();

System.out.print("And how old are you? "); int age = console.nextInt();

System.out.println(name + " is " + age); System.out.println("That's quite old!"); }}

Output (user input underlined):What is your first name? RuthHow old are you? 14Ruth is 14That's quite old!

Page 66: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

66Copyright 2006 by Pearson Education

Another Scanner exampleimport java.util.*; // so that I can use Scanner

public class Average { public static void main(String[] args) { Scanner console = new Scanner(System.in);

System.out.print("Please type three numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt();

double average = (double) (num1 + num2 + num3) / 3; System.out.println("The average is " + average); }}

Output (user input underlined):Please type three numbers: 8 6 13The average is 9.0

Notice that the Scanner can read multiple values from one line.

Page 67: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

67Copyright 2006 by Pearson Education

Scanners as parameters If multiple methods read user input, declare a Scanner

in main and pass it to each of them as a parameter. In this way, all of the methods share the same Scanner object.

public static void main(String[] args) { Scanner console = new Scanner(System.in); int sum = readSum3(console); System.out.println("The sum is " + sum);}

public static int readSum3(Scanner console) { System.out.print("Type 3 numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt(); return num1 + num2 + num3;}

Page 68: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

68Copyright 2006 by Pearson Education

Scanner BMI questionA person's body mass index (BMI) is computed by the following formula:

Write a program that produces the following output:This program reads in data for two peopleand computes their body mass index (BMI)and weight status.

Enter next person's information:height (in inches)? 62.5weight (in pounds)? 130.5

Enter next person's information:height (in inches)? 58.5weight (in pounds)? 90

Person #1 body mass index = 23.485824Person #2 body mass index = 18.487836949375414Difference = 4.997987050624587

7032

height

weightBMI

Page 69: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

69Copyright 2006 by Pearson Education

Scanner BMI solution// This program computes two people's body mass index (BMI)// and compares them. The code uses parameters and returns.

import java.util.*; // so that I can use Scanner

public class BMI { public static void main(String[] args) { introduction(); Scanner console = new Scanner(System.in);

double bmi1 = processPerson(console); double bmi2 = processPerson(console); // report overall results System.out.println("Person #1 body mass index = " + bmi1); System.out.println("Person #2 body mass index = " + bmi2); double difference = Math.abs(bmi1 - bmi2); System.out.println("Difference = " + difference); } // prints a welcome message explaining the program public static void introduction() { System.out.println("This program reads in data for two people"); System.out.println("and computes their body mass index (BMI)"); System.out.println("and weight status."); System.out.println(); } ...

Page 70: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Introduction to Parameters and Objects

70Copyright 2006 by Pearson Education

Scanner BMI solution, cont. ...

// reads information for one person, computes their BMI, and returns it public static double processPerson(Scanner console) { System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height = console.nextDouble(); System.out.print("weight (in pounds)? "); double weight = console.nextDouble(); System.out.println(); double bmi = getBMI(height, weight); return bmi; } // Computes a person's body mass index based on their height and weight // and returns the BMI as its result. public static double getBMI(double height, double weight) { double bmi = weight / (height * height) * 703; return bmi; }}