Chapter 5—Methods The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Methods C H A P T E R 5 With method and logic one can.

Slides:



Advertisements
Similar presentations
1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Advertisements

Methods Java 5.1 A quick overview of methods
Control Structures Selections Repetitions/iterations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 1. The Phases of Software Development. Data Structure 2 Chapter outline  Objectives  Use Javadoc to write a method’s complete specification.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
CS 201 Functions Debzani Deb.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS 201 Functions Debzani Deb.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Chapter 1 Program Design
Topic 4 – Programmer- Defined Functions. CISC 105 – Topic 4 Functions So far, we have only seen programs with one function, main. These programs begin.
 2003 Prentice Hall, Inc. All rights reserved Introduction Modules –Small pieces of a problem e.g., divide and conquer –Facilitate design, implementation,
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Methods Eric Roberts CS 106A January 20, Once upon a time...
Functions in C++ Eric Roberts CS 106B January 9, 2013.
Invitation to Computer Science, Java Version, Second Edition.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 5 Methods. An overview In Add2Integers: println(“This program adds two integers.”); int n1 = readInt(“Enter n1: “); method name: println argument.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.
Problem Solving Techniques. Compiler n Is a computer program whose purpose is to take a description of a desired program coded in a programming language.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Decision Making in Programs.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
1 CS161 Introduction to Computer Science Topic #9.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Five-Minute Review 1.What are expression statements? Compound statements? 2.What is a scope? 3.What are conditional statements in Java? How about iterative.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Functions and Libraries. The idea of a function Functions in programming A function is a block of code that has been given a name. To invoke that code.
11 Making Decisions in a Program Session 2.3. Session Overview  Introduce the idea of an algorithm  Show how a program can make logical decisions based.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Mechanics of Functions
Five-Minute Review What are expression statements? Compound statements? What is a scope? What are conditional statements in Java? How about iterative statements?
Five-Minute Review What are expression statements? Compound statements? What is a scope? What are conditional statements in Java? How about iterative statements?
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Mechanics of Functions
Methods Java 5.1 A quick overview of methods
Classes, Objects and Methods
Basic Concepts of Algorithm
CMSC 202 Exceptions.
Presentation transcript:

Chapter 5—Methods The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Methods C H A P T E R 5 With method and logic one can accomplish anything. —Agatha Christie, Poirot Investigates, 1924 Özyeğin University Slides are adapted from the originals available at

A Quick Overview of Methods At the most basic level, a method is a sequence of statements that has been collected together and given a name. The name makes it possible to execute the statements much more easily; instead of copying out the entire list of statements, you can just provide the method name.

A Quick Overview of Methods You have been working with methods ever since you wrote your first Java program in Chapter 2. The run method in every program is just one example. Most of the programs you have seen have used other methods as well, such as println and setColor. The following terms are useful when learning about methods: –Invoking a method using its name is known as calling that method. –The caller can pass information to a method by using arguments. –When a method completes its operation, it returns to its caller. –A method can pass information to the caller by returning a result.

Methods and Information Hiding One of the most important advantages of methods is that they make it possible for callers to ignore the inner workings of complex operations. When you use a method, it is more important to know what the method does than to understand exactly how it works. The underlying details are of interest only to the programmer who implements a method. Programmers who use a method as a tool can usually ignore the implementation altogether. The idea that callers should be insulated from the details of method operation is the principle of information hiding, which is one of the cornerstones of software engineering.

Methods as Tools for Programmers Particularly when you are first learning about programming, it is important to keep in mind that methods are not the same as application programs, even though both provide a service that hides the underlying complexity involved in computation. The key difference is that an application program provides a service to a user, who is typically not a programmer but rather someone who happens to be sitting in front of the computer. By contrast, a method provides a service to a programmer, who is typically creating some kind of application. This distinction is particularly important when you are trying to understand how the applications-level concepts of input and output differ from the programmer-level concepts of arguments and results. Methods like readInt and println are used to communicate with the user and play no role in communicating information from one part of a program to another.

Method Calls as Expressions Syntactically, method calls in Java are part of the expression framework. Methods that return a value can be used as terms in an expression just like variables and constants. The Math class in the java.lang package defines several methods that are useful in writing mathematical expressions. Suppose, for example, that you need to compute the distance from the origin to the point (x, y), which is given by x 2 + y 2 You can apply the square root function by calling the sqrt method in the Math class like this: double distance = Math.sqrt(x * x + y * y); Note that you need to include the name of the class along with the method name. Methods like Math.sqrt that belong to a class are called static methods.

Useful Methods in the Math Class Math.abs( x ) Returns the absolute value of x Math.min( x, y ) Returns the smaller of x and y Math.max( x, y ) Returns the larger of x and y Math.sqrt( x ) Returns the square root of x Math.log( x ) Returns the natural logarithm of x (log e x ) Math.exp( x ) Returns the inverse logarithm of x (e x ) Math.pow( x, y ) Returns the value of x raised to the y power (x y ) Math.sin( theta ) Returns the sine of theta, measured in radians Math.cos( theta ) Returns the cosine of theta Math.tan( theta ) Returns the tangent of theta Math.asin( x ) Returns the angle whose sine is x Math.acos( x ) Returns the angle whose cosine is x Math.atan( x ) Returns the angle whose tangent is x Math.toRadians( degrees ) Converts an angle from degrees to radians Math.toDegrees( radians ) Converts an angle from radians to degrees

Method Calls as Messages In object-oriented languages like Java, the act of calling a method is often described in terms of sending a message to an object. For example, the method call rect.setColor(Color.RED); is regarded metaphorically as sending a message to the rect object asking it to change its color. setColor(Color.RED) The object to which a message is sent is called the receiver. receiver. name ( arguments ); The general pattern for sending a message to an object is

Writing Your Own Methods The general form of a method definition is scope type name ( argument list ) { statements in the method body } where scope indicates who has access to the method, type indicates what type of value the method returns, name is the name of the method, and argument list is a list of declarations for the variables used to hold the values of each argument. The most common value for scope is private, which means that the method is available only within its own class. If other classes need access to it, scope should be public instead. If a method does not return a value, type should be void. Such methods are sometimes called procedures.

Returning Values from a Method You can return a value from a method by including a return statement, which is usually written as return expression ; where expression is a Java expression that specifies the value you want to return. As an example, the method definition private double feetToInches(double feet) { return 12 * feet; } converts an argument indicating a distance in feet to the equivalent number of inches, relying on the fact that there are 12 inches in a foot.

Methods Involving Control Statements The body of a method can contain statements of any type, including control statements. As an example, the following method uses an if statement to find the larger of two values: private int max(int x, int y) { if (x > y) { return x; } else { return y; } As this example makes clear, return statements can be used at any point in the method and may appear more than once.

The factorial Method The factorial of a number n (which is usually written as n! in mathematics) is defined to be the product of the integers from 1 up to n. Thus, 5! is equal to 120, which is 1 x 2 x 3 x 4 x 5. private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } The following method definition uses a for loop to compute the factorial function:

Nonnumeric Methods private String weekdayName(int day) { switch (day) { case 0: return "Sunday"; case 1: return "Monday"; case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Thursday"; case 5: return "Friday"; case 6: return "Saturday"; default: return "Illegal weekday"; } Methods in Java can return values of any type. The following method, for example, returns the English name of the day of the week, given a number between 0 (Sunday) and 6 (Saturday):

Methods Returning Graphical Objects The text includes examples of methods that return graphical objects. The following method creates a filled circle centered at the point ( x, y ), with a radius of r pixels, which is filled using the specified color: If you are creating a GraphicsProgram that requires many filled circles in different colors, the createFilledCircle method turns out to save a considerable amount of code. private GOval createFilledCircle(double x, double y, double r, Color color) { GOval circle = new GOval(x - r, y - r, 2 * r, 2 * r); circle.setFilled(true); circle.setColor(color); return circle; }

Predicate Methods Methods that return Boolean values play an important role in programming and are called predicate methods. As an example, the following method returns true if the first argument is divisible by the second, and false otherwise: private boolean isDivisibleBy(int x, int y) { return x % y == 0; } Once you have defined a predicate method, you can use it just like any other Boolean value. For example, you can print the integers between 1 and 100 that are divisible by 7 as follows: for (int i = 1; i <= 100; i++) { if (isDivisibleBy(i, 7)) { println(i); }

Using Predicate Methods Effectively New programmers often seem uncomfortable with Boolean values and end up writing ungainly code. For example, a beginner might write isDivisibleBy like this: private boolean isDivisibleBy(int x, int y) { if (x % y == 0) { return true; } else { return false; } A similar problem occurs when novices explicitly check to see if a predicate method returns true. You should be careful to avoid such redundant tests in your own programs. for (int i = 1; i <= 100; i++) { if (isDivisibleBy(i, 7) == true) { println(i); } While this code is not technically incorrect, it is inelegant enough to deserve the bug symbol. private boolean isDivisibleBy(int x, int y) { if (x % y == 0) { return true; } else { return false; }

Exercise: Testing Powers of Two Write a predicate method called isPowerOfTwo that takes an integer n and returns true if n is a power of two, and false otherwise. The powers of 2 are 1, 2, 4, 8, 16, 32, and so forth; numbers that are less than or equal to zero cannot be powers of two. private boolean isPowerOfTwo(int n) { if (n < 1) return false; while (n > 1) { if (n % 2 == 1) return false; n /= 2; } return true; }

Mechanics of the Method-Calling Process When you invoke a method, the following actions occur: Java evaluates the argument expressions in the context of the calling method. 1. Java then copies each argument value into the corresponding parameter variable, which is allocated in a newly assigned region of memory called a stack frame. This assignment follows the order in which the arguments appear: the first argument is copied into the first parameter variable, and so on. 2. Java then evaluates the statements in the method body, using the new stack frame to look up the values of local variables. 3. When Java encounters a return statement, it computes the return value and substitutes that value in place of the call. 4. Java then discards the stack frame for the called method and returns to the caller, continuing from where it left off. 5.

The Combinations Function To illustrate method calls, the text uses a function C(n, k) that computes the combinations function, which is the number of ways one can select k elements from a set of n objects. Suppose, for example, that you have a set of five coins: a penny, a nickel, a dime, a quarter, and a dollar: How many ways are there to select two coins? penny + nickel penny + dime penny + quarter penny + dollar nickel + dime nickel + quarter nickel + dollar dime + quarter dime + dollar quarter + dollar for a total of 10 ways.

Combinations and Factorials Fortunately, mathematics provides an easier way to compute the combinations function than by counting all the ways. The value of the combinations function is given by the formula C(n, k) = n !n ! k !k ! (n – k) !(n – k) ! x Given that you already have a factorial method, is easy to turn this formula directly into a Java method, as follows: private int combinations(int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); } The next slide simulates the operation of combinations and factorial in the context of a simple run method.

The Combinations Program At this point, the program calls the combinations method, as follows: 1. Evaluate the arguments n and k to get the integers 5 and Create a new frame for the combinations method. 3. Initialize the parameter variables n and k to the argument values. public void run() { int n = readInt("Enter number of objects in the set (n): "); int k = readInt("Enter number to be chosen (k): "); println("C(" + n + ", " + k + ") = " + combinations(n, k) ); } Combinations nk 10 Enter number of objects in the set (n): 5 C(5, 2) = 10 Enter number to be chosen (k): 25 2 private int combinations(int n, int k) { return factorial(n) / ( factorial(k) * factorial(n - k) ); } nk The program now calls the factorial method, applying the same process. The factorial method returns the value 120 to its caller. The program makes another call to factorial, with k as its argument. This call to factorial returns the value 2. The program calls factorial yet again with n - k as its argument. The final call to factorial returns the value 6. skip simulation private int factorial(int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result *= i; } return result; } nresult 5 i private int factorial(int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result *= i; } return result; } nresult 2 i private int factorial(int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result *= i; } return result; } nresult 3 i public void run() { int n = readInt("Enter number of objects in the set (n): "); int k = readInt("Enter number to be chosen (k): "); println("C(" + n + ", " + k + ") = " + combinations(n, k) ); } nk 25

Decomposition One of the most important advantages of methods is that they make it possible to break a large task down into successively simpler pieces. This process is called decomposition. Complete Task Suppose, for example, that you have been given a large task that seems too large to code as a single run method. Subtask 1Subtask 2Subtask 3 Before you start writing any code, you should think about the problem with an eye toward breaking the complete task into simpler subtasks. Subtask 2a Subtask 2b Some of the subtasks may themselves be so difficult that it makes sense to break them into even smaller subtasks. You can then continue the process until each individual subtask is manageable. One of the most important advantages of methods is that they make it possible to break a large task down into successively simpler pieces. This process is called decomposition. Once you have completed the decomposition, you can then write a method to implement each subtask.

Choosing a Decomposition Strategy One of the most subtle aspects of programming is the process of deciding how to decompose large tasks into smaller ones. In most cases, the best decomposition strategy for a program follows the structure of the real-world problem that program is intended to solve. If the problem seems to have natural subdivisions, those subdivisions usually provide a useful basis for designing the program decomposition. Each subtask in the decomposition should perform a function that is easy to name and describe. One of the primary goals of decomposition is to simplify the programming process. A good decomposition strategy must therefore limit the spread of complexity. As a general rule, each level in the decomposition should take responsibility for certain details and avoid having those details percolate up to higher levels.

Drawing a Train As its primary illustration of decomposition, the text uses the problem of writing a GraphicsProgram to draw a train: Although it would be possible to write a single run method to draw the necessary graphical objects, such a program would be very difficult to read. Fortunately, the problem has a natural decomposition, at least at the first level: public void run() { Draw the engine. Draw the boxcar. Draw the caboose. } DrawTrain

Using Pseudocode Although the run method public void run() { Draw the engine. Draw the boxcar. Draw the caboose. } suggests the decomposition for the DrawTrain program, it is not yet legal Java code, but instead a combination of English and Java that sketches the emerging outline of the solution. Such informal descriptions are called pseudocode. It is important to remember that you don’t need to implement each of the steps before you can turn this pseudocode into legal Java. Each of the English lines will simply be a method call. All you need to do at this point is give each method a name and decide what arguments those methods need.

Arguments vs. Named Constants In graphical programs like the DrawTrain example, there are two primary strategies for providing the individual methods with the information they need to draw the right picture, such as the sizes and locations of the individual objects: –You can use named constants to define the parameters of the picture. –You can pass this information as arguments to each method. Each of these strategies has advantages and disadvantages. Using named constants is easy but relatively inflexible. If you define constants to specify the location of the boxcar, you can only draw a boxcar at that location. Using arguments is more cumbersome but makes it easier to change such values. What you want to do is find an appropriate tradeoff between the two approaches. The text recommends these guidelines: –Use arguments when callers will want to supply different values. –Use named constants when callers will be satisfied with a single value.

Parameters for Drawing Train Cars The DrawTrain program in the text makes the following assumptions: –The caller will always want to supply the location of each car. –All train cars are the same size and have the same basic structure. –Engines are always black. –Boxcars come in many colors, which means the caller must supply it. –Cabooses are always red. These assumptions imply that the headers for drawEngine, drawBoxcar, and drawCaboose will look like this: private void drawEngine(double x, double y) private void drawBoxcar(double x, double y, Color color) private void drawCaboose(double x, double y)

Looking for Common Features Another useful strategy in choosing a decomposition is to look for features that are shared among several different parts of a program. Such common features can be implemented by a single method. In the DrawTrain program, every train car has a common structure that consists of the frame for the car, the wheels on which it runs, and a connector to link it to its neighbor. –The engine is black and adds a smokestack, cab, and cowcatcher. –The boxcar is colored as specified by the caller and adds doors. –The caboose is red and adds a cupola. You can use a single drawCarFrame method to draw the common parts of each car.

The End