Methods We write methods in our programs for many reasons:

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

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.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Procedural programming in Java
1 Various Methods of Populating Arrays Randomly generated integers.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
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,
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
20-Jun-15 Methods. Complexity The programmer's biggest adversary is complexity The programmer's biggest adversary is complexity Primitive types and the.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
CS 201 Functions Debzani Deb.
CHAPTER:09 METHODS(FUNCTIONS) IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Introduction to Methods
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
COMP More About Classes Yi Hong May 22, 2015.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Hello AP Computer Science!. What are some of the things that you have used computers for?
Methods and You. Up to this point, I have covered many different data types with you. Variables can be considered the nouns of an English sentence. If.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Objects are passed by reference.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Methods We write methods in our programs for many reasons: –By breaking the program into smaller units it is easier to design the program it is easier.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
Procedural programming in Java Methods, parameters and return values.
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.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
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.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Building java programs, chapter 3 Parameters, Methods and Objects.
1 ICS103 Programming in C Lecture 8: Functions I.
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
Department of Computer Engineering Methods Computer Programming for International Engineers.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
Programming Fundamentals Enumerations and Functions.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Methods. Methods are groups of statements placed together under a single name. All Java applications have a class which includes a main method class MyClass.
Functions + Overloading + Scope
User-Written Functions
Chapter 7 User-Defined Methods.
Methods Chapter 6.
Methods.
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.
Starting Out with Java: From Control Structures through Objects
Group Status Project Status.
Chapter 6 Methods.
Introduction to Java Programming
Names of variables, functions, classes
References Revisted (Ch 5)
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Methods We write methods in our programs for many reasons: By breaking the program into smaller units it is easier to design the program it is easier to write the program it is easier to debug the program We can reuse these smaller units once written We use methods to define the capabilities of our classes, so an object can perform any method written in it’s class definition We have already written a few methods to perform Graphics operations

Using Methods You have already used many methods: showInputDialog, showMessageDialog (JOptionPane) length, toUpperCase, toLowerCase, replace (String) nextInt (Random) abs, sqrt (Math) drawLine, fillRect, setColor, drawString, etc (Graphics) In each of the above cases, the method was written as part of another class, so to call them, we pass an object the message as listed above Today, we will write methods that go inside of our own classes we are making our program more involved – instead of just having a main method, the main method can call upon other methods

Example: Tic Tac Toe We could have simplified our Tic Tac Toe program through methods The idea is that each small task is taken care of in a separate method We would have a method to print the grid – printGrid(grid) input a player’s move and data verify it – getMove(grid, char) check to see if a player has won – checkForWin(grid) Our main method becomes far simpler: declare the grid and initialize variables while(!won) { printGrid(grid) square=getMove(grid, ‘X’); grid[square] = ‘X’; won=checkForWin(grid) if(won==‘n’) { square=getMove(grid, ‘O’); won=checkForWin(grid); }

Components of a Method Think of a method as a mini-program, but one that is incomplete – to be complete, it must be told what data to operate on we pass the data from one method to another through a parameter list as an example, we want to draw the current Tic Tac Toe grid so we pass the grid (the char array) to the output method or we want to see if someone has won we pass the grid to the win-checking method To define a method, we write two sets of code the method, which specifies how the operation will be executed a method call to invoke the method which specifies what data to operate on method call will list the method’s name, (, parameters, ); as in drawGrid(grid); or getMove(grid, ‘X’);

Writing Methods To write a method, we write the method’s header and the method’s body the header contains the name of the method type of value that the method will return (if any) parameters that are passed to the method along with each parameter’s type the body comprises variable declarations and executable statements the body looks a lot like your main method with one possible addition, if the method is to return a value, the method must include a return statement

Skeleton of a Method public static returntype name(parameter list) { declared variables executable statements return statement } Method header Method body All of our methods (for now) will be defined as public static The return type is the type of value returned in the return statement (if there is one), if not, we use the word void to denote that nothing is returned The executable statements are any type that we’ve already covered including calls to other methods

Some Examples public static int larger(int x, int y) { if(x > y) return x; else return y; } public static String getInitials(String first, String middle, String last) return "" + first.toUpperCase().charAt(0) + "." + middle.toUpperCase().charAt(0) + "." + last.toUpperCase().charAt(0) + "."; public static double computeAverage(int[ ] array, int n) int sum = 0; for(int i=0;i<n;i++) sum += array[i]; double average = (double) sum / n; return average; Why does this statement start with “”? sum, i and average are known as local variables – they are known only within this method

Invoking a Method One method calls another method the method call is accomplished by listing the name of the method and parens as in doIt( ); When a method is called the calling method suspends itself and the called method begins the called method executes until it terminates and then control returns to the calling method method calls can be nested as shown below doIt(); main doIt helpMe helpMe(); main calls doIt( ) and main suspends doIt( ) calls helpMe( ) and doIt suspends helpMe executes until it completes doIt resumes from right after the point where it called helpMe when helpMe ends, main resumes

Parameters Parameters provide information for the method to use that is, we use parameters to communicate between the calling method and the called method Parameters are lists of variables or values already known in the calling method without the parameters, the method does not receive any information from the calling method so does not know anything specific about how it should function a method that computes sales tax needs to know how much the sale was in order to compute the tax or the previous method that determined someone’s initials needed to know that person’s name Parameters must match in terms of the type of value and the number of parameters, but the names may differ

Actual vs. Formal Parameters Actual parameters the parameters listed in the method call Formal parameters the parameters listed in the method header The number of parameters in both list must be the same, and the types must be the same, but their names may differ Here we see that the method is called passing firstnum and secnum, but the formal parameters are named x and y instead

Complete Example We put together several of the concepts discussed to write a method that is passed 4 test scores, computes the average and based on the average, returns a letter grade (a char) public static char returnGrade(int exam1, int exam2, int exam3, int exam4) { int sum; double average; sum = (exam1 + exam2 + exam3 + exam4); average = (double) sum / 4.0; if(average >= 90.0) return ‘A’; else if(average >= 80.0) return ‘B’; else if(average >= 70.0) return ‘C’; else if(average >= 60.0) return ‘D’; else return ‘F’; } Notice that this method will return one of ‘A’, ‘B’, ‘C’, ‘D’, or ‘F’ – if our method ended with the statement else if(average >=0) return ‘F’; we would get a syntax error because Java is not convinced that any of the return statements would execute So be aware of this problem in Java and make sure that, if the method is to return a value, it definitely will under all circumstances

Complete Method Calling Example public class PrimeNumbers { public static void main(String[ ] args) System.out.println("I will tell you all prime numbers between 1 and 100"); for(j=1; j<=100; j++) if(isItPrime(j)) System.out.println(j + " is a prime number"); } // end main method public static boolean isItPrime(int x) int limit = 2; boolean returnValue = true; // assume x is prime unless we find a divisor if(x > 1) while(returnValue && limit < x) if(x % limit = = 0) returnValue = false; // divisor found, x is not prime else limit++; return returnValue; } // end isItPrime method } // end PrimeNumbers class

More on Formal and Actual Params Notice in the previous example that the formal parameter for isItPrime was called x but the actual param in main was called j How does this work? This is one of the most confusing things for beginning programmers to understand the two parameters are not the same thing, they are not the same memory location instead, we have two different variables, one is called j and it exists in main, the other is called x and it exists only in isItPrime the two variables are only linked when the method is first called, and the link is only that the formal param is initialized to the value of the actual param so x is initialized to whatever value j was when isItPrime was called

Changing Parameter Values The reason that the formal param is initialized to the actual param is because Java uses a parameter passing technique called “pass-by-value” the parameters in the method header (the formal parameters) receive copies of the parameters in the method call (the actual parameters) Since the actual params are only copies, if we change a value of an actual param, it has no affect on the formal param’s value for instance, if isItPrime at some point did x++; then x would change value, but j would not Note: this is true for any primitive type and for Strings, but it may or may not be true of other types of objects two examples follow

Example: Changing Parameter Values public class ChangeExample { public static void main(String[ ] args) int a = 5, b = 10, c, d; c = foo(a, b); d = foo(b, a); System.out.println(a + " " + b + " " + c + " " + d); } public static int foo(int x, int b) int z = x++; b += z; return x * b; Notice the parameter names in foo – x and b Is b the same as b in main? No So what happens in foo to a and b of main? Nothing This code will output 90 165 Can you figure out why?

Changing String Example public class ChangeString { public static void main(String[ ] args) String x = "hi there"; System.out.println(x); change1(x); change2(x); change3(x); } public static void change1(String x) x += "!"; public static void change2(String x) { x = x.toUpperCase( ); System.out.println(x); } public static void change3(String x) x = x.replace(‘e’, ‘o’); x = x.replace(‘i’, ‘u’); } // ends ChangeString method Output: hi there hi there! HI THERE hu thoro