Methods (Deitel chapter 6)

Similar documents
Methods (Deitel chapter 6)

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Part 8 Methods. scope of declarations method overriding method overloading recursions

Chapter 6 - Methods Prentice Hall. All rights reserved.

Methods: A Deeper Look

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter 3 - Functions

C Functions. 5.2 Program Modules in C

Functions. Systems Programming Concepts

CSE123. Program Design and Modular Programming Functions 1-1

CT 229 Java Syntax Continued

Introduction to Programming

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Methods: A Deeper Look Pearson Education, Inc. All rights reserved.

Object Oriented Methods : Deeper Look Lecture Three

Chapter 3 - Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Arrays (Deitel chapter 7)

Functions and Recursion

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

CS110: PROGRAMMING LANGUAGE I

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Pace University. Fundamental Concepts of CS121 1

CS 335 Lecture 02 Java Programming

Fundamentals of Programming Session 13

CS 335 Java Programming Controls. Fall 2007

Methods: A Deeper Look

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

C++ Programming Lecture 11 Functions Part I


142

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

C Functions Pearson Education, Inc. All rights reserved.

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

1001ICT Introduction To Programming Lecture Notes

Introduction to Computer Science I

Object-Based Programming. Programming with Objects

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Lecture 04 FUNCTIONS AND ARRAYS

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Lecture 04 FUNCTIONS AND ARRAYS

The Math Class. Using various math class methods. Formatting the values.

Methods CSC 121 Fall 2016 Howard Rosenthal

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Methods CSC 121 Spring 2017 Howard Rosenthal

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

CS110D: PROGRAMMING LANGUAGE I

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

C Programming for Engineers Functions

C Functions. Object created and destroyed within its block auto: default for local variables

Lecture 5: Methods CS2301

Chapter 5 C Functions

Introduction to Computer Science Unit 2. Notes

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

C Programs: Simple Statements and Expressions

JAVA: A Primer. By: Amrita Rajagopal

CS313D: ADVANCED PROGRAMMING LANGUAGE

A variable is a name for a location in memory A variable must be declared

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Methods CSC 121 Fall 2014 Howard Rosenthal

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Packages. Examples of package names: points java.lang com.sun.security drawing.figures

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

CS 106 Introduction to Computer Science I

We now start exploring some key elements of the Java programming language and ways of performing I/O

The return Statement

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Functions and Recursion

Java Classes: Math, Integer A C S L E C T U R E 8

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Downloaded from Chapter 2. Functions

Chapter 5 Methods / Functions

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

AP CS Unit 3: Control Structures Notes

Built-in Types of Data

ECE 122. Engineering Problem Solving with Java

- HALF YEARLY EXAM ANSWER KEY DEC-2016 COMPUTER SCIENCE ENGLISH MEDIUM

CS 106 Introduction to Computer Science I

JAVA Programming Concepts

Unit 7. Functions. Need of User Defined Functions

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Transcription:

1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods of Class JApplet Method Overloading Recursion Example Using Recursion: The Fibonacci Series Recursion vs. Iteration Introduction 3 Program Modules in Java Modules in Java Methods Classes Java API provides several modules Programmers can also create modules e.g., programmer-defined methods Methods Invoked by a method call Returns a result to calling method (caller) Similar to a boss (caller) asking a worker (called method) to complete a task The declarations and statements within braces form the method body. Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs 5 Math-Class Methods worker boss worker1 worker2 worker3 worker5 Class java.lang.math Provides common mathematical calculations Calculate the square root of 900.0: Math.sqrt( 900.0 ) Method sqrt belongs to class Math Dot (.) allows access to method sqrt The argument 900.0 is located inside parentheses Hierarchical boss-method/worker-method relationship. Math class is part of java.lang (automatically imported by the compiler)

Method Description Example abs( x absolute value abs( 23.7 ) of x (this method also has float, int and long versions) ) is 23.7 7 Methods Declarations 8 abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7 ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp( x ) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.3890 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0 max( x, y ) larger value of x and y (this method also has float, int and long max( 2.3, 12.7 ) is 12.7 versions) max( -2.3, -12.7 ) is -2.3 min( x, y ) smaller value of x and y (this method also has float, int and long min( 2.3, 12.7 ) is 2.3 versions) min( -2.3, -12.7 ) is -12.7 pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0 sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 Fig..2 Math-class methods. Methods Allow programmers to modularize programs Makes program development more manageable (divide-and-conquer) Software reusability (using existing methods as building blocks) Avoid repeating code Local variables Declared in method declaration Parameters Communicates information between methods via method calls Method Declarations (cont.) General format of method declaration: return-value-type method-name( parameter1, parameter2,, parametern ) { declarations and statements } Method can also return values: return expression; 9 25 double max = maximum( number1, number2, number3 ); // method call. 39 0 } // end method init 1 2 // maximum method uses Math class method max to help 3 // determine maximum value public double maximum( double x, double y, double z ) 5 { return Math.max( x, Math.max( y, z ) ); 7 8 } // end method maximum 9 50 } // end class Maximum Method maximum returns value from method max of class Math Maximum.java 10 Line 25 When maximum method is called a copy of the args is made and program control tranfers to 1st line of method maximum. Method receives a copy of the values in the parameters x,y,z. Line Method maximum returns value from method max of class Math Notes 11 Notes 12 Omitting the return-vale-type in a method definition is a syntax error All variables declared in method definitions are local variables Forgetting to return a value from a method that is supposed to return a value is a syntax error Redefining a method parameter as a local variable in the method is a syntax error Returning a value from a method whose return type has been declared void is a syntax error Methods should be small (half/1 page) Types are required for each parameter in the method Methods can return at most one value

Argument Promotion 13 1 Coercion of arguments Forcing arguments to appropriate type to pass to method e.g., System.out.println( Math.sqrt( ) ); Evaluates Math.sqrt( ) Then evaluates System.out.println() Promotion rules Specify how to convert types without data loss Type Valid promotions double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double byte short, int, long, float or double boolean None (boolean values are not considered to be numbers in Java) Fig..5 Allowed promotions for primitive types. Converting a primitive type to another primitive type may change the value if the new type is not an allowed promotion Java API Packages Packages Classes grouped into categories of related classes Promotes software reuse import statements specify classes used in Java programs 15 Package Description java.applet The Java Applet Package contains the Applet class and several interfaces that enable applet/browser interaction and the playing of audio clips. In Java 2, class javax.swing.japplet is used to define an applet that uses the Swing GUI components. java.awt The Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs in Java 1.0 and 1.1. In Java 2, the Swing GUI components of the javax.swing packages are often used instead. java.awt.event The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable event handling for GUI components in both the java.awt and javax.swing packages. java.io The Java Input/Output Package contains classes that enable programs to input and output data (see Chapter 17, Files and Streams). java.lang The Java Language Package contains classes and interfaces (discussed throughout this text) that are required by many Java programs. This package is imported by the compiler into all programs. 1 e.g., import javax.swing.japplet; java.net The Java Networking Package contains classes that enable programs to communicate via networks (see Chapter 18, Networking). java.text The Java Text Package contains classes and interfaces that enable a Java program to manipulate numbers, dates, characters and strings. The package provides many of Java s internationalization capabilities that enable a program to be customized to a specific locale (e.g., an applet may display strings in different languages, based on the user s country). java.util The Java Utilities Package contains utility classes and interfaces, such as date and time manipulations, randomnumber processing capabilities with class Random, storing and processing large amounts of data and breaking strings into smaller pieces called tokens with class StringTokenizer (see Chapter 20; Data Structures, Chapter 21, Java Utilities Package and Bit Manipulation; and Chapter 22, Collections). javax.swing The Java Swing GUI Components Package contains classes and interfaces for Java s Swing GUI components that provide support for portable GUIs. javax.swing.event The Java Swing Event Package contains classes and interfaces that enable event handling for GUI components in package javax.swing. Fig.. Java API packages (a subset). Random-Number Generation 17 Scope of Declarations 18 Java random-number generators Math.random() ( int ) ( Math.random() * ) Produces integers from 0-5 Use a seed for different random-number sequences Scope (of identifiers: var, ref, method) Portion of the program that can reference an entity by its name Basic scope rules Scope of a local-variable declaration Scope of a local-variable declaration that appears in the initialization section of a for statement s header Scope of a method or field of a class

1 // Fig..10: Scoping.java 2 // A scoping example. 3 import java.awt.container; Field x has class scope 5 import javax.swing.*; 7 public class Scoping extends JApplet { 8 JTextArea outputarea; 9 10 // field that is accessible to all methods of this class 11 int x = 1; 12 13 // create applet's GUI 1 init() 15 { 1 outputarea = new JTextArea(); 17 Container container = getcontentpane(); 18 container.add( outputarea ); 19 Local variable x has block scope 20 } // end method init 21 22 // method start called after init completes; start calls 23 // methods uselocal and usefield Method start uses 2 start() local variable x 25 { 2 int x = 5; // local variable in method start that shadows field x 27 28 outputarea.append( "local x in start is " + x ); 29 Scoping.java 19 Line 11 field x Line 2 Local variable x Line 28 Method start uses local variable x 30 uselocal(); // uselocal has local x 31 usefield(); // useinstance uses Scoping's field x 32 uselocal(); // uselocal reinitializes local x 33 usefield(); // Scoping's field x retains its value 3 35 outputarea.append( "\n\nlocal x in start is " + x ); 3 37 } // end method start 38 39 // uselocal creates and initializes Re-create local variable variable x x during each call 0 uselocal() and initialize it to 25 1 { 2 int x = 25; // initialized each time uselocal is called 3 outputarea.append( "\n\nlocal x in uselocal is " + x + 5 " after entering uselocal" ); ++x; 7 outputarea.append( "\nlocal x in uselocal is " + x + 8 " before exiting uselocal" ); 9 50 } // end method uselocal 51 Scoping.java 20 Line 2 Recreate variable x and initialize it to 25 Lines 0-50 Method uselocal uses local variable x Method uselocal uses local variable x 52 // usefield modifies Scoping's field x during each call 53 usefield() 5 { 55 outputarea.append( "\n\nfield x is " + x + 5 " on entering usefield" ); 57 x *= 10; 58 outputarea.append( "\nfield x is " + x + 59 " on exiting usefield" ); 0 1 } // end method useinstance 2 3 } // end class Scoping 21 Scoping.java Lines 53-1 Method usefield Method usefield uses field x uses field x Methods of Class JApplet Java API defines several JApplet methods Defining methods of Fig..11 in a JApplet is called overriding those methods. 22 Method init() start() paint( Graphics g ) When the method is called and its purpose This method is called once by the applet container when an applet is loaded for execution. It performs initialization of an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 19, Multimedia) and creating threads (see Chapter 1, Multithreading). This method is called after the init method completes execution. In addition, if the browser user visits another Web site and later returns to the HTML page on which the applet resides, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the HTML page on which the applet resides is revisited. Typical actions performed here include starting an animation (see Chapter 19) and starting other threads of execution (see Chapter 1). This drawing method is called after the init method completes execution and the start method has started. It is also called every time the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container. 23 Method Overloading Method overloading Several methods of the same name Different parameter set for each method Number of parameters Parameter types 2 stop() destroy() This method is called when the applet should stop executing normally, when the user of the browser leaves the HTML page on which the applet resides. The method performs any tasks that are required to suspend the applet s execution. Typical actions performed here are to stop execution of animations and threads. This method is called when the applet is being removed from memory normally, when the user of the browser exits the browsing session (i.e., closes all browser windows). The method performs any tasks that are required to destroy resources allocated to the applet. Fig..11 JApplet methods that the applet container calls during an applet s execution.

1 // Fig..12: MethodOverload.java 2 // Using overloaded methods 3 import java.awt.container; 5 import javax.swing.*; 7 public class MethodOverload extends JApplet { 8 9 // create GUI and call each square method 10 init() 11 { 12 JTextArea outputarea = new JTextArea(); 13 Container container = getcontentpane(); 1 container.add( outputarea ); 15 1 outputarea.settext( "The square of integer 7 is " + square( 7 ) + 17 "\nthe square of double 7.5 is " + square( 7.5 ) ); 18 19 } // end method init 20 Method square receives an 21 // square method with int argument int as an argument 22 public int square( int intvalue ) 23 { 2 System.out.println( "Called square with int argument: " + 25 intvalue ); 2 27 return intvalue * intvalue; 28 29 } // end method square with int argument 30 25 MethodOverload. java Lines 22-29 Method square receives an int as an argument 31 // square method with double argument 32 public double square( double doublevalue ) 33 { 3 System.out.println( "Called square with double argument: " + 35 doublevalue ); 3 37 return doublevalue * doublevalue; 38 39 } // end method square with double argument 0 1 } // end class MethodOverload Called square with int argument: 7 Called square with double argument: 7.5 2 MethodOverload. java Lines 32-39 Overloaded method Overloaded method square square receives a receives a double as an argument double as an argument 1 // Fig..13: MethodOverload.java 2 // Overloaded methods with identical signatures. 3 import javax.swing.japplet; 5 public class MethodOverload extends JApplet { 7 // declaration of method square with int argument 8 public int square( int x ) Lines 8 and 15 9 { Compiler cannot distinguish between Compiler cannot 10 return x * x; 11 } methods with identical names and 12 parameter sets 13 // second declaration of method square 1 // with int argument causes syntax error 15 public double square( int y ) 1 { 17 return y * y; 18 } 19 20 } // end class MethodOverload MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^ 1 error 27 MethodOverload. java distinguish between methods with identical names and parameter sets Fig..17 Compiler error messages generated from overloaded methods with identical parameter lists and different return types. Recursion Recursive method Calls itself (directly or indirectly) through another method Method knows how to solve only a base case Method divides problem Base case Simpler problem Method now divides simpler problem until solvable Recursive call Recursive step 28 29 1 // Fig..15: FactorialTest.java 2 // Recursive factorial method. 30 5! 5! Final value = 120 5! = 5 * 2 = 120 is returned 3 import java.awt.*; 5 import javax.swing.*; FactorialTest.j ava 5 *! * 3! 5 *!! = * = 2 is returned * 3! 3! = 3 * 2 = is returned 7 public class FactorialTest extends JApplet { 8 JTextArea outputarea; 9 10 // create GUI and calculate factorials of 0-10 11 init() 12 { Line 21 Invoke method factorial 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 13 outputarea = new JTextArea(); 1 Invoke method factorial 15 Container container = getcontentpane(); 2 * 1! 1 2 * 1! 1 1 returned 1 container.add( outputarea ); 17 18 // calculate the factorials of 0 through 10 19 for ( long counter = 0; counter <= 10; counter++ ) 20 outputarea.append( counter + "! = " + (a) Sequence of recursive calls. (b) Values returned from each recursive call. 21 factorial( counter ) + "\n" ); 22 23 } // end method init 2 Recursive evaluation of 5!.

25 // recursive declaration of method factorial 2 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return 1; 31 32 // recursive step 33 else 3 return number * factorial( number - 1 ); 35 3 } // end method factorial 37 38 } // end class FactorialTest Test for base case (method factorial can solve base case) 31 FactorialTest.j ava Lines 29-30 Else return simpler Test problem for base that case method factorial (method might solve factorial in next recursive can call solve base case) Line 3 Else return simpler problem that method factorial might solve in next recursive call Example Using Recursion: The Fibonacci Series Fibonacci series Each number in the series is sum of two previous numbers e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21 fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci( n 1 ) fibonacci(0) and fibonacci(1) are base cases Golden ratio (golden mean) 32 1 // recursive declaration of method fibonacci 2 public long fibonacci( long n ) 3 { // base case 5 if ( n == 0 n == 1 ) return n; Test for base case (method fibonacci can solve base case) 33 FibonacciTest.j ava fibonacci( 3 ) 3 7 8 // recursive step 9 else 70 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 71 72 } // end method fibonacci 73 7 } // end class FibonacciTest Else return simpler problem Lines 5- that method fibonaccitest might for solve base case in next recursive (method call fibonacci can solve base case) Lines 9-70 Else return simpler problem that method fibonacci might solve in next recursive call return return fibonacci( 2 ) + fibonacci( 1 ) fibonacci( 1 ) + fibonacci( 0 ) return 1 return 1 return 0 Set of recursive calls for fibonacci (3). Recursion vs. Iteration 35 Recursion vs. Iteration (cont.) 3 Iteration Uses repetition structures (for, while or do while) Repetition through explicitly use of repetition structure Terminates when loop-continuation condition fails Controls repetition by using a counter Recursion Uses selection structures (if, if else or switch) Repetition through repeated method calls Terminates when base case is satisfied Controls repetition by dividing problem into simpler one Recursion More overhead than iteration More memory intensive than iteration Can also be solved iteratively Often can be implemented with only a few lines of code