+ All Categories
Home > Documents > John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Date post: 02-Jan-2016
Category:
Upload: alfred-gardner
View: 215 times
Download: 1 times
Share this document with a friend
Popular Tags:
70
John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:
Transcript
Page 1: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

John HurleySummer 2012Cal State LA

CS 201 Lecture 7:

Page 2: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Midterm

The midterm exam will be administered in class on Wednesday of week 6.

The exam will have many short answer questions, one one-paragraph writing question, and a programming problem.

On Monday I will administer a sample midterm which will be very similar to the actual midterm in number and type of questions and topic coverage. One of the short-answer questions will be repeated on the actual exam.

Page 3: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

IMPORTANT NOTICE RE MIDTERM

You will need to use a lab computer, *not your own laptop* on the exam

Make sure *today* that you can log on to the network and familiarize yourself with the version of Eclipse that is installed in the lab.

Page 4: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Documentation From Oracle

Java was originally developed by Sun Microsystems and was closed-source but free for many years

Java is now open-sourceAnyone is free to use it or to write compilers, virtual machines, etc. that implement it

Oracle bought Sun a couple of years ago and now is the champion of Java

Page 5: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Documentation From Oracle

When you need to use something like Scanner, look it up in Oracle’s excellent online documentation

Example: Google +Java +ScannerFollow the link to

http://doc.java.sun.com/DocWeb/api/java.util.Scanner

Page 6: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Some Ugly Codepublic class UglyMess {

public static void main(String[] args){

int firstRadius = 2;

double firstCircumference = firstRadius * 2 * 3.1416;

System.out.printf("a circle with radius %d has circumference of %7.4f\n", firstRadius, firstCircumference);

int secondRadius = 6;

double secondCircumference = secondRadius * 2 * 3.14159;

System.out.printf("a circle with radius %d has circumference of %7f\n", secondRadius, secondCircumference);

int thirdRadius = 11;

double thirdCircumference = thirdCircumference = thirdRadius * 2 * 3.142;

System.out.printf("a circle with r = %d has circumference of %7.4f\n", thirdRadius, (thirdRadius * 2 * 3.142));

double fourthCircumference = 11 * 2 * 3.14;

System.out.printf(" circle with radius 11 has circumference of %7.4f\n", fourthCircumference);

}

}

Page 7: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

What We Already KnowWe can already spot some problems with the code above:The second line of output shows 6 digits past the decimal point while the others show 4. Unless there is some reason to do otherwise, we should make this uniform.The last two lines of output show different values for the circumference of a circle with radius 11. We have several variables that are only used once each and represent the same kinds of values (radii and circumferences.)Different lines of output have slightly different label textThis code is hard for humans to understand because it does the same thing repeatedly in inconsistent ways.

Page 8: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Version 1.1public class LessUglyMess {

public static void main(String[] args){

final double PI = 3.14159;

int radius;

double circumference;

radius = 2;

circumference = radius * 2 * PI;

System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);

radius = 6;

circumference = radius * 2 * PI;

System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);

radius = 11;

circumference = radius * 2 * PI;

System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);

radius = 11;

circumference = radius * 2 * PI;

System.out.printf("a circle with radius %d has circumference of %7.4f\n", radius, circumference);

}

}

Page 9: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Version 1.1

New version is easier to understand, more consistent, and does not use unnecessary variables

But we are still doing the same thing several timesSeveral opportunities to make each possible

mistakeHard to change Hard for human beings to read the code

Which mistakes are we likely to make?

Page 10: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Modularity

As the state of the art of programming has progressed, we have found ways to make programs more modular

Modular = constructed from standardized components

Your house contains thousands of nails. They were not each custom-machined-they are multiple copies of the same basic form.

Ford was able to make Model Ts cheaply because, since they were all the same, they could be made cheaply on assembly lines from interchangeable parts

If you made a car from custom-machined parts, it would be expensive to make and hard to repair

Page 11: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Modularity

How far can we take this analogy to physical products when we are talking about software engineering?

You will spend a lot of time in the near future learning ways to make your software more modular; using methods is just the first step

Page 12: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Version 2.0This is BASIC, but this technique was used in other languages ca. 1950s-1960s

10 LET P = 3.1416

20 LET r = 2

30 LET x = 50

40 GOTO 140

50 LET r = 6

60 LET x = 80

70 GOTO 140

80 LET r = 11

90 LET x = 110

100 GOTO 140

110 LET x = 130

120 GOTO 140

130 end

140 LET c = r * 2 * P

150 print "circumference of circle with radius "; r; " is "; c

160 GOTO x

Page 13: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Version 2.0: Pros

Achieves consistency in calculating circumference

If the calculation was more complex than this one, it would also reduce redundant code

We can use the same calculation code whenever we need to by using if statements

If you like this kind of stuff, check out http://www.quitebasic.com/ or find a download of Microsoft QBasic

Page 14: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Version 2.0: Cons

Even harder to understand than v. 1.1!Still many opportunities for errors, including

ones that would be harder to diagnose than the ones we might make with version 1.0

Note the global scope of x, r, and c. They are available anywhere in the program and might be changed anywhere. This is a common source of errors.

Page 15: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Methods

Solution: design and use a methodAlso called subroutines, functions, or procedures in other languages

Separate some coherent piece of functionality into a separate unit of code

Page 16: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

MethodsBenefit of using methods: Modularity

Code a method once, use it as often as you need to

If the method is sufficiently modular, you can even copy it into another class when you need similar functionality

Make code easier to understandMake it easier to change the code; only need to change the method once

Page 17: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Mt. Fuji Principle

A wise man climbs Mt. Fuji once. A fool does it twice.-Japanese proverb

Page 18: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

MethodsYou have already used the main(String[] args)

method in all your assignments so far.main(String[] args) is just a special method that the JVM will find and run when just given a class

You have also used methods from classes distributed with Java, like JOptionPane.showMessageDialog(null, message)

System.out.print()

Page 19: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Defining Methods

19

A method is a collection of statements that are grouped together to perform an operation.

public static int max(int num1, int num2) {

int result; if (num1 > num2) result = num1; else result = num2; return result;

}

modifier return value

type method name

formal parameters

return value

method body

method header

parameter list

Define a method Invoke a method

int z = max(x, y);

actual parameters (arguments)

method signature

Page 20: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Method Signature

20

Method signature is the combination of the method name and the parameter list.

public static int max(int num1, int num2) {

int result; if (num1 > num2) result = num1; else result = num2; return result;

}

modifier return value

type method name

formal parameters

return value

method body

method header

parameter list

Define a method Invoke a method

int z = max(x, y);

actual parameters (arguments)

method signature

Page 21: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Formal Parameters

21

The variables defined in the method header are known as formal parameters.

public static int max(int num1, int num2) {

int result; if (num1 > num2) result = num1; else result = num2; return result;

}

modifier return value

type method name

formal parameters

return value

method body

method header

parameter list

Define a method Invoke a method

int z = max(x, y);

actual parameters (arguments)

method signature

Page 22: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Actual Parameters

22

When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

public static int max(int num1, int num2) {

int result; if (num1 > num2) result = num1; else result = num2; return result;

}

modifier return value

type method name

formal parameters

return value

method body

method header

parameter list

Define a method Invoke a method

int z = max(x, y);

actual parameters (arguments)

method signature

Page 23: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Return Value Type

23

A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void.

public static int max(int num1, int num2) {

int result; if (num1 > num2) result = num1; else result = num2; return result;

}

modifier return value

type method name

formal parameters

return value

method body

method header

parameter list

Define a method Invoke a method

int z = max(x, y);

actual parameters (arguments)

method signature

Page 24: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Parameter Order

A method that takes multiple parameters will assign the values passed to its parameters in the order in which they appear in the method signature. This will seem completely obvious when you see the

next slide.If the values received don’t match the data

types in the method signature, an error exists.A good IDE will catch many errors of this kind

Page 25: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Parameter Orderpublic class ParameterOrderDemo{

public static final double PI = 3.1416;

public static void main(String[] args){

double radius = 1.0;

double height = 2.0;

double cylVol = calcCylinderVolume(radius, height);

System.out.println("radius: " + radius + "; height: " + height + "; cylinder volume: " + cylVol);

}

public static double calcCylinderVolume(double r, double h){

return radius * radius * PI * height;

}

}

Page 26: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Parameters and Return Values

Neither parameters nor a return value is required to meet the definition of a method

We might have any of the following combinations:

No parameters, no return valueParameters but no return valueReturn value but no parametersParameters and return value

Page 27: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

No Parameters, No Return Value

Some methods don’t take any parameters or return anything, just do something:

public static void main(String[] args) {boolean brat = false;// some other logic might result in brat == trueif (brat == true)

countToTen();// do other stuff

}

public static void countToTen() {System.out.println("Alright, I’m going to count to ten, and if

you don’t stop by then, you are in big trouble");for (int counter = 1; counter <= 10; counter++) {

System.out.println("that’s" + counter);}

}}

Page 28: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Parameters, No Return ValueDo something that can be adjusted according to the value of parameters, but don’t return anything:

public class Brat{public static void main(String[] args){

boolean brat = true;int limit = 1;String crime = “breaking dishes";if(brat == true) countToTen(limit, crime);

}

public static void countToTen(int max, String offense){System.out.println("Alright, I'm going to count to " + max + ",

and if you don't stop " + offense + " by the time I'm done, you are in big trouble!");

for(int counter = 1; counter <= max; counter++){System.out.println("that's " + counter);

}}

}

Page 29: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Parameters, No Return ValueNotice that, in this case, max and limit

have different namesWhat is the scope of max?What is the scope of limit?What would happen if we tried to print the

value of limit in countToTen()?What would happen if we tried to print the

value of max in main()?

Page 30: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Return Value, No ParametersA method may get a value of some kind without needing any parameters:

import javax.swing.JOptionPane;

public class Choice{

public static void main(String[] args){

int choice = getChoice();

System.out.println("you say you are " + choice);

}

public static int getChoice(){

int choice = 0;

String choiceString = null;

while(choice < 1 || choice > 100){

choiceString = JOptionPane.showInputDialog(null, "Please enter your age");

choice = Integer.parseInt(choiceString);

}

return choice;}

}

Page 31: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Return Value and ParametersA method may get and return some type of value, based on parameters sent in:

public class MethodDemo {

final static double PI = 3.14159;

public static void main(String[] args){

int radius;

double circumference;

radius = 2;

circumference = calcCircumference(radius);

printCircumference(radius, circumference);

radius = 6;

circumference = calcCircumference(radius);

printCircumference(radius, circumference);

//etc.

}

public static double calcCircumference(int r){

double circ = r * 2 * PI;

return circ;

}

public static void printCircumference(int r, double c){

System.out.printf("a circle with radius %d has circumference of %7.4f\n", r, c);

}

}

Page 32: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

32

Blocks

A pair of braces in a program forms a block

that groups components of a program.

public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Class block

Method block

Page 33: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

ScopeVariables and finals are visible at different

places in your program depending on where you declare them

Scope determines where each variable/final is visible

The modifiers public, protected, and private control which values are visible outside the class; we will cover this towards the end of the term

Variables/finals are only visible in the block in which they are declared and blocks that are inside it

Variables or finals are *not* visible in blocks outside the one in which they are declared, even ones that enclose it

Page 34: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

ScopeIf a variable is declared in an outer block but has

a value assigned to it in an inner block, it still has the new value when control returns to the outer block

This is convenient but can be a source of logic errors

Page 35: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Scope and Parameters

Why can we use PI in the calcCircumference(int r) method?

Why couldn’t we use radius in calcCircumference?

Why couldn’t we use circumference in main?

Page 36: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Scope and Parameters

public static double calcCircumference(int r){double circ = r * 2 * PI;return circ;

}

r is available in this version of calcCircumference() because it is declared and given a value in the method signature

Page 37: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Scope and Methodspublic class ScopeDemo{

static String classString = "This string is visible everywhere in this class";

public static void main(String[] args){String mainString = "This string is visible only in the main method";

for(int counter = 0; counter < 1; counter++){String loopString = "This string is visible only inside the loop";

System.out.println("main method output: \n" + classString + "\n" + mainString +"\n" + loopString);

}otherMethod();

// trying to print loopString or otherMethodString here would cause an error because they are not in scope

// System.out.println(loopString);// System.out.println(otherMethodString);}

public static void otherMethod(){String otherMethodString = "This string is visible only in otherMethod()";System.out.println("\notherMethod output: \n" + classString + "\n" +

otherMethodString);// trying to print mainString or loopString here would cause an error

because they are not in scope// System.out.println(MainString);// System.out.println(MainString);

}}

Page 38: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Scopepublic class ScopeDemo2{

static String classString = new String();

public static void main(String[] args){String mainString = new String();

for(int counter = 0; counter < 1; counter++){String loopString = new String();System.out.println("loop output: \n" + classString + "\n" + mainString +"\n" + loopString);

}

otherMethod();if(1+1 == 2){

classString = "class string";mainString = "main string";System.out.println("if output: \n" + classString + "\n" + mainString);// printing or assigning a value to loopString here would cause an error// loopString = "loopString";

}

System.out.println("output from main after end of if block:\n" + mainString);otherMethod();System.out.println("output from main after returning from otherMethod: \n" + classString);

}

public static void otherMethod(){System.out.println("\notherMethod output: \n" + classString);// using mainString here would cause an error because it is out of scope

classString = "new value of class string";}

Page 39: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Scope and Parameters

Consider MethodDemo againEven if circumference in main() and circ in

calcCircumference() both had the same name, they would still be two separate variables. We would still have to pass circ as a return value.

We could declare circumference with class scope and avoid passing a return value

We could also declare radius with class scope and avoid passing any parameters

Why is this a bad idea?

Page 40: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Scope and ParametersConsider this class:public class MethodScopeDemo{

static int myInt;

public static void main(String[] args){

myInt = 1;

System.out.println(myInt);

otherMethod();

System.out.println(myInt);

}

public static void otherMethod(){

myInt = 2;

}

}

myInt is not passed as a parameter. Why is it in scope in otherMethod()?

What will the output be?

Page 41: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

41

CAUTIONA return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value.

To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated.

public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }

(a)

Should be

(b)

public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return –1; }

Page 42: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and ReferenceSo far, parameters are passed by value

The called method sets up a variable, assigns the parameter value to it, and, presumably, uses it.

If the parameter was a variable, its value in the calling method does not change

If you want to change the value of the variable in the calling method, you can return the correct data type from the called method and assign the return value to the variable:x = getNewX();

Page 43: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference

If you want to change the value of the variable in the calling method, you can return the correct data type from the called method and assign the return value to the variable:x = getNewX();

Note the difference between this and the situation with myInt in MethodScopeDemo above!

Page 44: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference

Even if you use the value of a class scope variable as a parameter and give the formal parameter in the called method the same name, Java will create a new variable with method scope that “hides” the class scope variable:

public class HidingDemo{

static int x = 1;

public static void main(String[] args){

int y = otherMethod(x);

System.out.println(x);

System.out.println(y);

}

public static int otherMethod(int x){

x = 2;

return x; // this x “hides” the global x

}

}

Output of the above is:12

Page 45: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and ReferenceSounds pretty simple so far, right? Not any more!

The demos above all use primitive types like int and double

It’s more complicated when you pass an object, such as a String

There will certainly be problems on the midterm and final that require you to understand this.

Page 46: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference All parameters are passed by value as described above

BUT objects are not passed. Instead, we pass variables that contain references to objects

A reference is a description of where to look in memory for the object In this code:

StringBuilder sb = “Hi, Mom”; sb is a reference to the StringBuilder, not a copy of

the StringBuilder itself. We need to “dereference” the reference to get the actual StringBuilder.

This is transparent most of the time, but you need to understand it.

Page 47: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference

Other languages (eg Visual Basic) use the concept “pass by reference”

Some languages, like C, allow the programmer to choose whether to pass by value or by reference

In Java, objects can’t be passedIn Java we conventionally say we are passing

the reference variable by value

Page 48: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference

If the called method changes the object, we will see the changes from anywhere where the object is in scope

No need to return the new valueRemember that this is how we pass objects.

Primitive types are passed in a much simpler way, as described above.

Page 49: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Referencepublic class NoPassByReferenceDemo{

public static void main(String[] args){StringBuilder tagLine = new StringBuilder("Ah,

Satan sees Natasha");System.out.println(tagLine);otherMethod(tagLine);System.out.println(tagLine);

}

public static void otherMethod(StringBuilder myString){myString.reverse();

}}

Page 50: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference

In the code above,We passed the reference variable to otherMethod()Then we used it to find the object and changed the object,

but not the reference variableAfter that, the value of the reference is still the same – it

shows where to find the object. But, the object has changedWe see the new state of the object when we access it from

wherever it is in scope

This point is difficult but very important! If you don’t understand it after this lecture, study the last few slides carefully. If you still don’t understand it, come to my office hours.

Page 51: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Value and Reference

Next week’s lab will require you to track the largest value returned from multiple calls to a method.

The easiest way to do this is as follows:use an instance variable (one that has scope everywhere in the class) initialized to the lowest possible value; in the lab, that will be 0

Each time the other method is called, compare the return value to the value in the variable. If the new value is higher, reset the variable to that value; otherwise, do nothing.

Page 52: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Pass By ValueFor some reason,this image helps many students pay attention to the concept that passing by value is like making a copy of the value and handing it to the called method

Page 53: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Pass A Reference

Passing a reference to an object is like telling the called method where to find the object

Page 54: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Stacks

A stack is a way of ordering data so that the last value you add to the stack is the first one you use from it.Like a stack of plates in a cafeteria

Last In, First Out (LIFO)

Page 55: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Stacks

Stacks have many uses in programming

The one that concerns us in this class is that this is how the JVM keeps track of method calls

Page 56: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

56

Call Stacks

(a) The main method is invoked.

Space required for the main method k: j: 2 i: 5

(b) The max method is invoked.

Space required for the max method num2: 2 num1: 5

(d) The max method is finished and the return value is sent to k.

(e) The main method is finished.

Stack is empty

Space required for the main method k: j: 2 i: 5

Space required for the main method k: 5 j: 2 i: 5

(c) The max method is being executed.

Space required for the max method result: 5 num2: 2 num1: 5

Space required for the main method k: j: 2 i: 5

Page 57: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

57

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

i is declared and initialized

The main method is invoked.

i: 5

animation

Page 58: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

58

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

j is declared and initialized

The main method is invoked.

j: 2 i: 5

animation

Page 59: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

59

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Declare k

The main method is invoked.

Space required for the main method

k: j: 2 i: 5

animation

Page 60: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

60

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Invoke max(i, j)

The main method is invoked.

Space required for the main method

k: j: 2 i: 5

animation

Page 61: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

61

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

pass the values of i and j to num1 and num2

The max method is invoked.

num2: 2 num1: 5

Space required for the main method

k: j: 2 i: 5

animation

Page 62: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

62

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

pass the values of i and j to num1 and num2

The max method is invoked.

result:

num2: 2 num1: 5

Space required for the main method

k: j: 2 i: 5

animation

Page 63: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

63

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

(num1 > num2) is true

The max method is invoked.

result:

num2: 2 num1: 5

Space required for the main method

k: j: 2 i: 5

animation

Page 64: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

64

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Assign num1 to result

The max method is invoked.

Space required for the max method result: 5

num2: 2 num1: 5

Space required for the main method

k: j: 2 i: 5

animation

Page 65: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

65

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Return result and assign it to k

The max method is invoked.

Space required for the max method result: 5

num2: 2 num1: 5

Space required for the main method k:5

j: 2 i: 5

animation

Page 66: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

66

Trace Call Stack

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Execute print statement

The main method is invoked.

Space required for the main method k:5

j: 2 i: 5

animation

Page 67: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Method Overloading

Scary-sounding term for a very simple concept

You can’t have two methods in the same class with the same name and same method signature

But you can have two methods with the same name and different signatures

Page 68: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Method Overloading

Scary term for a very simple conceptYou can’t have two methods in the same class with the same name and same method signature

But you can have two methods with the same name and different signatures

Page 69: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

import javax.swing.JOptionPane;

public class Overload{

public static void main(String[] args){

int x = 0;

x = getInt();

JOptionPane.showMessageDialog(null, "You chose " + x);

int min = 2;

int max = 10;

x = getInt(min, max);

JOptionPane.showMessageDialog(null, "You chose " + x);

}

public static int getInt(){

int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter an integer"));

return x;

}

public static int getInt(int low, int high){

int val = low -1;

do{

val = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter an integer between " + low + " and " + high));

} while(val < low || val > high);

return val;

}

}

Page 70: John Hurley Summer 2012 Cal State LA CS 201 Lecture 7:

Write and Test Your Code Incrementally

70

You should be able to explain in one sentence how any method you write works. If you can’t, break it down into two or more methods.

The Stevie Wonder principle:"When you believe in things that you don't understand, then you suffer."


Recommended