23
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

Embed Size (px)

Citation preview

Page 1: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Methods and Functions

Page 2: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

If programs are shortWe can write the code as one contiguous segment

• The logic is probably simple• There are not too many variables• Not too likely to make a lot of errors

As programs get longerProgramming in a single segment gets more and more difficult• Logic is more complex• Many variables, expressions, control

statements

Page 3: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

If programs are shortCode as one contiguous segment

• The logic is probably simple• There are not too many variables• Not too likely to make a lot of errors

As programs get longerProgramming in a single segment gets difficult• Logic is more complex• Many variables, expressions, control

statements

Page 4: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Difficult to do if ONE BIG PROGRAM:• Isolating and fixing bugs • need to be modified program• Add to programAnswer: Break programs into small segments

Page 5: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Method (or function or subprogram)• A segment of code that is logically

separate from the rest of the program

• When invoked (i.e. called) control jumps from main to the method and it executes

• Usually with parameters (arguments) • When finished, control reverts to the

next statement after the method call

Page 6: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Methods provide us with functional (or procedural) abstraction

Do not need to know all of the details of the methods in order to use them.

Need to know:1. What arguments (parameters) we must

provide2. What the effect of the method is (i.e.

what does it do?)The actual implementation could be done in several different ways

Page 7: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Ex: Predefined method: sort(Object [] a)There are many ways to sort!EX: word.length();

This allows programmers to easily use methods that they didn’t write.

Page 8: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Java methods have two primary uses:1. To act as a function, returning a result to the calling code.

These methods are declared with return types, and are called within an assignment or expression

Ex: X = inScan.nextDouble();Y = (Math.sqrt(X))/2;

2. To act as a subroutine or procedure, executing code but not explicitly returning a result

These methods are declared to be void, and are called as separate stand-alone statements

Ex: System.out.println(“Wacky”);Arrays.sort(myData);

Page 9: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

•There are MANY predefined methods in Java4Look in the online API4These are often called with dot notation:

ClassName.methodName(param_list)• ClassName is the class in which the method is defined

• methodName is the name of the method

• param_list is a list of 0 or more variables or expressions that are passed to the method

Page 10: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Ex: Y = Math.sqrt(X);• These are called STATIC methods or CLASS methods

They are associated with a class, not with an object.

Page 11: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Some are also called in the following wayClassName.ObjectName.methodName(param_list)

• ObjectName is the name of a static, predefined object that contains the methodEx: System.out.println(“Hello There”);System is a predefined classout is a predefined PrintStream object within Systemprintln is a method within PrintStream

These are instance methods – associated with an object –Primarily we will focus on static methods

Page 12: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

What if we need to use a method that is not predefined?

That’s why we are coders , we are in charge of our universe .

Page 13: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Syntax:public static void methodName(param_list){ // method body}public static retval methodName(param_list){ // method body}

Where retval is some Java typeWhen method is not void, there MUST be a return statement

Page 14: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Really simple example:public static void sayWacky(){

System.out.println(“Wacky”);}

Now in our main program we can have:sayWacky();sayWacky();for (int i = 0; i < 5; i++)

sayWacky();

Note we are not using any parameters in this example

Page 15: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Theparam_list is a way in which we pass values into our methods

• This enables methods to process different information at different points in the program

Makes them more flexible• In the method definition (header or

signature): List of type identifier pairs, separated by

commas Called formal parameters, or parameters

• In the method call (can be main or another method):

List of variables or expressions that match 1-1 with the parameters in the definition

Called actual parameters, or arguments

Page 16: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Ex: public static double area(double radius){

double ans = Math.PI * radius * radius;

return ans;}In main:double rad = 2.0;double theArea = area(rad);

Note: If method is called in same class in which it was defined, we don’t need to use the class name in the call

Page 17: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

17

Lecture 7: Parameters

4 Parameters in Java are passed by value• The parameter is a copy of the evaluation of

the argument• Any changes to the parameter do not affect the

argument

Main Class

2.0rad

area method

radius 2.0

main calls area method

value passed from arg. to parameter

double theArea = area(rad);

theAreadouble ans =

Math.PI * radius * radius;

return ans;

ans 12.566…result returned to main

12.566…

answer calculated

answer returnedmethod completed

Page 18: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Effect of value parameters:Arguments passed into a method cannot be changed within the method, either intentionally or accidentally

Good result: Prevents accidental side-effects from methodsBad result: What if we want the arguments to be changed?Ex: swap(A, B)

Method swaps the values in A and B- Discuss

We can get around this issue when we get into object-oriented programming

Page 19: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

Variables declared within a method are local to that method

They exist only within the context of the methodThis includes parameters as well

Think of a parameter as a local variable that is initialized in the method call

We say the scope of these variables is point in the method that they are declared up to the end of the method

Page 20: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb

However, Java variables can also be declared within blocks inside of methods

In this case the scope is the point of the declaration until the end of that blockBe careful that you declare your variables in the correct block

Page 21: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

Proverb• However, Java variables can also be declared within blocks inside of methods4 In this case the scope is the point of the

declaration until the end of that block4 Be careful that you declare your variables

in the correct block

Page 22: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

22

References and Reference Types

• Recall primitive types and reference types4 Also recall how they are stored

• With primitive types, data values are stored directly in the memory location associated with a variable

• With reference types, values are references to objects that are stored elsewhere in memory

var1 100

sHello There

Page 23: “Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions

“Education is a Treasure that follows you everywhere.”– Chines

ProverbWhat do we mean by “references”?The data stored in a variable is just the “address” of the location where the object is stored

Thus it is separate from the object itselfEx: If I have a Contacts file on my PC, it will have the address of my friend, Joe Schmoe (stored as Schmoe, J.)I can use that address to send something to Joe or to go visit him if I would likeHowever, if I change that address in my Contacts file, it does NOT in any way affect Joe, but now I no longer know where Joe is located

However, I can indirectly change the data in the object through the reference. So if reference variables are changed in a methodIt will also be changed in main.