Methods Chapter 5 Spring 2007 CS 101

advertisement
Methods
Chapter 5
Spring 2007
CS 101
Aaron Bloomfield
1
Preparation
 Scene so far has been background material and experience
 Computing systems and problem solving
 Variables
 Types
 Input and output
 Expressions
 Assignments
 Using objects
 Standard classes and methods
 Decisions (if, switch)
 Loops (while, for, do-while)
 Next: Experience what Java is really about
 Design and implement objects representing information
2
and physical world objects
Object-oriented programming
 Basis
 Create and manipulate objects with attributes
behaviors that the programmer can specify
and
 Mechanism
 Classes
 Benefits
 An information type is design and implemented once
 Reused as needed
 No need reanalysis and re-justification of the
representation
3
Known Classes
 Classes we’ve seen
 BigInteger
 String
 Rectangle
 Vector
 Scanner
 System
 Classes we’ll be seeing soon
 BigDecimal
 But the first step is on creating methods…
4
Methods
5
Methods we’ve seen
 We’ve seen methods (functions) before
 angleSin = Math.sin (90 * PI/180.0);
 System.out.println (“Hello world”);
 value = card.getBlackjackValue();
 We are going to start defining them
 Note that many of these “return” a value
 Math.sin() and card.getBlackjack()
 The way to name methods is the same as variables
 allTheWordsTogether
 With the first letter of each word capitalized
 Except the very first letter is lower case
6
Our first class with methods
public class Methods1 {
public static void main (String args[]) {
Scanner stdin = new Scanner (System.in);
System.out.println ("Enter a valid int value");
int value = stdin.nextInt();
if ( value == 1 )
validValue();
else if ( value == 2 )
validValue();
else if ( value == 3 )
invalidValue();
else if ( value == 4 )
invalidValue();
else
validValue();
}
7
}
Our first class with methods, continued
public static void invalidValue() {
System.out.println ("You have entered an invalid value.");
System.out.println ("The program will now exit.");
System.exit (0);
}
public static void validValue() {
System.out.println ("You have entered an valid value.");
System.out.println ("Congratulations!");
System.out.println ("The program will now exit.");
System.exit (0);
}
8
Program Demo

Methods1.java
9
What’s happening there
public static void validValue() {
System.out.println ("You have entered an valid value.");
System.out.println ("Congratulations!");
System.out.println ("The program will now exit.");
System.exit (0);
}
public static void main (String args[]) {
Scanner stdin = new Scanner (System.in);
System.out.println ("Enter a valid int value");
int value = stdin.nextInt();
if ( value == 1 )
value
stdin
validValue();
// ...
Scanner
}
1
10
Notes on these methods
 At this point, all methods in the class are static
 We will be discussing what static means later in this slide
set
 Until then, I’ll be ignoring it, and just telling you when
things should and should not be static
 Sorry!
 None of those two methods return a value
 Notice the “void” before the method name
 And none take in any parameters
 Notice the empty parameters after the method name
11
13
A previous HW J3
14
15
Revamping last semester’s HW J3
Start
here
Done tech
support?
Bitter
yet?
Successful
managing?
Cynical
guru
Promoted
Become
a coder




A revised HW 3
flowchart
Green paths are
“yes” paths, red
are “no” paths
We’ll
make
a
slight modification
to the diagram:
Note that this part
is repeated twice!
Been a
sysadmin?
Worked
with NT?
Want to
play
w/nukes?
Hate
people?
Start
over
Public
danger
Defense
contractor
16
HW J3 Code

The yellow
boxed part is
what was
repeated from
the previous
slide
if ( extractor.askUser(Q_TECH_SUPPORT) ){
if ( extractor.askUser(Q_BITTER_YET) )
if ( extractor.askUser(Q_MANAGEMENT) )
System.out.println (A_CYNICAL);
else
System.out.println (A_PROMOTED);
else
System.out.println (A_START_OVER);
} else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){
if ( extractor.askUser(Q_HATE_PEOPLE) ) {
System.out.println (A_CODER);
} else if ( extractor.askUser(Q_WINNT) ){
if ( extractor.askUser(Q_NUCLEAR_WEAPONS) )
System.out.println (A_DEFENSE_CONTRACTOR);
else
System.out.println (A_PUBLIC_DANGER);
} else
System.out.println (A_START_OVER);
} else if ( extractor.askUser(Q_WINNT) ){
if ( extractor.askUser(Q_NUCLEAR_WEAPONS) )
System.out.println (A_DEFENSE_CONTRACTOR);
else
System.out.println (A_PUBLIC_DANGER);
} else
System.out.println (A_START_OVER);
17
HW J3 Code with methods

The yellow
boxed part is
what was
repeated from
the previous
slide
if ( extractor.askUser(Q_TECH_SUPPORT) ){
if ( extractor.askUser(Q_BITTER_YET) )
if ( extractor.askUser(Q_MANAGEMENT) )
System.out.println (A_CYNICAL);
else
System.out.println (A_PROMOTED);
else
System.out.println (A_START_OVER);
} else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){
if ( extractor.askUser(Q_HATE_PEOPLE) ) {
System.out.println (A_CODER);
} else
doBottomPartOfFlowchart();
} else
doBottomPartOfFlowchart();
18
HW J3 Code with methods
 The doBottomPartOfFlowchart method:
public static void doBottomPartOfFlowchart() {
if ( extractor.askUser(Q_WINNT) ){
if ( extractor.askUser(Q_NUCLEAR_WEAPONS) )
System.out.println (A_DEFENSE_CONTRACTOR);
else
System.out.println (A_PUBLIC_DANGER);
} else
System.out.println (A_START_OVER);
}
19
What happened here
 We took a common set of code
 Wrote it once
 But used it multiple times (twice in this case)
 Granted, the code was a small segment (7 lines)
 But, in other programs, could be very large
 This is called Refactoring
 It is an essential principle of software engineering
 Has other names: factoring (notice there is no ‘re’ at the
beginning), extracting a method, etc.
20
Pros of Refactoring
 Benefits of Refactoring
 Reduce length of code
 As you don’t have to repeat that section of code
multiple times
 Make code easier to read
 The main if-else-if statement is shorter, thus easier to
understand what’s going on
 Changes are easier to make
 If we want to modify that part of the flowchart, we only
have to do it once
 Rather than searching for each of the repeated code
segments in a program
21
Cons of Refactoring
 Drawbacks of Refactoring
 Because you are calling another method, it will be slightly
slower
 On the order of a few nanoseconds
 Modern compilers can sometimes eliminate this penalty
 The general consensus is that the benefits of Refactoring far
outweigh the drawback(s)
22
23
Return Values
24
The return keyword
 The return keyword immediately stops execution of a method
 And jumps back to whatever called that method
 And possibly returns a value (we’ll see this next)
 Consider the following method
public static void foo (int x) {
if ( x == 1 )
return;
System.out.println (“x is not 1”);
}
 This method will only print the String if x is not 1
25
Return values

At some point in those methods, Java must be told to take a value
and “pass” it back

Consider angleSin = Math.sin (90 * PI/180.0);
 At some point in the Math.sin() method, the sin has been
computed
 And that value must be “passed back” to be stored in angle

Consider value = card.getBlackjackValue();
 At some point in the card.getBlackjackValue() method, the value
has been computed
 And that value must be “passed back” to be stored in value

This is called “returning” a value from a method

Note that some methods don’t return a value
 System.out.println(), for example
26
Return values (aka return types)
public class Methods2 {
public static int returnsAValue () {
return 1;
}
public static double alsoReturnsAValue() {
return 1.0;
}
public static void main (String args[]) {
int value1 = returnsAValue();
System.out.println (value1);
double value2 = alsoReturnsAValue();
System.out.println (value2);
}
}
// The following line requires a cast
int value3 = (int) alsoReturnsAValue();
System.out.println (value3);
27
Program Demo

Methods2.java
28
Return types
 All



a return statement does is take the value
Which could be a number
Or a value in a variable
Or an expression (such as x+1)
 And “pass” it back to whatever called the method
29
How well do you feel you understand
return values?
a)
b)
c)
d)
e)
Very well! This stuff is so easy.
With a little review, I’ll be good.
Not very well at all.
I’m so lost. What’s a return type again?
I’d rather not answer this question, thanks.
30
Parameters
 Sometimes you need to pass in parameters to tell a method
how to perform
 Consider Math.sin() – it needs to know the angle
 The parameters are listed between the parenthesis after the
method name
 public static void main (String args[])
 The methods we will study next compute (and return) x2, x3,
and x4
31
The methods
public static int square (int x) {
int theSquare = x * x;
return theSquare;
}
public static int cube (int x) {
return x * x * x;
}
public static int fourthPower (int x) {
return square(x) * square(x);
}
32
A method with multiple parameters
public static int squareOrCube (int which, int value) {
if ( which == 1 )
return value * value;
else if ( which == 2 ) {
int cube = value * value * value;
return cube;
} else
return 0;
}
33
The main() method
import java.util.*;
public class Methods3 {
// the previous methods go here
public static void main (String args[]) {
Scanner stdin = new Scanner (System.in);
System.out.println ("Enter an int value");
int value = stdin.nextInt();
int theSquare = square(value);
System.out.println ("Square is " + theSquare);
System.out.println ("Cube is " + cube (value));
System.out.println ("Square is " + squareOrCube (1, value));
System.out.println ("Cube is " + squareOrCube (2,value));
System.out.println ("Fourth power is " + fourthPower (value));
}
34
}
Program Demo

Methods3.java
35
36
Returning objects

We can also return objects from methods
 What gets returned is the reference
to the object
name
public class Methods4 {
public static String getCourse () {
String name = "CS 101";
return name;
}
public static void main (String args[]) {
String courseName = getCourse();
System.out.println (courseName);
}
}
String
“CS 101”
courseName
37
Program Demo

Methods4.java
39
Modifying parameters

Consider the following code
public class Methods5 {
public static void changeValue (int x) {
x = 7;
}
public static void main (String args[]) {
int y = 5;
changeValue(y);
System.out.println (y);
}
}

What gets printed?
40
Program Demo

Methods5.java
41
Pass by value
 Java is a pass-by-value language
 This means that a COPY of the parameter’s value is passed
into the method
 If a method changes that value, only the COPY is changed
 Once the method returns, the copy is forgotten
 And thus the change is not visible outside the method
 There are other manners of returning values that are used in
other languages
 Pass by reference
 Pass by name (nobody uses this anymore)
 We will see about trying to change object parameters later in
this slide set
42
How well do you feel you understand
parameters?
oo
...
so
oo
c.
..
da
I’m
at
a
ot
N
N
ot
w
el
l.
ll.
I’m
no
It’
s
y.
ki
n
tg
re
at
a
ith
w
ka
O
,b
u.
..
lit
t..
...
st
uf
fi
w
el
l–
Th
is
irl
y
5.
Fa
4.
w
el
l!
3.
20% 20% 20% 20% 20%
ry
2.
Very well! This stuff is
easy!
Fairly well – with a little
review, I’ll be good
Okay. It’s not great, but
it’s not horrible, either
Not well. I’m kinda
confused
Not at all. I’m
soooooo lost
Ve
1.
43
Variable scoping

A variable is visible within the block it is declared
 Called the “scope” of the variable
public class Scoping {
static int z
This variable is visible
anywhere in the Scoping class
public static void foo (int x) {
// ...
}
This parameter is visible
only in the foo() method
public static void bar () {
// ...
}
public static void main (String[] args) {
int y;
This local variable is visible until
// ...
the end of the main() method
}
}
44
How well do you feel you understand
variable scoping?
oo
...
so
oo
c.
..
da
I’m
at
a
ot
N
N
ot
w
el
l.
ll.
I’m
no
It’
s
y.
ki
n
tg
re
at
a
ith
w
ka
O
,b
u.
..
lit
t..
...
st
uf
fi
w
el
l–
Th
is
irl
y
5.
Fa
4.
w
el
l!
3.
20% 20% 20% 20% 20%
ry
2.
Very well! This stuff is
easy!
Fairly well – with a little
review, I’ll be good
Okay. It’s not great, but
it’s not horrible, either
Not well. I’m kinda
confused
Not at all. I’m
soooooo lost
Ve
1.
45
Method notes summary
 You can put the methods in a class in any order
 Java doesn’t care which one is listed first
 Thus, you can call a method listed later in the method
 This is different than C/C++
 All methods must specify a return type
 If it’s void, then no value is returned
 Parameters can’t be changed within a method
 Although the objects that the parameters point to can be
46
The 2005 Ig Nobel Prizes






Agricultural
history
Physics
Medicine
Literature
Peace
Economics
Chemistry
 Biology
 Nutrition


Fluid dynamics
“The Significance of Mr. Richard Buckley’s Exploding
Trousers”
The pitch drop experiment, started in 1927
Neuticles – artificial replacement testicles for dogs
The 409 scams of Nigeria for a “cast of rich characters”
Locust brain scans while they were watching Star Wars
For an alarm clock that runs away, thus making people more
productive
“Will Humans Swim Faster or Slower in Syrup?”
For cataloging the odors of 131 different stressed frogs
To Dr. Yoshiro Nakamats who catalogued and analyzed every
meal he ate for the last 34 years (and counting)
“Pressures Produced When Penguins Pooh – Calculations on
Avian Defaecation”
47
More on parameter passing
48
Modifying parameters

Consider the following code
public class Methods5 {
public static void changeValue (int x) {
x = 7;
}
x
5
7
y
5
public static void main (String args[]) {
int y = 5;
changeValue(y);
System.out.println (y);
}
}

What gets printed?
 5 is printed
49
Program Demo

Methods5.java
50
Pass by value
 Java is a pass-by-value language
 This means that a COPY of the parameter’s value is passed
into the method
 If a method changes that value, only the COPY is changed
 Once the method returns, the copy is forgotten
 And thus the change is not visible outside the method
 There are other manners of returning values that are used in
other languages
 Pass by reference
 Pass by name (nobody uses this anymore)
 We will see about trying to change object parameters later in
this slide set
51
Modifying parameters

Consider the following code
import java.awt.*;
Rectangle
r
public class Methods6 {
public static void changeValue
(Rectangle r) {
r.setSize (10,20);
}
- width = 10
1
- height = 20
2
+ Rectangle ()
+ Rectangle (int width, int height)
+ setSize (int width, int height)
+ getWidth ()
public static void main (String args[]) {
Rectangle rect = new Rectangle(1, 2);
changeValue(rect);
System.out.println (rect.getWidth());
}
rect
}

What gets printed?
 10 is printed
52
Program Demo

Methods6.java
53
Fan-supplied demotivators!
54
Pass by value
 Java is still a pass-by-value language
 This means that a COPY of the parameter’s value is passed
into the method
 But the parameter is a REFERENCE to an object
 The object itself is not passed
 So any changes to the reference are forgotten about
 But you can modify the object it refers to
55
Rectangle
Modifying parameters

Consider the following code
import java.awt.*;
- width = 10
+ Rectangle ()
+ Rectangle (int width, int height)
+ setSize (int width, int height)
+ getWidth()
r
public class Methods7 {
Rectangle
- width = 1
public static void changeValue
(Rectangle r) {
r = new Rectangle (10,20);
}

What gets printed?
 1 is printed
- height = 2
+ Rectangle ()
+ Rectangle (int width, int height)
+ setSize (int width, int height)
+ getWidth()
public static void main (String args[]) {
Rectangle rect = new Rectangle(1, 2);
changeValue(rect);
System.out.println (rect.getWidth());
}
}
- height = 20
rect
The only change!
56
Program Demo

Methods7.java
57
Pass by value
 Java is still a pass-by-value language
 This means that a COPY of the parameter’s value is passed
into the method
 But the parameter is a REFERENCE to an object
 The object itself is not passed
 So any changes to the reference are forgotten about
 But you can modify the object it refers to
58
How well do you feel you understand
parameter passing?
oo
...
so
oo
c.
..
da
I’m
at
a
ot
N
N
ot
w
el
l.
ll.
I’m
no
It’
s
y.
ki
n
tg
re
at
a
ith
w
ka
O
,b
u.
..
lit
t..
...
st
uf
fi
w
el
l–
Th
is
irl
y
5.
Fa
4.
w
el
l!
3.
20% 20% 20% 20% 20%
ry
2.
Very well! This stuff is
easy!
Fairly well – with a little
review, I’ll be good
Okay. It’s not great, but
it’s not horrible, either
Not well. I’m kinda
confused
Not at all. I’m
soooooo lost
Ve
1.
59
A frisbee demo of parameter passing…
60
How well do you feel you understand
parameter passing?
oo
...
so
oo
c.
..
da
I’m
at
a
ot
N
N
ot
w
el
l.
ll.
I’m
no
It’
s
y.
ki
n
tg
re
at
a
ith
w
ka
O
,b
u.
..
lit
t..
...
st
uf
fi
w
el
l–
Th
is
irl
y
5.
Fa
4.
w
el
l!
3.
20% 20% 20% 20% 20%
ry
2.
Very well! This stuff is
easy!
Fairly well – with a little
review, I’ll be good
Okay. It’s not great, but
it’s not horrible, either
Not well. I’m kinda
confused
Not at all. I’m
soooooo lost
Ve
1.
61
Today’s demotivators
62
Download