Chapter 5, Methods Java How to Program, Late Objects Version, 10/e

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
 2005 Pearson Education, Inc. All rights reserved Introduction.
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.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
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.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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 6: Functions Starting Out with C++ Early Objects
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Procedural programming in Java Methods, parameters and return values.
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.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
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.
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.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
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.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
by Tony Gaddis and Godfrey Muganda
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Methods.
Chapter 6 Methods: A Deeper Look
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Starting Out with Java: From Control Structures through Objects
Chapter 6 Methods: A Deeper Look
6 Chapter Functions.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Lecture 5- Classes, Objects and Methods
Object Oriented Programming in java
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.
Presentation transcript:

Chapter 5, Methods Java How to Program, Late Objects Version, 10/e © 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Chapter 5 Topics 5.1 Introduction to Methods 5.2 Calling Methods 5.3 Class Members Instance Members static Members 5.4 Value-Returning & Value-Receiving Methods 5.5 Notes on Declaring & Using Methods 5.7 Passing Arguments to a Method 5.11 Scope of Variable Declarations 5.12 Method Overloading  Documenting Methods 5-2 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 2

5.1 Why Write Methods? Divide and Conquer: Methods break a problem down into small manageable pieces. A method 1contains code that performs a specific task. 2simplifies programs because a method can be used in several places in a program. This is known as code reuse (method coded once, used many times). facilitates the design, implementation, operation and maintenance of large programs. Programs can be created from standardized methods rather than by building customized code. Dividing a program into meaningful methods makes the program easier to debug and maintain. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. Source: 1Linda Shepherd, Dept. of ISCS, COB, UTSA. Modified By: 2Linda Shepherd, Dept. of ISCS, COB, UTSA. 5-3 3

5.1 Methods & Variables A method can have its own variables (local variables). These variables are declared in the body of the method and belongs only to that method. Declaration Format: dataType variableName = initializationValue; A method also can use fields (class/global variables). Fields can be used by more than one method. Fields have to be static if the methods calling them are static. Fields are to be declared as private. Fields are declared at the beginning of a class. private static dataType variableName = initializationValue; 5-4 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 4

5.1 Method Declaration & Header Method Modifiers Return Type Method Name public static void displayMessage() { System.out.printf(“%nHello“); } public static void displayMessage () { System.out.printf(“%nHello“); }//This method receives nothing and returns //nothing. Header Parameter List empty, i.e., no para- meter variables Body 5-5 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 5

5.1 Parts of a Method Header Method Modifiers 1Return Type Method Name Parameter List public static String getName () { Scanner input = new Scanner(System.in); System.out.printf(“%nWhat is your name? “); String name = input.nextLine(); return name; }//This is a value-returning method. 1A return allows a method to pass or give back a value. Therefore, it has to be typed for the value it’s returning. The return type can be void, a primitive data type (int, char, byte, short, long, float, double, boolean), or complex data type (classes such as String or any other class). ©Linda Shepherd, Dept. ISTM, COB, UTSA 5-6 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 6

5.1 Parts of a Method Header Method Modifiers Return Type Method Name Parameter List with 1 parameter variable public static void printName (String name) { System.out.printf(“Your name is %s.”, name); }//This is a value-receiving method. 1Parameter variables are variables listed within the parentheses or parameter list. They can be of any data type - primitive data type (int, char, byte, short, long, float, double, boolean), or complex data type (classes such as String or any other class). They are local to the method and help the method receive data for processing. The paramater variable name is an object of the String class. ©Linda Shepherd, Dept. ISTM, COB, UTSA 5-7 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 7

5.1 Parts of a Method Header Method Modifiers Return Type Method Name Parentheses contain a parameter list public static int sum(int num1, int num2) { int result = 0; result = num1 + num2; return result; }//This is a value-returning & value-receiving //method. 5-8 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 8

5.1 static and void Methods 1A void method is one that simply performs a task and then terminates. System.out.printf(“%nHi!"); 2It can receive or not receive data. 3It definitely doesn’t return data. 4It has to be static if it’s in the same class as another static method that calls it. 5-9 Source: 1Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 2,3,4Linda Shepherd, Dept. of ISCS, COB, UTSA. 9

5.1 static and void Methods public class DemoStaticVoidMethod { private static String personName; private static Scanner input = new Scanner (System.in); public static void main(String[] args) String greeting = “Hello”; setName(); System.out.printf(“%s %s!”, greeting, personName); System.exit(0); }//END main() public static void setName() System.out.print(“Enter your name: “); personName = input.nextLine(); }//END setName() }//END APPLICATION CLASS DemoStaticVoidMethod 5-10 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 10

5.1 Value-Returning Methods A value-returning method not only performs a task, but also sends a value back to the code that called it. name = input.nextLine(); System.out.printf(“Hi %s!”, name); OR System.out.printf(“Hi %s!”, getName()); nextLine is a method that captures a name and returns it to be stored in the variable name; therefore, nextLine is a value-returning method. Method that returns a name see slides 5-6 5-11 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 11

5.1 Value-Receiving Methods A value-receiving method not only performs a task, but also gets a value or values from the code that calls it. name = input.nextLine(); System.out.println(“Hi “ + name + “!” ); OR System.out.printf(“Hi %s!”, getName()); “Hi “ plus the value in name plus “!” are all concatenated (joined) then sent to println which is a value-receiving method This String value/literal containing a name is sent to printf() which in turn displays the greeting; therefore, printf is a value-receiving method, but printf is also value-returning because it returns the formatted output which is then printed. 5-12 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 12

5.1 Methods: Summary Methods are real important because they are how programs can share code and interact one another. One method (the client) from one class can call the method of another class to use that method’s code (or services). The method header has Modifiers usually: public static A return type: void, primitive or complex data type Method name: should describe the method’s purpose Parentheses: the parameter list that can be empty or contain a list of parameter variables with their data types. void methods return nothing. Value-returning methods have a return type other than void. They return or give back data to the code that calls it. The data has to have the same data type as the return type. They must have only one return statement as the last statement in the method body. 5-13 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 13

5.1 Methods: Summary (cont) A method with empty parentheses or no variables in its parameter list receives nothing – no data – from the code that calls it. Value-receiving methods accept or receive data from the code that calls it. The type of data and how much data sent to a method is dictated by its parameter list (what is inside the parentheses). Data sent has to be in the same order as what is listed in the parameter list. Methods that are in the same program and are static can only interact with other static methods and can only use global variables (fields) that are static. static means that there is only one of that method or variable in existence during runtime. Variables that are global are declared at the class level right after the open brace { for the class. They should be declared private. 5-14 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 14

5.1 Methods: Summary (cont) Methods are written so code can be grouped according to its purpose or function. This allows for code to be reused without having to be re- written. This makes debugging easier. This allows the programmer to call the method with the code that is needed when and where it’s needed. Program maintenance is easier because any changes to a program can be targeted to the method that needs changing, so the other parts of the program remain unaffected. 5-15 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 15

5.2 Calling Methods name = input.nextLine(); A method has to be called or invoked to use its code. Methods coded in the same program are called directly using its name. displayMessage(); 1Methods coded in another program (class) … are called by … objects: name = input.nextLine(); Where input is an object of the Scanner class. 2Methods coded in another class that are static … can be called using the class name … int highValue = Math.max(8,5); Never call methods with the header intact: public static void displayMessage(); 5-16 © 1992-2015 by Pearson Education, Inc. All Rights Reserved. Modified By: 1,2Linda Shepherd, Dept. of ISCS, COB, UTSA.

5.2 Calling Methods: Summary Methods in the same class are called/invoked using their name followed by parentheses. methodName(); Methods from other classes that are static can be called using the name of the class followed by a dot operator and the method name and parentheses. ClassName.methodName(); Methods from other classes can be called using an object of the class. These methods are usually non-static. objectName.methodName(); 5-17 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 17

5.3 static Class Members The fields and methods of a class are referred to as class members. Class members can be static or non-static (also known as instance members). Within the same class, static methods can only access static fields, call other static methods. To invoke (call) a public static method or use a public static field from another class, the class name, rather than the instance name, is used. Example: double val = Math.sqrt(25.0); Class name Static method 5-18 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 9. 1, 2©Linda Shepherd, Dept. of ISCS, COB, UTSA. 18

5.3 static Methods Methods can … be declared static by placing the keyword static between the access modifier and the return type of the method. public static double milesToKilometers(double miles) {…} When a class contains a static method, it is not necessary to create an instance (copy) of the class in order to use the method. double kilosPerMile = Metric.milesToKilometers(1.0); Examples: Metric.java, MetricDemo.java 5-19 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 9. 19

5.3 static Methods static methods are convenient because they may be called at the class level, i.e., using the class name. They are typically used to create utility classes, such as the Math class in the Java Standard Library (Java API). 5-20 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 9. 20

5.3 static and void Methods public class DemoStaticVoidMethod { private static Scanner input = new Scanner (System.in); public static String setName() System.out.print(“Enter your name: “); return input.nextLine(); }//END setName() }//END CLASS DemoStaticVoidMethod //NO IMPORT STMT NEEDED IN Test IF BOTH CLASSES IN SAME DIRECTORY public class TestDemoStaticVoidMethod { public static void main(String[] args) { String greeting = “Hello”; System.out.printf(“%s %s!”, greeting, DemoStaticVoidMethod.setName()); System.exit(0); }//END main() }//END APPLICATION CLASS TestDemoStaticVoidMethod 5-21 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 21

5.3 static and void Methods public class DemoStaticVoidMethod { private static Scanner input = new Scanner (System.in); public static String setName() System.out.print(“Enter your name: “); return input.nextLine(); }//END setName() }//END CLASS DemoStaticVoidMethod //NO IMPORT STMT NEEDED IN Test IF BOTH CLASSES IN SAME DIRECTORY public class TestDemoStaticVoidMethod { public static void main(String[] args) { DemoStaticVoidMethod demoProg = new DemoStaticVoidMethod(); String greeting = “Hello”; System.out.printf(“%s %s!”, greeting, demoProg.setName()); System.exit(0); }//END main() }//END APPLICATION CLASS TestDemoStaticVoidMethod demoProg is an object of DemoStaticVoidMethod class. 5-22 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 22

5.3 static Members: Summary There are 2 types of class members: Global variables or fields Methods These members can be static or non-static. static members are coded with the word static whereas non-static members aren’t. In the same program, static methods can only interact with other static methods. use static fields. Note: The variables coded in a method are not fields. They are local or method level variables and they are never static. Therefore programs with the main() will be coded with static methods and static fields because the main() is static. 5-23 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 23

5.4 Value-Returning and Value-Receiving Methods A method can only return a single value to a calling statement through its return-type. public static String yourName() A method can receive values through its parameter list. public static void yourName(String first, String last) A method can receive one or more values and return a value. public static String yourName(String first, String last) 5-24 ©Linda Shepherd, Dept. of ISCS, COB, UTSA 24

5.4 Defining a Value-Returning and Value-Receiving Method public static int sum(int num1, int num2) { int result = 0; result = num1 + num2; return result; } Return type The return statement causes the method to end execution and it returns a value back to the statement that called the method. This [variable] must be of the same data type as the return type 5-25 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 25

5.4 Defining a Value-Returning and Value-Receiving Method public static int sum(int num1, int num2) { int result = 0; result = num1 + num2; return result; } 1Parameter List contains a list of variables the method takes in for processing. Parameter variables are local. 5-26 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 1Linda Shepherd, Dept. of ISCS, COB, UTSA. 26

5.4 Returning a Value from a Method Data can be passed into a method by way of the parameter variables. Data may also be returned from a method, back to the statement that called it. int num = Integer.parseInt("700"); The String literal “700” is passed to the parseInt method. The int value 700 is returned from the method and assigned to the num variable. 5-27 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 27

5.4 Calling a Value-Returning and Value-Receiving Method public static void main(String[] args) { int value1 = 20; int value2 = 40; int total = 0; These are variable arguments. total = sum(value1, value2); } public static int sum(int num1, int num2) { int result = 0; result = num1 + num2; return result; 60 40 20 5-28 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 28

5.4 Returning a boolean Value Sometimes we need to write methods to test arguments for validity and return true or false public static boolean isValid( int number ) { boolean status = false; if(number >= 1 && number <= 100) status = true; } return status; Calling code: int value = 20; if(isValid(value)) System.out.printf(“%nThe value is within range.“); else System.out.printf(“%nThe value is out of range.“); 5-29 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 29

5.4 Returning a Reference to a String Object These are literal arguments. customerName = fullName("John“, "Martin“); public static String fullName(String first, String last) { String name = null; name = first + " " + last; return name; } See example: ReturnString.java address “John Martin” Local variable name holds the reference to the object. The return statement sends a copy of the reference back to the call statement and it is stored in customerName. 5-30 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 30

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

5.4 Value-Receiving & Value-Returning Methods: Summary A method can be value-receiving only. A method can be value-returning only. A method can be both value-receiving and value- returning. A method can be void and value-receiving. A method can be void and NOT value-receiving or parameterless (empty parentheses). A method can be value-returning and NOT value- receiving. A call to a value-returning method requires the calling statement to handle that value by Storing it in a variable of the same type which requires the use of an assignment operator. Printing it Using it in some type of expression Processing it in some way. 5-33 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 33

5.4 Value-Receiving & Value-Returning Methods: Summary (cont) A call to a value-receiving method requires the calling statement to send it data that matches the data type of the parameter variables in the method’s parameter list. The data sent has to be sent in the same order as what is listed in the parameter list. There is no limit to the number of parameter variables, but practicality dictates that you make the method as simple as possible. The data sent to the method are called arguments. There are variable arguments. calc(num1, num2); where num1 and num2 are variables so they’re being used as variable arguments. There are literal arguments. calc(10, 5); where 10 and 5 are integer literals so they’re being used as literal arguments. There are value-returning method arguments. calc(val1(), val2()); where val1() and val2() are methods that return the numbers sent to the calc method, so they’re used as method arguments. . 5-34 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 34

5.7 Passing Arguments to a Value-Receiving Method What is sent to a method is an argument. System.out.printf(“%nHello”); number = Integer.parseInt(str); The data type of an argument in a method call must correspond to the 1data type of the parameter variable in the parentheses of the method 2header. The parameter is the variable that holds the value being passed to a method. By using parameter variables in your method declarations, you can design your own methods that accept data. See example: PassArg.java 5-35 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 1,2Linda Shepherd, Dept. of ISCS, COB, UTSA 35

5.7 Passing 5 to the displayValue Method public static void displayValue(int num) { System.out.printf(“The value is %d.“, num); } The argument 5 is an integer literal that is copied to the parameter variable num. The method will display The value is 5. 5-36 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 36

5.7 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 5-37 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 37

5.7 Passing Multiple Arguments The argument 5 is copied to the num1 parameter. The argument 10 is copied to the num2 parameter. showSum(5, 10); public static void showSum(double num1, double num2) { double sum = 0; //to hold the sum sum = num1 + num2; System.out.printf(“%nThe sum is %.0f“, sum); } method call NOTE: Order matters! 5-38 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 38

5.7 Arguments Passed by Value or by Reference Passed by Value: In Java, all arguments of the primitive data types are passed by value, which means that a copy of an argument’s value is passed to a parameter variable. If a parameter variable is changed inside a method, it has no affect on the original argument. See example: PassByValue.java Passed by Reference: In Java, objects are passed by reference which means the address (memory location) of the object is passed/sent to a parameter variable. Can the original object be affected if it’s changed inside the method? A method’s parameter variables are separate and distinct from the arguments that are listed inside the parentheses of a method call. 5-39 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 39

5.7 Passing Method Arguments: Summary Arguments passed to a value-receiving method must be of the same type as the parameter variables. Arguments of primitive data types are passed by value – meaning a copy of the arguments are sent and stored in the parameter variables so the method can use them. Arguments of complex data types are passed by reference – meaning an address of the object is sent and stored in the parameter variable. Parameter variables are local variables. They belong to the method only. Arguments must be sent in the order of the parameter variables; otherwise, the data stored in the parameter variables are not accurate. There will be a compilation error if there is not the right number or the right type of arguments sent. 5-40 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 40

5.11 Scope of Variable Declarations 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. 5-41 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 41

5.11 Scope of Variable Declarations Global Variables A class variable or class field is declared at the class level right after the class header, following the open brace for the class. It is accessible to all statements (methods) within the class and is known as a global variable. It is declared using access specifiers private – which means only the statements inside the class can use the field and is primarily used when declaring class fields Useful in promoting data hiding Protects variables from corruption or malicious alteration public – which means statements inside or outside the class can use the field protected – which means statements in the same family of classes can use the field Class variables are automatically initialized when declared. E.g.: private int age; //where age will be initialized to 0. 5-42 ©Linda Shepherd, Dept. of ISCS, COB, UTSA 42

5.11 Scope of Declarations Any block may contain variable declarations If a local variable or parameter in a method has the same name as a field of the class, the class field is “hidden” until the block terminates execution Called shadowing The application in Fig. 5.9 demonstrates scoping issues with fields and local variables 5-43 © 1992-2015 by Pearson Education, Inc. All Rights Reserved.

5.11  Scope of Declarations © 1992-2015 by Pearson Education, Inc. All Rights Reserved.

5.11 Scope of Declarations 5-45 © 1992-2010 by Pearson Education, Inc. All Rights Reserved.

5.11 Variable Scope: Summary Variables declared at the class level are global variables or fields. They are scoped to the class. All the code within the class can use these variables. Should be always declared as private unless told otherwise. Variables declared at the method level are local variables. They are scoped to the method only. No other code in the same class can access a method’s variables. Class level and method level variables can have the same name, but the method level variables take precedence. To access the class level variable in the same method use the name of the class followed by a dot operator and the field name. 5-46 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 46

5.12 Overloading Methods Two or more methods in a class may have the same name as long as their parameter lists are different. When this occurs, it is called method overloading. Method overloading is important because sometimes you need several different ways to perform the same operation. 6-47 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 6. 47

5.12 Overloaded Method add public static int add(int num1, int num2) { return num1 + num2; } public static double add(double num1, double num2) double sum = 0.0; sum = num1 + num2; return sum; 6-48 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 6. 48

5.12 Method Signature and Binding A method signature consists of the method’s name and the data types of the method’s parameters, in the order that they appear. The return type is not part of the signature. add(int, int) add(double, double) The process of matching a method call with the correct method is known as static binding. The compiler uses the method signature to determine which version of the overloaded method to bind the call to. Signatures of the add methods from previous slide 6-49 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 6. 49

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

5.12 Method Overloading Error © 1992-2010 by Pearson Education, Inc. All Rights Reserved. 5-52

5.12 Method Overloading: Summary Methods in a program that have the same name are called overloaded methods. For the computer to know which method to call or bind to, the method signature has to be different. The signature is the method name along with the data types of the parameter variables in the order listed. Overloaded methods are helpful when you need to have a method handle or process different types of data. 5-53 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 53

 Documenting Methods A method should always be documented by writing comments that appear just before the method header. The comments should provide a brief explanation of the method’s purpose. The documentation comments begin with /** and end with */. @return and @param tags can be used to describe a method’s return value and/or parameter variables. 5-54 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 54

 @return Tag in Documentation Comments You can provide a description of the return value in your documentation comments by using the @return tag. General format @return Description See example: ValueReturn.java The @return tag in a method’s documentation comment must appear after the general description. The description can span several lines. /** The sum method returns the sum of its two parameters. @param num1 The first number to be added. @param num2 The second number to be added. @return The sum of num1 and num2. */ 5-55 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 55

 @param Tag in Documentation Comments You can provide a description of each parameter in your documentation comments by using the @param tag. General format @param parameterName Description See example: TwoArgs2.java All @param tags in a method’s documentation comment must appear after the general description.The description can span several lines. /** The sum method returns the sum of its two parameters. @param num1 The first number to be added. @param num2 The second number to be added. @return The sum of num1 and num2. */ 5-56 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 56