Methods.

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

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
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.
Road Map Introduction to object oriented programming. Classes
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
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.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 5, Methods Java How to Program, Late Objects Version, 10/e
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.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
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 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.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
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. Why Write Methods?  Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Methods.
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
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.
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.
Functions + Overloading + Scope
Suppose we want to print out the word MISSISSIPPI in big letters.
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.
if-else-if Statements
Chapter 6 Methods: A Deeper Look
CS139 – Fall 2010 How far we have come
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 6 Methods: A Deeper Look
Chapter 4 void Functions
6 Chapter Functions.
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
CHAPTER 6 GENERAL-PURPOSE METHODS
Defining methods and more arrays
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 6 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
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
Classes, Objects and Methods
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.
Happy October Exam Review 10/01/2014.
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

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.0");

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 Header public static void displayMesssage() { System.out.println("Hello"); } Body

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

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.

Calling a Method 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!”);

Hierarchical Method Calls 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 the main method.”); } 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.”); 1 2 7 2 3 4 6 4 5

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 */.

Documenting Methods 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.”); } /** The displayMessage method displays a greeting */ public static void displayMessage() System.out.println(“Hello from the displayMessage method!”);

Method Overloading

Method Overloading A class may define multiple methods with the same name- --this is called method overloading usually perform the same task on different data types Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) … The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);

Method Overloading: Signature The compiler must be able to determine which version of the method is being invoked This is by analyzing the parameters, which form the signature of a method the signature includes the type and order of the parameters if multiple methods match a method call, the compiler picks the best match if none matches exactly but some implicit conversion can be done to match a method, then the method is invoke with implicit conversion. the return type of the method is not part of the signature

double tryMe (int x) { return x + .375; } Version 1 double tryMe (int x, double y) { return x * y; } Version 2 result = tryMe (25, 4.32) Invocation

Which tryMe will be called? More Examples double tryMe ( int x ) { return x + 5; } Which tryMe will be called? tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); double tryMe ( double x ) { return x * .375; } double tryMe (double x, int y) { return x + y; }

Variable Scoping

There are two types of scopes in Java At a given point, the variables that a statement can access are determined by the scoping rule the scope of a variable is the section of a program in which the variable can be accessed (also called visible or in scope) There are two types of scopes in Java class scope a variable defined in a class but not in any method block scope a variable defined in a block {} of a method; it is also called a local variable

Java Scoping Rule A variable with a class scope class/static variable: a variable defined in class scope and has the static property it is associated with the class and thus can be accessed (in scope) in all methods in the class instance variable: a variable defined in class scope but not static it is associated with an instance of an object of the class, and thus can be accessed (in scope) only in instance methods, i.e., those non-static methods A variable with a block scope can be accessed in the enclosing block; also called local variable a local variable can shadow a variable in a class scope with the same name Do not confuse scope with duration a variable may exist but is not accessible in a method, e.g., method A calls method B, then the variables declared in method A exist but are not accessible in B.

Scoping Rules (cont.): Variables in a method There can be three types of variables accessible in a method : class and instance variables static and instance variables of the class local variables those declared in the method formal arguments

Example1: instance variables formal arguments local variables public class Box { private int length, width; … public int widen (int extra_width) private int temp1; size += extra_width; } public int lenghten (int extra_lenth) private int temp2; size += extra_length; instance variables formal arguments local variables

Instance variables are accessible in all methods of the class public class Box { private int length, width; … public int widen (int extra_width) private int temp1; size += extra_width; } public int lenghten (int extra_lenth) private int temp2; size += extra_length; Instance variables are accessible in all methods of the class formal arguments are valid within their methods Local variables are valid from the point of declaration to the end of the enclosing block

public class Test { final static int NO_OF_TRIES = 3; static int i = 100; public static int square ( int x ) // NO_OF_TRIES, x, i in scope int mySquare = x * x; // NO_OF_TRIES, x, i, mySquare in scope return mySquare; } public static int askForAPositiveNumber ( int x ) for ( int i = 0; i < NO_OF_TRIES; i++ ) { // NO_OF_TRIES, x, i in scope; local i shadows class i System.out.print(“Input: “); Scanner scan = new Scanner( System.in ); String str = scan.nextLine(); int temp = Integer.parseInt( str ); // NO_OF_TRIES, x, i, scan, str, temp in scope if (temp > 0) return temp; } // NO_OF_TRIES, x, i in scope return 0; } // askForPositiveNumber public static void main( String[] args ) {…}

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.

Passing Arguments to a Method public class PassArg { public static void main(String[] args) int x = 10; displayValue(x); displayValue(x * 4); } public static void displayValue(int num) System.out.println(“The value is: ” + num);

Passing 5 to the displayValue Method 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 The argument 5 is copied into the num1 parameter. The argument 10 is copied into the num2 parameter. 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); } 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.

public class PassArg { public static void main(String[] args) int number = 99; System.out.println(“Number is “ + number); changeMe(number); } public static void changeMe(int myValue) System.out.println(“I am changing the value.”); myValue = 0; System.out.println(“Now the value is “ + myValue); Program output Number is 99 I am changing the value Now the value is 0 Only a copy of an argument’s value is passed into a parameter variable

Passing 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 Arguments by Reference public class Swap { public int x; public static void swap(Swap s1, Swap s2) { int temp = s1.x; s1.x = s2.x; s2.x = temp; }

class SwapTest{ public static void main(String args[]) { Swap a1 = new Swap(); // creating object Swap a2 = new Swap(); a1.x = 2; // assigning value to data field a2.x = 5; System.out.println("Before swap"); System.out.println("a1.x="+a1.x+" a2.x="+a2.x); Swap.swap(a1.x,a2.x); System.out.println("After swap"); System.out.println("a1.x="+a1.x+" a2.x="+a2.x); } } Output:??

class SwapTest{ public static void main(String args[]) { Swap a1 = new Swap(); // creating object Swap a2 = new Swap(); a1.x = 2; // assigning value to data field a2.x = 5; System.out.println("Before swap"); Output: Before swap a1.x=2 a2.x=5 After swap a1.x=5 a2.x=2 System.out.println("a1.x="+a1.x+" a2.x="+a2.x); Swap.swap(a1.x,a2.x); System.out.println("After swap"); System.out.println("a1.x="+a1.x+" a2.x="+a2.x); } }

Arguments passing by value and reference exercise Write a void method (call it argumentExample) that takes an integer argument, modifies its value to be twice as much as originally, and prints it. In your main method, create an int variable int Num = 50, then call argumentExample (Num), then print the variable myNum below that. What do you observe? Write a few words about what is happening as a block comment above this method in your code.

Arguments passing by value and reference exercise Now change the above example program In class, declare an instance variable Number of int type. Define a one argument constructor which sets the initial value of Number variable passed at the time of object creation. Call argumentExpamle method and pass object of the class as an argument, method should receive object and change the value instance variable and return object back to main. Print value of variable before and after argumentExample method call. See how output is different in both programs.

Reference Chapter 5 & 9, Introduction to Java Programming, Liang.