Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Similar documents
Chapter 7 User-Defined Methods. Chapter Objectives


CS212 Midterm. 1. Read the following code fragments and answer the questions.

Array. Prepared By - Rifat Shahriyar

Fundamentals of Programming Data Types & Methods

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

Introduction to Programming Using Java (98-388)

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

PROGRAMMING FUNDAMENTALS

Chapter 4: Control Structures I

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

Computer Science is...

Example: Monte Carlo Simulation 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Chapter 2: Basic Elements of Java

Question: Total Points: Score:

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

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

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Loops and Expression Types

Lecture 5: Methods CS2301

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Top-down programming design

( &% class MyClass { }

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

CMPT 125: Lecture 4 Conditionals and Loops

CSC Java Programming, Fall Java Data Types and Control Constructs

Arrays. Eng. Mohammed Abdualal

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

EECS168 Exam 3 Review

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

1 Lexical Considerations

Lexical Considerations

CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays

Methods. Bok, Jong Soon

CS171:Introduction to Computer Science II

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

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

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

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

Programming with Java

Anatomy of a Class Encapsulation Anatomy of a Method

Introduction to Programming (Java) 4/12

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

Example Program. public class ComputeArea {

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Getting started with Java

Full file at

Introduction to Software Development (ISD) Week 3

Lab Exercise 1. Objectives: Part 1. Introduction

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

Lexical Considerations

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Oct Decision Structures cont d

Methods and Functions

Introduction to Java. Handout-1d. cs402 - Spring

(a) Assume that in a certain country, tax is payable at the following rates:

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

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

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

CS-201 Introduction to Programming with Java

H212 Introduction to Software Systems Honors

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Declarations and Access Control SCJP tips

Selected Questions from by Nageshwara Rao

Chapter 4: Writing Classes

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

Chapter 4 Defining Classes I

Computational Expression

Methods. Eng. Mohammed Abdualal

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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 );

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Controls Structure for Repetition

Java Identifiers, Data Types & Variables

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

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

Final Exam COMP Fall 2004 Dec 16, 2004

Chapter 5: Classes and Objects in Depth. Introduction to methods

Handout 4 Conditionals. Boolean Expressions.

Flow Control. CSC215 Lecture

Static Methods. Why use methods?

Building Java Programs

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

Computer Applications Answer Key Class IX December 2017

Transcription:

Chapter 7: User-Defined Methods Java Programming: Program Design Including Data Structures Chapter Objectives Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined methods Examine value-returning methods, including actual and formal parameters Java Programming: Program Design Including Data Structures 2 Chapter Objectives (continued) Explore how to construct and use a value-returning, user-defined method in a program Learn how to construct and use user-defined void methods in a program Explore variables as parameters Learn about the scope of an identifier Become aware of method overloading Java Programming: Program Design Including Data Structures 3 1

Predefined Classes Methods already written and provided by Java Organized as a collection of classes (class libraries) Must import package Method type: The data type of the value returned by the method Java Programming: Program Design Including Data Structures 4 Predefined Classes (continued) Java Programming: Program Design Including Data Structures 5 Predefined Classes (continued) Java Programming: Program Design Including Data Structures 6 2

Predefined Classes (continued) Java Programming: Program Design Including Data Structures 7 class Character (Package: java.lang) Java Programming: Program Design Including Data Structures 8 class Character (Package: java.lang) (continued) Java Programming: Program Design Including Data Structures 9 3

Syntax of Value-Returning Method modifier(s) returntype methodname (formal parameter list) statements Java Programming: Program Design Including Data Structures 10 User-Defined Methods Value-returning methods: Used in expressions Calculate and return a value Can save value for later calculation or print value modifiers: public, private, protected, static, abstract, final. returntype: Type of the value that the method calculates and returns (using return statement) methodname: Java identifier; name of method Java Programming: Program Design Including Data Structures 11 Syntax Syntax of formal parameter list: datatype identifier, datatype identifier,... Syntax to call a value-returning method: methodname(actual parameter list) Java Programming: Program Design Including Data Structures 12 4

Syntax (continued) Syntax of the actual parameter list: expression or variable, expression or variable,... Syntax of the return statement: return expr; Java Programming: Program Design Including Data Structures 13 Equivalent Method Definitions public static double larger(double x, double y) double max; if (x >= y) max = x; else max = y; return max; Java Programming: Program Design Including Data Structures 14 Equivalent Method Definitions (continued) public static double larger(double x,double y) if (x >= y) return x; else return y; Java Programming: Program Design Including Data Structures 15 5

Equivalent Method Definitions (continued) public static double larger(double x, double y) if (x >= y) return x; return y; Java Programming: Program Design Including Data Structures 16 Programming Example: Palindrome Number Palindrome: An integer or string that reads the same forwards and backwards Input: Integer or string Output: Boolean message indicating whether integer string is a palindrome Java Programming: Program Design Including Data Structures 17 Solution: ispalindrome Method public static boolean ispalindrome(string str) int len = str.length(); int i, j; j = len - 1; for (i = 0; i <= (len - 1) / 2; i++) if (str.charat(i)!= str.charat(j)) return false; j--; return true; Java Programming: Program Design Including Data Structures 18 6

Sample Runs: Palindrome Java Programming: Program Design Including Data Structures 19 Sample Runs: Palindrome (continued) Java Programming: Program Design Including Data Structures 20 Flow of Execution Execution always begins with the first statement in the method main User-defined methods execute only when called Call to method transfers control from caller to called In the method call statement, specify only actual parameters, not data type or method type Control goes back to caller when method exits Java Programming: Program Design Including Data Structures 21 7

Programming Example: Largest Number Input: Set of 10 numbers Output: Largest of 10 numbers Solution: Get numbers one at a time Method largest number: Returns larger of 2 numbers For loop: Calls method largest number on each number received and compares to current largest number Java Programming: Program Design Including Data Structures 22 Solution: Largest Number static Scanner console = new Scanner(System.in); public static void main(string[] args) double num; double max; int count; System.out.println("Enter 10 numbers."); num = console.nextdouble(); max = num; for (count = 1; count < 10; count++) num = console.nextdouble(); max = larger(max, num); System.out.println("The largest number is " + max); Java Programming: Program Design Including Data Structures 23 Sample Run: Largest Number Sample Run: Enter 10 numbers: 10.5 56.34 73.3 42 22 67 88.55 26 62 11 The largest number is 88.55 Java Programming: Program Design Including Data Structures 24 8

Void Methods Similar in structure to value-returning methods Call to method is always stand-alone statement Can use return statement to exit method early Java Programming: Program Design Including Data Structures 25 Void Methods: Syntax Method definition: syntax of a void method without parameters: modifier(s) void methodname() statements Method call (within the class): use following syntax: methodname(); Java Programming: Program Design Including Data Structures 26 Void Methods with Parameters: Syntax Method definition: definition of a void method with parameters has the following syntax: modifier(s) void methodname (formal parameter list) statements Formal parameter list: following syntax: datatype variable, datatype variable,... Java Programming: Program Design Including Data Structures 27 9

Void Methods with Parameters: Syntax (continued) Method call: use the following syntax: methodname(actual parameter list); Actual parameter list: use the following syntax: expression or variable, expression or variable,... Java Programming: Program Design Including Data Structures 28 Primitive Data Type Variables as Parameters A formal parameter receives a copy of its corresponding actual parameter If a formal parameter is of a primitive data type Value of actual parameter is directly stored Cannot pass information outside the method Provides only a one-way link between actual parameters and formal parameters Java Programming: Program Design Including Data Structures 29 Reference Variables as Parameters If a formal parameter is a reference variable: Copies value of corresponding actual parameter Value of actual parameter is address of the object where actual data is stored Both formal and actual parameters refer to same object Java Programming: Program Design Including Data Structures 30 10

Uses of Reference Variables as Parameters Can return more than one value from a method Can change the value of the actual object When passing an address, saves memory space and time, relative to copying large amount of data Java Programming: Program Design Including Data Structures 31 Reference Variables as Parameters: type String Java Programming: Program Design Including Data Structures 32 Scope of an Identifier within a Class Local identifier: declared in a method or block; visible only in that method or block Cannot nest methods: cannot include the definition of one method in the body of another method An identifier must be declared before it can be used A method s definition can contain several blocks Within a class, outside of every method definition (and block), an identifier can be declared anywhere Java Programming: Program Design Including Data Structures 33 11

Scope of an Identifier within a Class In a method, an identifier that is used to name a variable in the outer block of the method cannot be used to name any other variable in an inner block of the method. Second declaration of the variable x is illegal: public static void illegalidentifierdeclaration() int x; //block double x;... //illegal declaration, //x is already declared Java Programming: Program Design Including Data Structures 34 Scope Rules Scope rules of an identifier declared within a class and accessed within a method (block) of the class An identifier, say X, declared within a method (block) is accessible: Only within the block from the point at which it is declared until the end of the block By those blocks that are nested within that block Java Programming: Program Design Including Data Structures 35 Scope Rules (continued) Suppose X is declared within a class and outside of every method s definition (block) If X is declared without static (e.g., a named constant or a method name), then it cannot be accessed in a static method If X is declared with static (e.g., a named constant or a method name), then it can be accessed within a method (block) provided the method (block) does not have any other identifier named X Java Programming: Program Design Including Data Structures 36 12

Scope Rules (continued) Example 7-12 public class ScopeRules static final double rate = 10.50; static int z; static double t; public static void main(string[] args) int num; double x, z; char ch; //... public static void one(int x, char y) //... Java Programming: Program Design Including Data Structures 37 Scope Rules (continued) public static int w; public static void two(int one, int z) char ch; int a; //block three int x = 12; //... //end block three //... Java Programming: Program Design Including Data Structures 38 Scope Rules: Demonstrated Java Programming: Program Design Including Data Structures 39 13

Method Overloading: An Introduction Method overloading: More than one method can have the same name Two methods are said to have different formal parameter lists: If methods have a different number of parameters If the number of formal parameters is the same in both methods, the data type of the formal parameters in the order you list must differ in at least one position Java Programming: Program Design Including Data Structures 40 Method Overloading public void methodone(int x) public void methodtwo(int x, double y) public void methodthree(double y, int x) public int methodfour(char ch, int x, double y) public int methodfive(char ch, int x, String name) These methods all have different formal parameter lists Java Programming: Program Design Including Data Structures 41 Method Overloading (continued) public void methodsix(int x, double y, char ch) public void methodseven(int one, double u, char firstch) methodsix and methodseven both have three formal parameters, and the data type of the corresponding parameters is the same These methods have the same formal parameter lists Java Programming: Program Design Including Data Structures 42 14

Method Overloading (continued) Method overloading: Creating several methods within a class with the same name The signature of a method: name and formal parameter list Two methods have different signatures if they have either different names or different formal parameters Signature does not include the return type Java Programming: Program Design Including Data Structures 43 Method Overloading (continued) The following method headings correctly overload the method methodxyz: public void methodxyz() public void methodxyz(int x, double y) public void methodxyz(double one, int y) public void methodxyz(int x, double y, char ch) Java Programming: Program Design Including Data Structures 44 Method Overloading (continued) public void methodabc(int x, double y) public int methodabc(int x, double y) These method headings have the same name and same formal parameter list Incorrect overloading Compiler generates a syntax error, even though return types are different Java Programming: Program Design Including Data Structures 45 15

Programming Example: Data Comparison Input: Data from two different files Data format: Course number followed by scores Output: Course number, group number, course average Solution: Read from more than one file; write output to file Generate bar graphs User-defined methods and re-use (calculateaverage and printresult) Parameter passing Java Programming: Program Design Including Data Structures 46 Programming Example: Data Comparison (continued) Sample Output Course No Group No Course Average CSC 1 83.71 2 80.82 ENG 1 82.00 2 78.20 HIS 1 77.69 2 84.15 MTH 1 83.57 2 84.29 PHY 1 83.22 2 82.60 Avg for group 1: 82.04 Avg for group 2: 82.01 Java Programming: Program Design Including Data Structures 47 Programming Example: Data Comparison (continued) Java Programming: Program Design Including Data Structures 48 16

Chapter Summary Pre-defined methods User-defined methods: Value-returning methods Void methods Formal parameters Actual parameters Flow of execution Java Programming: Program Design Including Data Structures 49 Chapter Summary (continued) Primitive data type variables as parameters: One-way link between actual parameters and formal parameters (limitations caused) Reference variables as parameters: Can pass one or more variables from a method Can change value of actual parameter Scope of an identifier within a class Method overloading Java Programming: Program Design Including Data Structures 50 17