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

Similar documents
Functions. Lecture 6 COP 3014 Spring February 11, 2018

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

Object Oriented Methods : Deeper Look Lecture Three

Lecture 5: Methods CS2301

CS-201 Introduction to Programming with Java

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

Lecture 04 FUNCTIONS AND ARRAYS

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

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

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 7 User-Defined Methods. Chapter Objectives

CT 229 Java Syntax Continued

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

6.096 Introduction to C++

Introduction to Programming Using Java (98-388)

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Methods. Bok, Jong Soon

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

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

Chapter 4. Defining Classes I

CS-201 Introduction to Programming with Java


User Defined Functions

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

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

Unit 7. Functions. Need of User Defined Functions

Chapter 3 Function Overloading

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

Lecture Set 4: More About Methods and More About Operators

Methods CSC 121 Fall 2016 Howard Rosenthal

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

CS110: PROGRAMMING LANGUAGE I

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

CS110D: PROGRAMMING LANGUAGE I

Methods: A Deeper Look

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

EECS168 Exam 3 Review

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

Lexical Considerations

1 Lexical Considerations

Full file at

This page intentionally left blank

Lecture 5 Tao Wang 1

Chapter 6 Methods. Dr. Hikmat Jaber

STUDENT LESSON A12 Iterations

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CSE 230 Intermediate Programming in C and C++ Functions

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

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

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

Methods. CSE 114, Computer Science 1 Stony Brook University

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

CS111: PROGRAMMING LANGUAGE II

Methods with Parameters and Return Values

Methods CSC 121 Spring 2017 Howard Rosenthal

C Programming for Engineers Functions

Lab Instructor : Jean Lai

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

Java Bytecode (binary file)

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

Object-Oriented Programming and Software Engineering CITS1001 MID-SEMESTER TEST

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

A Foundation for Programming

Flow Control. CSC215 Lecture

Methods CSC 121 Fall 2014 Howard Rosenthal

CS115 Principles of Computer Science

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

Defining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1

Lecture 18 Tao Wang 1

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

Chapter 4 Defining Classes I

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Top-down programming design

YOLOP Language Reference Manual

M.CS201 Programming language

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

Introduction to Programming

Lexical Considerations

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Pace University. Fundamental Concepts of CS121 1

Lecture 04 FUNCTIONS AND ARRAYS

Chapter 3. Selections

Lecture Set 4: More About Methods and More About Operators

Variables, Types, Operations on Numbers

C++ Programming: From Problem Analysis to Program Design, Third Edition

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Fundamental Concepts and Definitions

Programming with Java

Chapter 10 Introduction to Classes

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)

Language Fundamentals

Transcription:

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

Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method is a function that belongs to a class. In Java, every function belongs to a class. A function is a reusable portion of a program, sometimes called a procedure or subroutine. The properties of a method are: It is like a mini-program (or subprogram) in its own right. Can take in special inputs (arguments). Can produce an answer value (return value). Similar to the idea of a function in mathematics.

Why write and use functions? Divide-and-conquer Breaking up programs and algorithms into smaller, more manageable pieces This makes for easier writing, testing, and debugging Also easier to break up the work for team development Reusability Functions can be called to do their tasks anywhere in a program, as many times as needed Avoids repetition of code in a program Functions can be placed into libraries to be used by more than one program With methods (functions), there are 2 major points of view Builder of the method responsible for creating the declaration and the definition of the method (i.e. how it works) Caller somebody (i.e. some portion of code) that uses the method to perform a task

Using Methods The user of a method is the caller. Use a method by making calls to the method with real data, and getting back real answers. Consider a typical function from mathematics: f(x) = 2x + 5 In mathematics, the symbol x is a placeholder, and when you run the function for a value, you plug in the value in place of x. Consider the following equation, which we then simplify: y = f(10) // must evaluate f(10) y = 2 * 10 + 5 // plug in 10 for x y = 20 + 5 y = 25 // so f(10) results in 25 In programming, we would say that the call f(10) returns the value 25.

Using Methods Java methods work in largely the same way. General format of a Java method call: methodname(argumentlist) The argumentlist is a comma-separated list of arguments (data being sent into the method). Use the call anywhere that the returned answer would make sense. When calling a Java method from another class library, we have to precede the call with the object name or the class name, depending on whether the method is static or not: classname.methodname(argumentlist) // for static methods objectname.methodname(argumentlist) // for instance methods If a method is a member of the same class from which it is called from, there is no need for a dot-operator on the call.

Example There is a pre-defined Math class method called sqrt, which takes one input value (of type double) and returns its square root. Sample calls: double x = 9.0, y = 16.0, z; z = Math.sqrt(36.0); //returns 6.0 (stored in z) z = Math.sqrt(x); //returns 3.0 (stored in z) z = Math.sqrt(x + y); //returns 5.0(stored in z) System.out.print(Math.sqrt(100.0)); //returns 10.0, which gets printed System.out.print(Math.sqrt(49)); //due to automatic type conversion rules System.out.print( Math.sqrt(Math.sqrt(625.0)));

A special use of import for static methods There is a special use of the keyword static for use in import statements. On an import statement, a programmer can import the static methods of a class, so that the class name and dot-operator does not have to be used in subsequent calls in the file. For example, suppose we do this statement in our file: import static java.lang.math.sqrt; The above would mean that anywhere in the file we call the sqrt method, it s specifically the one from the Math class. In this case, we would not need to use the Math. syntax before each call.

A special use of import for static methods To import all static methods from a class this way, use the * wildcard character. For example: import static java.lang.math.*; // import all static methods from Math It s best to use this sparingly. If a code file is using multiple libraries, it can get confusing what class different method calls are coming from, especially if multiple classes have similarly named methods.

Building Methods The builder of a method (a programmer) is responsible for the prototype (or signature) of a method, as well as the definition (i.e. how it works) The structure of a method: modifier(s) returntype methodname(parameter list) // this is the signature { // method body (i.e. what it does, how it works) -- the definition }

Building Methods The pieces: methodname - identifier chosen by the builder. parameter list - a comma-separated list of the parameters that the method will receive. This is data passed IN to the method by the caller. The parameter list indicates the types, order, and number of parameters. returntype - the data type of the value returned by the method. A method that returns no value should have return type void. modifier(s) - optional labels that can specify certain properties or restrictions on the method. For now, we will use the modifier static on our methods. method body - code statements that make up the definition of the method and describe what the method does, how it works.

Returning values To return a value (from the body of a method with a non-void return type), use the keyword return, followed by an expression that matches the expected return type: return expression; A return statement will force immediate exit from the method, and it will return the value of the expression to the caller. A method with a non-void return type needs to return an appropriate value.

Method Examples Here are two simple methods that do a math calculation and return a result public static int sum(int x, int y, int z) // add the 3 parameters and return the result { int answer; answer = x + y + z; return answer; } public static double average (double a, double b, double c) //add parameters, divide by 3, return the result { return (a + b + c) / 3.0; }

More Examples More than one return statement may appear in a function definition, but the first one to execute will force immediate exit from the function. boolean InOrder(int x, int y, int z) // answers yes/no to the question "are these parameters in order, // smallest to largest?" Returns true for yes, false for no. { if (x <= y && y <= z) return true; else return false; }

Some common mistakes Examples of ILLEGAL syntax (common mistakes to watch out for): double average(double x, y, z){ } // Each parameter must list a type printdata(int x){ } // missing return type int double Task(int x) { } // only one return type allowed!

Scope of Identifiers The scope of an identifier (i.e. variable) is the portion of the code where it is valid and usable A variable declared within a block (i.e. a compound statement) of normal executable code has scope only within that block. Includes method bodies Includes other blocks nested inside methods (like loops, if-statements, etc) Does not include some special uses of block notation to be seen later (like the declaration of a class which will have a separate scope issue) Variables declared in the formal parameter list of a method definition have scope only within that method. These are considered local variables to the method. Variables declared completely inside the method body (i.e. the block) are also local variables.

void methods and empty parameter lists Parameter lists Mathematical functions must have 1 or more parameters Java methods can have 0 or more parameters To define a method with no parameters, leave the parentheses empty Same goes for the call. (But parintheses must be present, to identify it as a method call). Return types A mathematical function must return exactly 1 answer A Java method can return 0 or 1 return value To declare a method that returns no answer, use void as the return type A void method can still use the keyword return inside, but not with an expression (only by itself). One might do this to force early exit from a method. To CALL a void method, call it by itself do NOT put it in the middle of any other statement or expression

Sample Prototype Here are some sample method prototypes: char getaletter() // no parameters void printquotient(int x, int y) // void return type void killsometime() // both

Functions and the compiler The compiler will check all method CALLS to make sure they match the expectations (which are described in the method signature) method name must match arguments passed in a call must match expected types and order returned value must not be used illegally static methods can be called through class name, but instance methods only through an object Decisions about parameters and returns are based on type-checking. legal automatic type conversions apply when passing arguments into a method, and when checking what is returned against the expected return type

Pass By Value Default mode of passing parameters into methods Means that the parameter inside the method body is a copy of the original argument that was passed in Changes to the local parameter only affect the local copy, not the original argument in the call static int mymethod(int x, int y) { x = x * 2; System.out.println("x = " + x); y = y * 2; System.out.println("y = " + y); return x + y; }

Pass by value Sample call: int a = 5, b = 8, ans; ans = mymethod(a, b); System.out.println("ans = " + ans); System.out.println("a = " + a); System.out.println("b = " + b); Notice that the output of the code is: x = 10 y = 16 ans = 26 a = 5 b = 8

Method Overloading The term method overloading refers to the fact that it is perfectly legal to have more than one method in the same class with the same name, as long as they have different parameter lists. The difference can be in the number of parameters, or in the types of parameters. Example: int process(double num) { } // method 1 int process(char letter) { } // method 2 int process(int num, int pos) { } //method 3

Method Overloading Notice that although all three methods above have the same exact name, they each have a different parameter list. Some of them differ in the number of parameters (2 parameters vs. 1 parameter), and the first two differ in types (double vs. char). The compiler will distinguish which function to invoke based on what is actually passed in when the function is called. x = process(3.45,12); //invokes the third function x = process( f ); // invokes the second function

Ambiguous Invocation Because of method overloading and the legality of some automatic type conversions, it is possible to make a call that could match two methods (due to the type conversion issue). This will result in a compiler error. Example: double sum(int x, double y); double sum(double x, int y); This pair of methods is legal, since the parameter lists differ. But the following is an illegal call, due to ambiguous invocation: System.out.print("The sum is " + sum(3, 4));