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.

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
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.
Introduction to Methods
Chapter 6: Functions.
© 2007 Lawrenceville Press Slide 1 Chapter 7 Top-Down Development  Problem-solving approach  Breaking a task down into smaller subtasks  First level.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
© 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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 5, Methods Java How to Program, Late Objects Version, 10/e
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
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.
Procedural programming in Java Methods, parameters and return values.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
1/28: Inputs, Variable Types, etc. Addition.java in depth Variable types & data types Input from user: how to get it Arithmetic operators.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
Method Examples CS 139 Algorithm Development 10/06/2008.
Exam Review 10/01/2014 Happy October. The Exam  Will be in Canvas  Two parts  Part A is recall – closed book, closed notes ◦Quizzes, in class activity.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 5.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Introduction to Methods ISYS 350. Methods Methods can be used to break a complex program into small, manageable pieces – This approach is known as divide.
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.
Chapter 7 Top-Down Development
by Tony Gaddis and Godfrey Muganda
Object Oriented Systems Lecture 03 Method
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Methods.
if-else-if Statements
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
Starting Out with Java: From Control Structures through Objects
Chapter 4 void Functions
6 Chapter Functions.
CHAPTER 6 GENERAL-PURPOSE METHODS
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
Lecture 5- Classes, Objects and Methods
Based on slides created by Bjarne Stroustrup & Tony Gaddis
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.
Starting Out with Java: From Control Structures through Objects
Happy October Exam Review 10/01/2014.
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
Presentation transcript:

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.  Methods simplify programs. If a specific task is performed in several places in the program, a method can be written once to perform that task, and then be executed anytime it is needed. This is known as code reuse.

void Methods and Value- Returning Methods  A void method is one that simply performs a task and then terminates. System.out.println(“Hi!”);  A value-returning method not only performs a task, but also sends a value back to the code that called it. int number = Integer.parseInt(“700”);

Defining a void Method  To create a method, you must write a definition, which consists of a header and a body.  The method header, which appears at the beginning of a method definition, lists several important things about the method, including the method’s name.  The method body is a collection of statements that are performed when the method is executed.

Two Parts of Method Declaration public static void displayMesssage() { System.out.println(“Hello”); } Chapter 5 Slide #5 header body

Parts of a Method Header public static void displayMessage () { System.out.println(“Hello”); } Method Modifiers Return Type Method Name Parentheses

Parts of a Method Header  Method modifiers public —method is publicly available to code outside the class static —method belongs to a class, not a specific object.  Return type—void or the data type from a value-returning method  Method name—name that is descriptive of what the method does  Parentheses—contain nothing or a list of one or more variable declarations if the method is capable of receiving arguments.

Calling a Method  A method executes when it is called.  The main method is automatically called when a program starts, but other methods are executed by method call statements. displayMessage();  Notice that the method modifiers and the void return type are not written in the method call statement. Those are only written in the method header.

SimpleMethod.java public class SimpleMethod { public static void main(String[] args) { System.out.println("Hello from the main method."); displayMessage(); System.out.println("Back in the main method."); } public static void displayMessage() { System.out.println("Hello from the displayMessage method."); }

LoopCall.java public class LoopCall { public static void main(String[] args) { System.out.println("Hello from the main method."); for (int i = 0; i < 5; i++) displayMessage(); System.out.println("Back in the main method."); } public static void displayMessage() { System.out.println("Hello from displayMessage method."); }

CreditCard.java import javax.swing.JOptionPane; /** This program uses two void methods. */ public class CreditCard { public static void main(String[] args) { double salary; // Annual salary int creditRating; // Credit rating String input; // To hold the user's input // Get the user's annual salary. input = JOptionPane.showInputDialog("What is " + "your annual salary?"); salary = Double.parseDouble(input);

CreditCard.java // Get the user's credit rating (1 through 10). input = JOptionPane.showInputDialog("On a scale of " + "1 through 10, what is your credit rating?\n" + "(10 = excellent, 1 = very bad)"); creditRating = Integer.parseInt(input); // Determine whether the user qualifies. if (salary >= && creditRating >= 7) qualify(); else noQualify(); System.exit(0); }

CreditCard.java /** The qualify method informs the user that he or she qualifies for the credit card. */ public static void qualify() { JOptionPane.showMessageDialog(null, "Congratulations! " + "You qualify for the credit card!"); }

CreditCard.java /** The noQualify method informs the user that he or she does not qualify for the credit card. */ public static void noQualify() { JOptionPane.showMessageDialog(null, "I'm sorry. You " + "do not qualify for the credit card."); }

DeepAndDeeper.java public class DeepAndDeeper { public static void main(String[] args) { System.out.println("I am starting in main."); deep(); System.out.println("Now I am back in main."); } I am starting in main.

DeepAndDeeper.java public static void deep() { System.out.println("I am now in deep."); deeper(); System.out.println("Now I am back in deep."); } public static void deeper() { System.out.println("I am now in deeper."); } I am starting in main. I am now in deep. I am starting in main. I am now in deep. I am now in deeper. I am starting in main. I am now in deep. I am now in deeper. Now I am back in deep.

DeepAndDeeper.java public class DeepAndDeeper { public static void main(String[] args) { System.out.println("I am starting in main."); deep(); System.out.println("Now I am back in main."); } I am starting in main. I am now in deep. I am now in deeper. Now I am back in deep. Now I am back in main.

Documenting Methods  A method should always be documented by writing comments that appear just before the method’s definition.  The comments should provide a brief explanation of the method’s purpose.  The documentation comments begin with /** and end with */.

Passing Arguments to a Method  Values that are sent into a method are called arguments. System.out.println(“Hello”); number = Integer.parseInt(str);  The data type of an argument in a method call must correspond to the variable declaration in the parentheses of the method declaration. The parameter is the variable that holds the value being passed into a method.  By using parameter variables in your method declarations, you can design your own methods that accept data this way.

Example: PassArg.javaPassArg.java  public class PassArg  {  public static void main(String[] args)  {  int x = 10;  System.out.println("I am passing values to displayValue.");  displayValue(5); // Pass 5  displayValue(x); // Pass 10  displayValue(x * 4); // Pass 40  displayValue(Integer.parseInt("700")); // Pass 700  System.out.println("Now I am back in main.");  } 

PassArg.java  /**  The displayValue method displays the value  of its integer parameter.  */   public static void displayValue(int num)  {  System.out.println("The value is " + num);  }

Passing 5 to the displayValue Method displayValue(5); public static void displayValue(int num) { System.out.println(“The value is “ + num); } The argument 5 is copied into the parameter variable num. The method will display The value is 5

Argument and Parameter Data Type Compatibility  When you pass an argument to a method, be sure that the argument’s data type is compatible with the parameter variable’s data type.  Java will automatically perform widening conversions, but narrowing conversions will cause a compiler error. double d = 1.0; displayValue(d); Error! Can’t convert double to int

Passing Multiple Arguments showSum(5,10); public static void showSum(double num1, double num2) { double sum;//to hold the sum sum = num1 + num2; System.out.println(“The sum is “ + sum); } The argument 5 is copied into the num1 parameter. The argument 10 is copied into the num2 parameter. NOTE: Order matters!

Arguments are Passed by Value  In Java, all arguments of the primitive data types are passed by value, which means that only a copy of an argument’s value is passed into a parameter variable.  A method’s parameter variables are separate and distinct from the arguments that are listed inside the parentheses of a method call.  If a parameter variable is changed inside a method, it has no affect on the original argument.

Example: PassByValue.javaPassByValue.java  public static void main(String[] args)  {  int number = 99; // number starts with 99   // Display the value in number.  System.out.println("number is " + number);   // Call changeMe, passing the value in number  // as an argument.  changeMe(number);   // Display the value in number again.  System.out.println("number is " + number);  }

Example: PassByValue.javaPassByValue.java  public static void changeMe(int myValue)  {  System.out.println("I am changing the value.");   // Change the myValue parameter variable to 0.  myValue = 0;   // Display the value in myValue.  System.out.println("Now the value is " + myValue);  }

Passing String Object References to a Method  Recall that a class type variable does not hold the actual data item that is associated with it, but holds the memory address of the object. A variable associated with an object is called a reference variable.  When an object, such as a String is passed as an argument, it is actually a reference to the object that is passed.

Passing a Reference as an Argument showLength(name); public static void showLength(String str) { System.out.println(str + “ is “ + str.length() + “characters long.”); str = “Joe”; //see next slide } address “Warren” Both variables reference the same object The address of the object is copied into the str parameter.

Strings are Immutable Objects  Strings are immutable objects, which means that they cannot be changed. When the line str = “Joe”; is executed, it cannot change an immutable object, so creates a new object. address “Warren” “Joe” The name variable holds the address of a String object The str variable holds the address of a different String object

Example: PassString.javaPassString.java public static void main(String[] args) { // Create a String object containing "Shakespeare". // The name variable references the object. String name = "Shakespeare"; System.out.println("In main, the name is " + name); changeName(name); // Display the String referenced by the name variable. System.out.println("Back in main, the name is " + name); }

public static void changeName(String str) { // Create a String object containing "Dickens". // Assign its address to the str parameter variable. str = "Dickens"; // Display the String referenced by str. System.out.println("In changeName, the name " + "is now " + str); }

More About Local Variables  A local variable is declared inside a method and is not accessible to statements outside the method.  Different methods can have local variables with the same names because the methods cannot see each other’s local variables.  A method’s local variables exist only while the method is executing. When the method ends, the local variables and parameter variables are destroyed and any values stored are lost.  Local variables are not automatically initialized with a default value and must be given a value before they can be used.

Example: LocalVars.javaLocalVars.java public static void main(String[] args) { texas(); california(); }

Example: LocalVars.javaLocalVars.java public static void texas() { int birds = 5000; System.out.println("In texas there are " + birds + " birds."); } public static void california() { int birds = 3500; System.out.println("In california there are " + birds + " birds."); }