Lecture #6-7 Methods

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

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter 6 Methods. Dr. Hikmat Jaber

JAVA Programming Concepts

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

CS110: PROGRAMMING LANGUAGE I

Lecture 5: Methods CS2301

Chapter 5 Methods / Functions

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

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

CS115 Principles of Computer Science

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

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

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Benefits of Methods. Chapter 5 Methods

CS110D: PROGRAMMING LANGUAGE I

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CS1150 Principles of Computer Science Methods

CS-201 Introduction to Programming with Java

Introduction to Programming (Java) 4/12

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Methods. CSE 114, Computer Science 1 Stony Brook University

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

CS1150 Principles of Computer Science Methods

CS-201 Introduction to Programming with Java

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

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

CS111: PROGRAMMING LANGUAGE II

Methods. Eng. Mohammed Abdualal

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

The return Statement

A Foundation for Programming

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Zheng-Liang Lu Java Programming 45 / 79

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

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

Lecture Set 4: More About Methods and More About Operators

Computer Science II (20082) Week 1: Review and Inheritance

Module 4: Characters, Strings, and Mathematical Functions

Computer Science 1 Ah

Top-down programming design

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Object Oriented Methods : Deeper Look Lecture Three

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Lecture Set 4: More About Methods and More About Operators

Java Memory Management

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

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

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Handout 7. Defining Classes part 1. Instance variables and instance methods.

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

M e t h o d s a n d P a r a m e t e r s

AP CS Unit 3: Control Structures Notes

Anatomy of a Class Encapsulation Anatomy of a Method

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Programming Language Concepts: Lecture 2

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

More types, Methods, Conditionals. ARCS Lab.

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

CS111: PROGRAMMING LANGUAGE II

Introduction to Programming Using Java (98-388)

Contents. 8-1 Copyright (c) N. Afshartous

Lecture 10 Declarations and Scope

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Types, Values and Variables (Chapter 4, JLS)

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Research Group. 2: More types, Methods, Conditionals

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Condi(onals and Loops

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Chapter 4 Mathematical Functions, Characters, and Strings

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Object Oriented Modeling

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

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

CS171:Introduction to Computer Science II

1.1 Your First Program

Java Identifiers, Data Types & Variables

Computer Science II (20073) Week 1: Review and Inheritance

CS 335 Java Programming Controls. Fall 2007

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Transcription:

Lecture #6-7 s 1. a. group of statements designed to perform a specific function b. may be reused many times i. in a particular program or ii. in multiple programs 2. Examples from the Java Library a. System.out.println() b. JOptionPane.showMessageDialog() c. Integer.parseInt() d. Math.random() 3. Defining a modifiers return type parameters (formal placeholders) public static int max( int n1, int n2) int result; block of code constitutes the method body return statement required for non-void methods Remark: s are defined outside of the main() program! 4. Invoking, i.e., calling, a public static void main( String [ ]args ) int x, y; input values for x & y; int z = max(x, y); values of the actual parameters, i.e., arguments output the z value; Remark: s are called inside of the main() program!

5. Return Types a. Void s -- public static void main( String [ ]args ) b. Value Returning s Math.random, public static int max( int, int) Remark: return statement is required for value-returning method 6. Formal Parameters parameters (formal placeholders) parameter list type, order, number of parameters Signature: Header: int max( int, int); i.e., method name + parameter list public static int max( int, int) Remark: Each data type in the parameter list must be separately declared, i.e., public static int max( int n1, int n2) not public static int max( int n1, n2) 7. Alternative Names for s a. Value-Returning Function b. Void Procedure 8. Calling a -- Revisited a. Value-Returning Function If the method returns a value, the call to the method is usually treated as a value, e.g., int z = max(x, y); However, it is permissible to call value-returning method as a statement, if the return value is of no interest to the calling program. b. Void Procedure If the method returns a void, the call must be in the form of a statement, e.g., System.out.println( This is the correct way );

9. Placement of s If the method is to be used only in the current program, then place it in the same class, i.e., file, as the program, e.g., public class TestMax public static void main(string [ ] args) int i = 5; int j = 2; int k = max(i, j); System.out.println( Max of + i + and + j + : +k); public static int max( int n1, int n2) int result; If the method is to be used in other programs, place it in another class, i.e., file, with a different descriptive name. For instance place the method, public static void main( String [ ]args ) int x, y; input values for x & y; int z = max(x, y); output the z value; in a class, i.e., file, MyMathStuff; the method call then be invoked by any other program in your account as int z = MyMathStuff.max(x, y);

10. Call Stacks A stack is, simply, an area of memory in which information is stored and retrieved in a last-in, first-out, i.e., FIFO, manner. The storage of dinner plates is normally accomplished by placing one plate on top of another. In this case, the set of plates are usually treated as a stack, i.e., a clean plate is placed on the top of the stack and when a plate is required for service, it is the plate on the top of the stack which is retrieved. It is the FIFO action and the storage structure which constitutes a stack. When a method is called, the execution of the calling program must be suspended, and the called method is allowed to execute. When any method is called, including the main method, the stack allocates an area at the top of the stack to store information relevant to that method. Thus as each executing method calls another method, the stack allocates additional area at the top of the stack for that method. The area allocated to each method is often referred to as a frame and common terminology is that a frame is pushed onto the stack. When a method finishes executing, execution returns to the calling method and the area reserved for the completed method is deallocated, i.e., the frame is popped off the stack, or the stack is popped. Max result: _ n1: 2 n2: 5 Max result: 5 n1: 2 n2: 5 Stack Pointers k: _ k: _ k: _ k: 5 Empty Stack Diagram Liang page 145

11. Void public class VoidTest public static void main(string [ ] args) double numbergrade; input value for numbergrade System.out.print( Number Grade: + numbergrade + \tletter Grade: ); printgrade(numbergrade); public static void printgrade( double Score) if ((score < 0) (score > 100)) System.out.println( Invalid Score ); return; if (score >= 90.0) System.out.println( A ); else if (score >= 80.0) System.out.println( B ); else if (score >= 70.0) System.out.println( C ); else if (score >= 60.0) System.out.println( D ); else System.out.println( F ); 12. Passing Parameters a. Parameter Order Association Pattern Matching The arguments provided to a called method MUST be in the same order, be of a compatible type and, unless otherwise specified, be of the same number as that of the method s definition. Compatible type means passing without explicit casting! Given the method definition public static void nprintmessage(string message, int n) for (int i = 0; i < n; i++) System.out.println(message); the calling statement nprintmessage(v, w); is valid only if v is of type String and w is of type int. The statement nprintmessage(15, hello ); will fail!

b. Pass-by-Value public class Increment public static void main(string [ ] args) int x = 1; System.out.println(x); increment(x); System.out.println(x); public static void increment(int n) n++; System.out.println(n); Output: 1, 2, 1 swap(n1, n2) int temp = n1; n1 = n2; n2 = temp; Swap n1: 2 n2: 5 Max n1: 5 n2: 2 Stack Pointers Empty Stack

13. Modular Code a. Reduce redundant code b. Enable the reuse of code c. Improve program quality public static int gcd(int n1, int n2) int gcd = 1; int k = 2; while( k <= n1 && k <= n2) if( n1 % k == 0 && n2 % k == 0) gcd = k; k++; return gcd; public static boolean isprime(int n) for( divisor = 2; divisor <= n/2; divisor++) if( n % divisor == 0) return false; return true;

14. Overloading s public static int max( int n1, int n2) int result; public static double max( double n1, double n2) double result; public static long max( long n1, long n2) long result; public static float max( float n1, float n2) float result; public static char max( charn1, char n2) char result;

public static double max( double n1, double n2, double n3) return max(max(n1, n2), n3); double x = max(3, 3.5); invokes double x = max(3, 5); invokes double max( double, double) int max( int, int) 15. Ambiguous Overloads compiler cannot determine which of two or more possible matches should be used for an invocation of a method. For example, given public static double max( int n1, double n2) double result; public static double max( double n1, int n2) double result; Overloaded methods should be defined in such a manner that such ambiguities cannot occur! Ambiguous overloads result in compiler errors! 16. Scope of Variables The scope of a particular variable is the part of the program where the variable can be referenced. A variable defined inside of a method is referred to as a LOCAL variable. In the method below, n is a local variable with a scope limited by the enclosing block; n cannot be referenced outside of the block! public static void increment(int n) n++; Scope of the variable n System.out.println(n);

Scope of the variable j public static void increment(int n) n++; System.out.println(n); int j = 1; n++; System.out.println(n + j++); Scope of the variable n 17. Math Class http://java.sun.com/javase/6/docs/api/index.html a. Math.PI b. Math.E see Liang pages 154-157 for complete list c. public static double ceil(double x) // rounded up to nearest neighbor // ceil(4.1) 5.0 d. public static double floor(double x) // rounded down to nearest neighbor // floor(4.9) 4.0 e. public static double rint(double x) // rounded to nearest neighbor, if equally close, rounded to the even number, e.g., // rint(4.5) 4.0 // rint(5.5) 6.0 f. public static int round(float x) // returns (int)math.floor(x + 0.5) // (int)math.floor(4.4 + 0.5) (int)math.floor(4.9) 4 // (int)math.floor(4.5 + 0.5) (int)math.floor(5.0) 5 g. public static long round(double x) // returns (long)math.floor(x + 0.5) // (long)math.floor(4.4 + 0.5) (long)math.floor(4.9) 4 // (long)math.floor(4.5 + 0.5) (long)math.floor(5.0) 5

18. Random Numbers a. 0.0 Math.random() < 1.0 b. 0.0 Math.random() * 10 < 10.0 c. 0.0 Math.random() * 100 < 100.0 d. 15.0 15 + (Math.random() * 100) < 115.0 e. 0.0 Math.random() * (65535 +1) < 65536, i.e., generates all numbers in the range [000016, FFFF16] which encompasses the entire Unicode system. f. (char)( a + Math.random() * ( z a + 1)) generates all lower case characters g. (char)( A + Math.random() * ( Z A + 1)) generates all upper case characters h. (char)(ch1 + Math.random() * (ch2 ch1 + 1)) where ch1 < ch2 generates characters between ch1 & ch2 19. Abstraction & Stepwise Refinement Separate the Usage of a from its Implementation, i.e., the implementation details are encapsulated in the method and hidden from the user; the user does not need to know the implementation details to use the method. Header public -- users Body private implementers only!! E.g., System.out.print(); System.out.println(); Math.max(); JOptionPane.showInputDialog(); Page 159