Introduction to Methods

Slides:



Advertisements
Similar presentations
Procedural programming in Java
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Introduction to C++ Functions Chapter 6 Sections 6.1 – 6.3 Computer II.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CS0007: Introduction to Computer Programming Methods: Documentation, Reference Parameters, Modularization 2.
1 Fall 2009ACS-1903 Methods – Ch 5 A design technique referred to as stepwise refinement (or divide and conquer, or functional decomposition) is used to.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
CS 106 Introduction to Computer Science I 02 / 25 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 02 / 27 / 2008 Instructor: Michael Eckmann.
CS 201 Functions Debzani Deb.
Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University.
Topic 4 – Programmer- Defined Functions. CISC 105 – Topic 4 Functions So far, we have only seen programs with one function, main. These programs begin.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
CS0004: Introduction to Programming Subprocedures and Modular Design.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Methods CSCI 1301 What is a method? A method is a collection of statements that performs a specific task. Pre-Defined methods: available in Java library.
Chapter 5 : Methods. Why Write Methods?  Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Fundamentals Enumerations and Functions.
CS 106 Introduction to Computer Science I 10 / 10 / 2007 Instructor: Michael Eckmann.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Chapter 5 Methods. 2 Contents 1. Introduction to Methods 2. Passing Arguments to a Method 3. More about Local Variables 4. Returning a Value from a Method.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
by Tony Gaddis and Godfrey Muganda
CSCI 161: Introduction to Programming Function
Methods.
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
Chapter 6 Methods: A Deeper Look
Chapter 4 void Functions
6 Chapter Functions.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Topics Introduction to Functions Defining and Calling a Void Function
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Topics Introduction to Functions Defining and Calling a Function
Object Oriented Programming in java
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Java Methods: A Deeper Look Academic 2019 Class: BIT23/BCS10 Chapter 06 Abdulaziz Yasin Nageye Faculty of Computing Java How to Program, 10/e 1 © Co py.
Presentation transcript:

Introduction to Methods CS0007: Introduction to Computer Programming

Methods So far in this course we have seen methods in two ways: We’ve used predefined methods from the Java API: System.out.println Math.sqrt We have created a method named main in every program we’ve written. Now we will learn to create our own methods that can be used just like any from the Java API. So what are methods exactly? Methods are a collection of statements that perform a specific task. Why do we have methods? Methods break problems in smaller, more manageable, subproblems. Where have we seen this before? Hierarchy Charts!

Methods and Hierarchy Charts Postage Stamp Program Input Calculate Stamps Display Stamps Read Sheets Validate Sheets Set Stamps = Sheets/5 Round Stamps to the next whole number

Divide and Conquer and Modular Design Instead of writing one long method that contains all of the statements necessary to solve a problem, you can write several small methods that solve each specific part of the problem. This is what is known as divide and conquer approach to programming. When you use divide and conquer to design a program, this is known as Modular Design. As a result, each subproblem is known as a module. These modules can easily be implemented as their own methods! Programs that follow modular design principles have benefits: They are easier to write. They are easier to understand. They are easier to debug. They are easier to change. They have parts that can be reused. After learning about methods, you are required to design and implement your programs according modular design principles.

void Methods and Value-Returning Methods The reason why these structures are called methods is because they reside in classes. This is because in Java almost everything resides in a class. In other Non-Object-Oriented languages, we would call these structures functions and subprocedures, but instead we call them void methods and value-returning methods. void methods simply perform a task then terminate. value-returning methods not only perform a task, but also send a value back to the code that called it. For example: You can perform all output in a void method because it doesn’t require and result to be used. Math.sqrt returns a value back to where it was called (For instance, Math.sqrt(9) returns 3 to where it was called). Key terms: Call Return

Method Definition Before you can use a method you must define it. A method definition has two parts: Method header – appears at the beginning of the method definition and several important things about the method Method body – the collection of statements to be executed when the method is called. It is enclosed in curly braces. Again, we’ve seen this before: public static void main(String[] args) { ... }

Method Definition General form of a method: methodModifiers returnType name (parameterList) { body } methodModifiers – Keywords that define specific attributes about the method. returnType – If the method is value-returning the data type of the returned value goes here. If it is a void method, the keyword void goes here. name – Any valid identifier that will be used as the name of the method. Again, it should be descriptive of what the method does, and often should be a verb. parameterList – Methods are capable of receiving outside information called arguments. They are assigned to the method’s parameters. If the method does not receive any arguments, there is nothing inside of the parentheses. We will discuss arguments and parameters later.

Method Example public static void displayMessage(){ System.out.println("Hello from the displayMessage method!"); } public and static are method modifiers. In short public makes the method available for use outside of the class, and static means that it belongs to the class itself and not individual objects. void is the return type meaning this method does not return a value. displayMessage is the name of the method This method does not take any arguments.

Method Call A method is only executed when called. The only exception to this is the main method, which is executed when the program is run. When the JVM sees a method call, it branches to the statements inside of the method. To call a method, you must use its name and supply it with arguments if the method expects them. General form of a method call: name(argumentList); If the method definition has nothing for its parameter list, then you do not need to supply an argument list.

Method Example New Topics: Methods

Arguments and Parameters Methods declared outside of one another have different scope: public static void method1() { int x; method2(); } public static void method2() { int y; method2 cannot see method1’s local variable x, even though method2 is called from method2. Similarly, method1 cannot see method2’s local variable y. General Rule: Local variables declared inside of a method cannot be seen outside of the method it was declared in. So how can methods pass data from one to another? First part of the answer: the caller can pass data to the callee in the form of arguments. An argument is data passed to a method during a method call.

Arguments and Parameters We’ve passed arguments to methods before: System.out.println("Hello"); Math.sqrt(9); "Hello" and 9 are data we passed the println and sqrt methods that is used to perform their desired functions. These arguments are then stored as local variables that can be used corresponding definition. These local variables are called parameters. Parameters appear in the method header and can be used anywhere in the method definition.

Arguments and Parameters public static void method1() { int x = 5; method2(); } public static void method2() { int y = x; method2() cannot see x because it is out of scope, so this is an error.

Arguments and Parameters public static void method1() { int x = 5; method2(x); } public static void method2(int myX) { int y = myX; method1 passes the local variable x as an argument method2 takes an integer parameter called myX When method1 calls method2, the value stored in x is sent to the parameter myX so that method2 can use it. Note: arguments can be any expression that resolves to the type that corresponds to the called method’s parameter.

Arguments and Parameters Example New Topics: Arguments and Parameters

Argument and Parameter Notes Terminology varies for what people call arguments and parameters, but what is important is that you remain consistent. The argument must be some expression that is of the same type as the corresponding parameter OR some type of lower rank. Java will automatically perform widening conversions. Java WILL NOT perform narrowing conversions. Parameters have the same scope as local variables declared in the method. To pass an array variable as an argument, you can simply pass the variable by name. The corresponding method parameter looks very much like a normal parameter, but with [] between the parameter data type and the parameter name There are many, many more nuances to arguments and parameters, but we will cover them later.

Passing Multiple Arguments Java also allows for the passing of multiple arguments to a single method: public static void method1() { method2(1, 2); } public static void method2(int x, int y){ int z = x + y; The arguments in the method call, as well as, the parameters in the method header are both separated by commas. The argument’s values are passed to the corresponding parameters in the order in which they are arranged from left to right. For example, x would get the value 1 here and y would get the value 2. Example: MultipleArgs.java

Returning Values Methods may also pass data back to where it was called. This is called returning a value. We’ve seen this before: Math.sqrt(9) This method call returns the value of 3 back to where it was called. There are two differences when writing value returning methods: Instead of void as the return type, now that should be whatever type the value you want to return will be You must use a return statement to return a value at some point for all possible branches in the method definition.

Returning Values public static int addOne(int x) { return x+1; } The int after static indicates that this method will return a value of type int. return x+1; is a return statement. return is a keyword that indicates that the result of the expression following it will be returned to where the method was called So in this case, the result of x+1 will be returned to where it was called You can have as many statements as you like leading up to the return statement, but all branches that are possible in the method definition should end in a return statement. Once a return statement is reached, the program’s control flow leaves the method and goes back to where it was called. The expression following the return statement must be the same type as the return type for the method, or one of a lower rank.

Calling a Value-Returning Method Its often the case that you want to do something meaningful with the value a value-returning method returns. You can assign the return value to a variable: double x = Math.sqrt(9); You can use it in an expression: double x = Math.sqrt(9) * 2; You can print it to the screen System.out.println(Math.sqrt(9)); You can use it anywhere a value of the return type can be used

Value-Returning Method Example New Topics: Value-Returning Method