Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Classes  All code in a Java program is part of a class  A class has two purposes  Provide functions to do work for the programmer  Represent data.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Chapter 6: User-Defined Functions I
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Introduction to Java Programming, 4E Y. Daniel Liang.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
CS 201 Functions Debzani Deb.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Chapter 6: User-Defined Functions I
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
COMP More About Classes Yi Hong May 22, 2015.
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
Procedural programming in Java Methods, parameters and return values.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Writing Static Methods Up until now, we have been USING (calling) static methods that other people have written. Now, we will start CREATING our own static.
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.
Lab 01-2 Objectives:  Writing a Java program.  How to send output to the command line console.  Learn about escape sequences.  Learn how to compile,
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
CSI 3125, Preliminaries, page 1 Compiling the Program.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
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.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
TOPIC 6 Methods F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters F Pass by Value F Overloading Methods F Method Abstraction.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
C# Programming Methods.
Methods.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
COP 2220 Computer Science I Topics –Breaking Problems Down –Functions –User-defined Functions –Calling Functions –Variable Scope Lecture 4.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Chapter 6: User-Defined Functions I
Introduction to Modular Programming
Yanal Alahmad Java Workshop Yanal Alahmad
Object Oriented Systems Lecture 03 Method
Functions CIS 40 – Introduction to Programming in Python
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 5 Methods.
Chapter 6: User-Defined Functions I
ITM 352 Functions.
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Methods

Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods can accept inputs in the form of arguments, perform some operations with the arguments, and then can return a value the is the output, or result of their computations. The Concept of a Method method inputsoutputs

Square root is a good example of a method. The square root method accepts a single number as an argument and returns the square root of that number. The computation of square roots involves many intermediate steps between input and output. When we use square root, we don’t care about these steps. All we need is to get the correct output. Hiding the internal workings of a method from a user but providing the correct answer is known as abstraction Square Root Method

A method has 4 parts: the return type, the name, the arguments, and the body: double sqrt(double num) { // a set of operations that compute // the square root of a number } The type, name and arguments together is referred to as the signature of the method Declaring Methods type namearguments body

The Return Type of a Method The return type of a method may be any data type. The type of a method designates the data type of the output it produces. Methods can also return nothing in which case they are declared void.

Return Statements The return statement is used in a method to output the result of the methods computation. It has the form: return expression_value; The type of the expression_value must be the same as the type of the method: double sqrt(double num){ double answer; // Compute the square root of num and store // the value into the variable answer return answer; }

Return Statements A method exits immediately after it executes the return statement Therefore, the return statement is usually the last statement in a method A method may have multiple return statements. Can you think of an example of such a case?

Brain Teaser Answer Example: int absoluteValue (int num){ if (num < 0) return –num; else return num; }

void Methods A method of type void has a return statement without any specified value. i.e. return; This may seem useless, but in practice void is used often. A good example is when a methods only purpose is to print to the screen. If no return statement is used in a method of type void, it automatically returns at the end

Method Arguments Methods can take input in the form of arguments. Arguments are used as variables inside the method body. Like variables, arguments, must have their type specified. Arguments are specified inside the paren- theses that follow the name of the method.

Here is an example of a method that divides two doubles: double divide(double a, double b) { double answer; answer = a / b; return answer; } Example Method

Method Arguments Multiple method arguments are separated by commas: double pow(double x, double y) Arguments may be of different types int indexOf(String str, int fromIndex)

The Method Body The body of a method is a block specified by curly brackets. The body defines the actions of the method. The method arguments can be used anywhere inside of the body. All methods must have curly brackets to specify the body even if the body contains only one or no statement.

Invoking Methods To call a method, specify the name of the method followed by a list of comma separated arguments in parentheses: pow(2, 10); //Computes 2 10 If the method has no arguments, you still need to follow the method name with empty parentheses: size();

Static Methods Some methods have the keyword static before the return type: static double divide(double a, double b) { return a / b; } We'll learn what it means for a method to be static in a later lecture For now, all the methods we write in lab will be static.

main - A Special Method The only method that we have used in lab up until this point is the main method. The main method is where a Java program always starts when you run a class file with the java command The main method is static has a strict signature which must be followed: public static void main(String[] args) {... }

main continued class SayHi { public static void main(String[] args) { System.out.println("Hi, " + args[0]); } } When java Program arg1 arg2 … argN is typed on the command line, anything after the name of the class file is automatically entered into the args array: java SayHi Sonia In this example args[0] will contain the String "Sonia", and the output of the program will be "Hi, Sonia".

class Greetings { public static void main(String args[]) { String greeting = ""; for (int i=0; i < args.length; i++) { greeting += "Jambo " + args[i] + "! "; } System.out.println(greeting); } After compiling, if you type java Greetings Alice Bob Charlie prints out "Jambo Alice! Jambo Bob! Jambo Charlie!" Example main method

class Factorial { public static void main (String[] args) { int num = Integer.parseInt(args[0])); System.out.println(fact(num)); } static int fact(int n) { if (n <= 1) return 1; else return n * fact(n – 1); } After compiling, if you type java Factorial 4 the program will print out 24 Recursive Example

class Max { public static void main(String args[]) { if (args.length == 0) return; int max = Integer.parseInt(args[0]); for (int i=1; i < args.length; i++) { if (Integer.parseInt(args[i]) > max) { max = Integer.parseInt(args[i]); } System.out.println(max); } After compiling, if you type java Max the program will print out 9 Another Example

Summary Methods capture a piece of computation we wish to perform repeatedly into a single abstraction Methods in Java have 4 parts: return type, name, arguments, body. The return type and arguments may be either primitive data types or complex data types (Objects) main is a special Java method which the java interpreter looks for when you try to run a class file main has a strict signature that must be followed: public static void main(String args[])