CS-201 Introduction to Programming with Java

Similar documents
CS-201 Introduction to Programming with Java

Lecture 5: Methods CS2301

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

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

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

Methods. CSE 114, Computer Science 1 Stony Brook University

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

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

Chapter 6 Methods. Dr. Hikmat Jaber

CS110: PROGRAMMING LANGUAGE I

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

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

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

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

JAVA Programming Concepts

CS115 Principles of Computer Science

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

Introduction to Programming (Java) 4/12

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

CS171:Introduction to Computer Science II

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

Object Oriented Methods : Deeper Look Lecture Three

Chapter 5 Methods / Functions

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

CS110D: PROGRAMMING LANGUAGE I

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

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

Lecture #6-7 Methods

Benefits of Methods. Chapter 5 Methods

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

Introduction to Programming Using Java (98-388)

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

AP Computer Science Unit 1. Programs

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

Lecture Set 4: More About Methods and More About Operators

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

User Defined Functions

A Foundation for Programming

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods

Chapter 4. Defining Classes I

CS-202 Introduction to Object Oriented Programming

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Lecture Set 4: More About Methods and More About Operators

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

BM214E Object Oriented Programming Lecture 4

( &% class MyClass { }

Advanced Computer Programming

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)

Lecture 3. Lecture

Computational Expression

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

Static Methods. Why use methods?

Chapter 7 User-Defined Methods. Chapter Objectives

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

CS111: PROGRAMMING LANGUAGE II

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Chapter 4. Defining Classes I

CS 101 Spring 2007 Midterm 2 Name: ID:

Data Conversion & Scanner Class

Methods CSC 121 Fall 2016 Howard Rosenthal

Chapter 3 Function Overloading

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

Chapter 1. Section 1.4 Subprograms or functions. CS 50 - Hathairat Rattanasook

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Programming Exercise 7: Static Methods

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Unit 7. Functions. Need of User Defined Functions

RECOMMENDATION. Don't Write Entire Programs Unless You Want To Spend 3-10 Times As Long Doing Labs! Write 1 Function - Test That Function!

Class, Variable, Constructor, Object, Method Questions

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

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

CS 112 Introduction to Programming

CS 112 Introduction to Programming

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

Names, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

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

COP 3330 Final Exam Review

This exam is open book. Each question is worth 3 points.

Names, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University

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.

Methods CSC 121 Spring 2017 Howard Rosenthal

CS 200 Using Objects. Jim Williams, PhD

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

Final Examination Semester 3 / Year 2012

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

Methods. Eng. Mohammed Abdualal

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 1 Getting Started

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

The return Statement

CS 149. Professor: Alvin Chao

Software and Programming 1

Chapter 2 Elementary Programming

EXPRESSIONS AND ASSIGNMENT CITS1001

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Transcription:

CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture X: Methods II

Passing Arguments

Passing Arguments methods can accept outside information input to the method always provided by the calling method makes methods reusable since you can use the same method with different sets of data. outside information is passed as arguments to the parameters of the method.

Passing Arguments Recall: arguments are the actual values passed in the method call. parameters are the place holder variables in the method definition. Example: if I have a method with a header of: public static void mymethod(int x, double y, String s) and I call the method using mymethod(5, 12.6, "Java"); x, y, and s are the parameters 5, 12.6, and "Java" are the arguments passed to the parameters

Passing Arguments If a method header has parameters: you MUST pass arguments to the method call. if a method has no parameters: you CANNOT pass arguments to the method call. you MUST still include an empty set of parenthesis. Example: Math.pow(a, b) is method where you are required to pass two arguments, a base and an exponent. nextint() of the Scanner class is a method were you CANNOT pass arguments, but the empty ( ) are still required.

Passing Arguments parameter order association: arguments passed to parameters MUST: be passed in the correct order have the exact number of arguments (no more or no less than what the method defines) match the parameters based on compatible types Compatible type: you can pass an argument to a parameter without explicit casting i.e. passing an int value to a double value parameter is ok, but the reverse would not be.

Passing Arguments public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nprintln( Welcome to Java, 5); What is the output? Suppose you invoke the method using nprintln( Computer Science, 15); What is the output?

Passing Values a copy of the VALUE of the argument is passed to the parameter: not the actual variable...but the VALUE changes made to a value inside a method will not affect the value outside of the method. primitives pass their values. Code Examples: Increment.java TestPassByValue.java

Passing Arguments by Values

Modularizing Code

Modularizing Code modularizing code: large amounts of code can be broken down into smaller "modules", each of which could function on its own and be reused over and over again. makes code easier to maintain and debug: instead of focusing on the program as a whole, now you can focus on and test only one small portion of the overall program. by testing methods one at a time, you can eliminate bugs much faster, than if you were to write a whole program and then test it.

Modularizing Code methods give you some advantages: the code inside the method is isolated from the rest of the code in the program. program logic becomes clear and the program is much easier to read any errors which occur in a method will be contained in that method, which narrows the scope of debugging (you don't have to look all over the place for the bug you can just go to the specific method). See Code: PrimeNumberNoMethods.java PrimeNumberMethod.java

Overloading Methods

Overloading Methods What if we want to define multiple methods which accepts parameters of different types and performs the same function? Eg. max(int, int) only works with integers. What if we need to determine which of two floating-point numbers has the maximum value? Solutions Define maxdouble(double, double) define a new method with a different name not so great because then you have to remember the exact method name for all variations of the parameter lists. Define overloaded methods This way is better

Overloading Methods method overloading: define two or more methods with the same name but different parameter lists. different parameter lists means: having a different number of parameters or having parameters with different data types. Example: public public public public static static static static int max(int x, int y) double max(double x, double y) double max(int x, double y) int max(int x, int y, int z)

Overloading Methods Compiler decides which method to use by matching the calling method's argument list to one of the overloaded method's parameter lists the compiler will always try to choose the best match (if one exists). Example: A. public B. public C. public D. public static static static static int max(int x, int y) double max(double x, double y) double max(int x, double y) int max(int x, int y, int z) max(2, 3) matches method A max(10.5, 11.5) matches method B max(7, 13.2) matches method C max(45, 23, 56) matches method D

Overloading Methods Differences in return type are irrelevant in method overloading Overloaded methods can have different return types Methods with different return types but the same signature cause a compilation error Different modifiers are irrelevant in method overloading public and static are modifiers THE ONLY PART OF A METHOD THAT IS CONSIDERED WHEN OVERLOADING IS THE METHOD SIGNATURE (METHOD NAME AND PARAMETER LIST)

Overloading Methods See Code: TestMethodOverloading.java Can you do max(2, 2, 5)? If so, which of the max methods is invoked? If the definition of max(int, int) is deleted, will the problem still work? Why is the method max(double, double) not invoked for the call max(3,4)?

Ambiguous Invocation What happens if there are two or more possible matches for an invocation of a method? Will the compiler make an arbitrary choice? How does the compiler choose? Answer: The compiler cannot decide for itself which to use, so this will trigger a compile error. This is called ambiguous invocation.

Ambiguous Invocation public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } }

Ambiguous Invocation Suppose you already defined a method public static int mymethod(int n1, int n2, double n3) Which of the following overloaded methods can be defined in the same class? public static int mymethod(int p1, int p2, double p3) public static int mymethod(double n1, int n2, int n3) public static double mymethod(int n1, int n2, double n3) public static int mymethod(int n1, int n2) public static double mymethod(int n1, int n2, int n3)