SlideShare a Scribd company logo
1 of 48
PSYC 3663 SAFMEDS TERMS – Assignment 1
Provide a definition for each of the following terms:
1. Functional Relation
2. Applied
3. Generality
4. Conceptually Systematic
5. Explanatory Fiction
6. Behaviour
7. Environment
8. Stimulus
9. Interresponse Time
10. Momentary Time Sampling
11. Whole-Interval Recording
12. Partial-Interval Recording
13. Baseline
14. Positive Reinforcement
15. Negative Reinforcement
16. Motivating Operation
17. Stimulus Control
18. Premack Principle
19. Reinforcer Assessment
20. Unconditioned Reinforcer
21. Conditioned Reinforcer
22. Automatic Reinforcement
23. Discriminative Stimulus (SD)
24. Noncontingent Reinforcement
25. High-Probability Request Sequence
26. Extinction
27. Extinction Burst
28. Spontaneous Recovery
29. Differential Reinforcement
30. Shaping
***SAMPLE OUTPUT***
What is the name of your city? San Antonio
What is your state? Texas
Enter the population of San Antonio: 1409019
Enter the population of TEXAS: 26505637
POPULATION STATISTICS
City: San Antonio
State: TEXAS
City Population: 1,409,019
State Population: 26,505,637
City to State Population: 5.32%
Chapter 5, Methods
Java How to Program,
Late Objects Version, 10/e
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
5-2
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
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
Chapter 5 Topics
2
5-3
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.
3
5-4
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.
Declaration Format:
private static dataType variableName = initializationValue;
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.1 Methods & Variables
4
5-5
5.1 Method Declaration & Header
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
public static void displayMessage()
{
System.out.printf(“%nHello“);
}
Body
Header
public static void displayMessage ()
{
System.out.printf(“%nHello“);
}//This method receives nothing and returns
//nothing.
Method Modifiers
Return Type
Method Name
Parameter List
empty,
i.e., no para-
meter variables
5
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
5.1 Parts of a Method Header
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.
Method Modifiers
1Return Type
Method Name
Parameter List
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
6
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
5.1 Parts of a Method Header
public static void printName (String name)
{
System.out.printf(“Your name is %s.”, name);
}//This is a value-receiving method.
Method Modifiers
Return Type
Method Name
Parameter List
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
with 1 parameter variable
7
5-8
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
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.1 Parts of a Method Header
Method Modifiers
Method Name
Parentheses
Return Type
contain a parameter list
8
5-9
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.
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.
5.1 static and void Methods
9
5-10
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
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.1 static and void Methods
10
5-11
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());
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
Method that returns a name
see slides 5-6
5.1 Value-Returning Methods
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.
11
5-12
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());
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
5.1 Value-Receiving Methods
“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.
12
5-13
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.1 Methods: Summary
13
5-14
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.1 Methods: Summary (cont)
14
5-15
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.1 Methods: Summary (cont)
15
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();
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
5.2 Calling Methods
5-16
Modified By: 1,2Linda Shepherd, Dept. of ISCS, COB, UTSA.
5-17
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();
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.2 Calling Methods: Summary
17
5-18
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);
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.
Class name
Static method
18
5-19
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
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 9.
5.3 static Methods
19
5-20
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).
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 9.
5.3 static Methods
20
5-21
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
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
5.3 static and void Methods
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
//NO IMPORT STMT NEEDED IN Test IF BOTH CLASSES IN
SAME DIRECTORY
21
5-22
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
5.3 static and void Methods
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
//NO IMPORT STMT NEEDED IN Test IF BOTH CLASSES IN
SAME DIRECTORY
demoProg is an object of DemoStaticVoidMethod class.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
22
5-23
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.3 static Members: Summary
23
5-24
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.4 Value-Returning and Value-Receiving Methods
©Linda Shepherd, Dept. of ISCS, COB, UTSA
24
5-25
public static int sum(int num1, int num2)
{
int result = 0;
result = num1 + num2;
return result;
}
This [variable] must be of the same data type as the return type
Return type
The return statement causes the method to end execution and it
returns a value back to the statement that called the method.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
5.4 Defining a Value-Returning and Value-Receiving Method
25
5-26
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.4 Defining a Value-Returning and Value-Receiving Method
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-27
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
27
5-28
total = sum(value1, value2);
}
public static int sum(int num1, int num2)
{
int result = 0;
result = num1 + num2;
return result;
}
20
40
60
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
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.
28
5-29
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.4 Returning a boolean Value
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
29
5-30
5.4 Returning a Reference to a String Object
customerName = fullName("John“, "Martin“);
public static String fullName(String first, String last)
{
String name = null;
name = first + " " + last;
return name;
}
See example:
ReturnString.java
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.
address
“John Martin”
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
These are literal arguments.
30
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
5-33
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.4 Value-Receiving & Value-Returning Methods: Summary
33
5-34
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.
.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.4 Value-Receiving & Value-Returning Methods: Summary
(cont)
34
5-35
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
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
5.7 Passing Arguments to a Value-Receiving Method
35
5-36
5.7 Passing 5 to the displayValue Method
displayValue(5);
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
36
5-37
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
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
37
5-38
5.7 Passing Multiple Arguments
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);
}
The argument 5 is copied to the num1 parameter.
The argument 10 is copied to the num2 parameter.
NOTE: Order matters!
method call
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
38
5-39
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
39
5-40
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.7 Passing Method Arguments: Summary
40
5-41
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
5.11 Scope of Variable Declarations Local Variables
41
5-42
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA
5.11 Scope of Variable Declarations Global Variables
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
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
5-43
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
5.11 Scope of Declarations
© 1992-2010 by Pearson Education, Inc. All Rights Reserved.
5-45
5.11 Scope of Declarations
5-46
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.11 Variable Scope: Summary
46
6-47
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 6.
47
6-48
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;
}
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 6.
48
6-49
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
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-52
5.12 Method Overloading Error
© 1992-2010 by Pearson Education, Inc. All Rights Reserved.
5-53
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.
©Linda Shepherd, Dept. of ISCS, COB, UTSA.
5.12 Method Overloading: Summary
53
5-54
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
54
/**
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
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
55
5-56
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.
Source: Gaddis, Tony, Starting Out with Java From Control
Structures through Objects 4th Edition, Pearson Education Inc.,
2010, Chapter 5.
/**
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.
*/
56

More Related Content

Similar to PSYC 3663 SAFMEDS TERMS – Assignment 1Provide a definition for e.docx

Lecture 4 classes ii
Lecture 4 classes iiLecture 4 classes ii
Lecture 4 classes ii
the_wumberlog
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 

Similar to PSYC 3663 SAFMEDS TERMS – Assignment 1Provide a definition for e.docx (20)

Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class Structure
 
polymorphism method overloading and overriding .pptx
polymorphism method overloading  and overriding .pptxpolymorphism method overloading  and overriding .pptx
polymorphism method overloading and overriding .pptx
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Java Basics
Java BasicsJava Basics
Java Basics
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Lecture 4 classes ii
Lecture 4 classes iiLecture 4 classes ii
Lecture 4 classes ii
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
4. java intro class
4. java intro class4. java intro class
4. java intro class
 
Chap11
Chap11Chap11
Chap11
 
Cis160 Final Review
Cis160 Final ReviewCis160 Final Review
Cis160 Final Review
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or Functions
 

More from amrit47

Apa format1-2 paragraphsreferences It is often said th.docx
Apa format1-2 paragraphsreferences It is often said th.docxApa format1-2 paragraphsreferences It is often said th.docx
Apa format1-2 paragraphsreferences It is often said th.docx
amrit47
 
APA Formatting AssignmentUse the information below to create.docx
APA Formatting AssignmentUse the information below to create.docxAPA Formatting AssignmentUse the information below to create.docx
APA Formatting AssignmentUse the information below to create.docx
amrit47
 
APA style300 words10 maximum plagiarism  Mrs. Smith was.docx
APA style300 words10 maximum plagiarism  Mrs. Smith was.docxAPA style300 words10 maximum plagiarism  Mrs. Smith was.docx
APA style300 words10 maximum plagiarism  Mrs. Smith was.docx
amrit47
 
APA General Format Summary APA (American Psychological.docx
APA General Format Summary APA (American Psychological.docxAPA General Format Summary APA (American Psychological.docx
APA General Format Summary APA (American Psychological.docx
amrit47
 
Appearance When I watched the video of myself, I felt that my b.docx
Appearance When I watched the video of myself, I felt that my b.docxAppearance When I watched the video of myself, I felt that my b.docx
Appearance When I watched the video of myself, I felt that my b.docx
amrit47
 
APA STYLE  follow this textbook answer should be summarize for t.docx
APA STYLE  follow this textbook answer should be summarize for t.docxAPA STYLE  follow this textbook answer should be summarize for t.docx
APA STYLE  follow this textbook answer should be summarize for t.docx
amrit47
 

More from amrit47 (20)

APA, The assignment require a contemporary approach addressing Race,.docx
APA, The assignment require a contemporary approach addressing Race,.docxAPA, The assignment require a contemporary approach addressing Race,.docx
APA, The assignment require a contemporary approach addressing Race,.docx
 
APA style and all questions answered ( no min page requirements) .docx
APA style and all questions answered ( no min page requirements) .docxAPA style and all questions answered ( no min page requirements) .docx
APA style and all questions answered ( no min page requirements) .docx
 
Apa format1-2 paragraphsreferences It is often said th.docx
Apa format1-2 paragraphsreferences It is often said th.docxApa format1-2 paragraphsreferences It is often said th.docx
Apa format1-2 paragraphsreferences It is often said th.docx
 
APA format2-3 pages, double-spaced1. Choose a speech to review. It.docx
APA format2-3 pages, double-spaced1. Choose a speech to review. It.docxAPA format2-3 pages, double-spaced1. Choose a speech to review. It.docx
APA format2-3 pages, double-spaced1. Choose a speech to review. It.docx
 
APA format  httpsapastyle.apa.orghttpsowl.purd.docx
APA format     httpsapastyle.apa.orghttpsowl.purd.docxAPA format     httpsapastyle.apa.orghttpsowl.purd.docx
APA format  httpsapastyle.apa.orghttpsowl.purd.docx
 
APA format2-3 pages, double-spaced1. Choose a speech to review. .docx
APA format2-3 pages, double-spaced1. Choose a speech to review. .docxAPA format2-3 pages, double-spaced1. Choose a speech to review. .docx
APA format2-3 pages, double-spaced1. Choose a speech to review. .docx
 
APA Formatting AssignmentUse the information below to create.docx
APA Formatting AssignmentUse the information below to create.docxAPA Formatting AssignmentUse the information below to create.docx
APA Formatting AssignmentUse the information below to create.docx
 
APA style300 words10 maximum plagiarism  Mrs. Smith was.docx
APA style300 words10 maximum plagiarism  Mrs. Smith was.docxAPA style300 words10 maximum plagiarism  Mrs. Smith was.docx
APA style300 words10 maximum plagiarism  Mrs. Smith was.docx
 
APA format1. What are the three most important takeawayslessons.docx
APA format1. What are the three most important takeawayslessons.docxAPA format1. What are the three most important takeawayslessons.docx
APA format1. What are the three most important takeawayslessons.docx
 
APA General Format Summary APA (American Psychological.docx
APA General Format Summary APA (American Psychological.docxAPA General Format Summary APA (American Psychological.docx
APA General Format Summary APA (American Psychological.docx
 
Appearance When I watched the video of myself, I felt that my b.docx
Appearance When I watched the video of myself, I felt that my b.docxAppearance When I watched the video of myself, I felt that my b.docx
Appearance When I watched the video of myself, I felt that my b.docx
 
apa format1-2 paragraphsreferencesFor this week’s .docx
apa format1-2 paragraphsreferencesFor this week’s .docxapa format1-2 paragraphsreferencesFor this week’s .docx
apa format1-2 paragraphsreferencesFor this week’s .docx
 
APA Format, with 2 references for each question and an assignment..docx
APA Format, with 2 references for each question and an assignment..docxAPA Format, with 2 references for each question and an assignment..docx
APA Format, with 2 references for each question and an assignment..docx
 
APA-formatted 8-10 page research paper which examines the potential .docx
APA-formatted 8-10 page research paper which examines the potential .docxAPA-formatted 8-10 page research paper which examines the potential .docx
APA-formatted 8-10 page research paper which examines the potential .docx
 
APA    STYLE 1.Define the terms multiple disabilities and .docx
APA    STYLE 1.Define the terms multiple disabilities and .docxAPA    STYLE 1.Define the terms multiple disabilities and .docx
APA    STYLE 1.Define the terms multiple disabilities and .docx
 
APA STYLE  follow this textbook answer should be summarize for t.docx
APA STYLE  follow this textbook answer should be summarize for t.docxAPA STYLE  follow this textbook answer should be summarize for t.docx
APA STYLE  follow this textbook answer should be summarize for t.docx
 
APA7Page length 3-4, including Title Page and Reference Pag.docx
APA7Page length 3-4, including Title Page and Reference Pag.docxAPA7Page length 3-4, including Title Page and Reference Pag.docx
APA7Page length 3-4, including Title Page and Reference Pag.docx
 
APA format, 2 pagesThree general sections 1. an article s.docx
APA format, 2 pagesThree general sections 1. an article s.docxAPA format, 2 pagesThree general sections 1. an article s.docx
APA format, 2 pagesThree general sections 1. an article s.docx
 
APA Style with minimum of 450 words, with annotations, quotation.docx
APA Style with minimum of 450 words, with annotations, quotation.docxAPA Style with minimum of 450 words, with annotations, quotation.docx
APA Style with minimum of 450 words, with annotations, quotation.docx
 
APA FORMAT1.  What are the three most important takeawayslesson.docx
APA FORMAT1.  What are the three most important takeawayslesson.docxAPA FORMAT1.  What are the three most important takeawayslesson.docx
APA FORMAT1.  What are the three most important takeawayslesson.docx
 

Recently uploaded

Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 

PSYC 3663 SAFMEDS TERMS – Assignment 1Provide a definition for e.docx

  • 1. PSYC 3663 SAFMEDS TERMS – Assignment 1 Provide a definition for each of the following terms: 1. Functional Relation 2. Applied 3. Generality 4. Conceptually Systematic 5. Explanatory Fiction 6. Behaviour 7. Environment 8. Stimulus 9. Interresponse Time 10. Momentary Time Sampling 11. Whole-Interval Recording 12. Partial-Interval Recording 13. Baseline 14. Positive Reinforcement 15. Negative Reinforcement 16. Motivating Operation 17. Stimulus Control 18. Premack Principle 19. Reinforcer Assessment 20. Unconditioned Reinforcer 21. Conditioned Reinforcer 22. Automatic Reinforcement 23. Discriminative Stimulus (SD) 24. Noncontingent Reinforcement 25. High-Probability Request Sequence 26. Extinction 27. Extinction Burst 28. Spontaneous Recovery 29. Differential Reinforcement 30. Shaping
  • 2. ***SAMPLE OUTPUT*** What is the name of your city? San Antonio What is your state? Texas Enter the population of San Antonio: 1409019 Enter the population of TEXAS: 26505637 POPULATION STATISTICS City: San Antonio State: TEXAS City Population: 1,409,019 State Population: 26,505,637 City to State Population: 5.32% Chapter 5, Methods Java How to Program, Late Objects Version, 10/e © 1992-2015 by Pearson Education, Inc. All Rights Reserved.
  • 3. 5-2 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 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. Chapter 5 Topics 2 5-3 5.1 Why Write Methods? Divide and Conquer: Methods break a problem down into small manageable pieces. A method
  • 4. 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. 3 5-4 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.
  • 5. 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. Declaration Format: private static dataType variableName = initializationValue; ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.1 Methods & Variables 4 5-5 5.1 Method Declaration & Header Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. public static void displayMessage() { System.out.printf(“%nHello“); } Body
  • 6. Header public static void displayMessage () { System.out.printf(“%nHello“); }//This method receives nothing and returns //nothing. Method Modifiers Return Type Method Name Parameter List empty, i.e., no para- meter variables
  • 7. 5 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 5.1 Parts of a Method Header 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. Method Modifiers 1Return Type Method Name Parameter List
  • 8. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 6 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 5.1 Parts of a Method Header public static void printName (String name) { System.out.printf(“Your name is %s.”, name); }//This is a value-receiving method. Method Modifiers
  • 9. Return Type Method Name Parameter List Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. with 1 parameter variable 7 5-8 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 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.1 Parts of a Method Header
  • 10. Method Modifiers Method Name Parentheses Return Type contain a parameter list 8 5-9 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. Source: 1Gaddis, Tony, Starting Out with Java From Control
  • 11. Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 2,3,4Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.1 static and void Methods 9 5-10 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 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();
  • 12. }//END setName() }//END APPLICATION CLASS DemoStaticVoidMethod 5.1 static and void Methods 10 5-11 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()); Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. Method that returns a name see slides 5-6 5.1 Value-Returning Methods 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.
  • 13. 11 5-12 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()); Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 5.1 Value-Receiving Methods “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.
  • 14. 12 5-13 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.1 Methods: Summary
  • 15. 13 5-14 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.1 Methods: Summary (cont) 14 5-15
  • 16. 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.1 Methods: Summary (cont) 15 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();
  • 17. © 1992-2015 by Pearson Education, Inc. All Rights Reserved. 5.2 Calling Methods 5-16 Modified By: 1,2Linda Shepherd, Dept. of ISCS, COB, UTSA. 5-17 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(); ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.2 Calling Methods: Summary
  • 18. 17 5-18 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); 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. Class name Static method
  • 19. 18 5-19 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 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 9. 5.3 static Methods 19 5-20 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). Source: Gaddis, Tony, Starting Out with Java From Control
  • 20. Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 9. 5.3 static Methods 20 5-21 ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 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 5.3 static and void Methods public class TestDemoStaticVoidMethod { public static void main(String[] args) { String greeting = “Hello”; System.out.printf(“%s %s!”, greeting, DemoStaticVoidMethod.setName()); System.exit(0);
  • 21. }//END main() }//END APPLICATION CLASS TestDemoStaticVoidMethod //NO IMPORT STMT NEEDED IN Test IF BOTH CLASSES IN SAME DIRECTORY 21 5-22 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 5.3 static and void Methods public class TestDemoStaticVoidMethod { public static void main(String[] args) { DemoStaticVoidMethod demoProg = new DemoStaticVoidMethod(); String greeting = “Hello”; System.out.printf(“%s %s!”, greeting, demoProg.setName());
  • 22. System.exit(0); }//END main() }//END APPLICATION CLASS TestDemoStaticVoidMethod //NO IMPORT STMT NEEDED IN Test IF BOTH CLASSES IN SAME DIRECTORY demoProg is an object of DemoStaticVoidMethod class. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 22 5-23 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA.
  • 23. 5.3 static Members: Summary 23 5-24 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.4 Value-Returning and Value-Receiving Methods ©Linda Shepherd, Dept. of ISCS, COB, UTSA 24 5-25
  • 24. public static int sum(int num1, int num2) { int result = 0; result = num1 + num2; return result; } This [variable] must be of the same data type as the return type Return type The return statement causes the method to end execution and it returns a value back to the statement that called the method. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 5.4 Defining a Value-Returning and Value-Receiving Method 25 5-26 public static int sum(int num1, int num2)
  • 25. { 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.4 Defining a Value-Returning and Value-Receiving Method 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-27 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.
  • 26. 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 27 5-28 total = sum(value1, value2); } public static int sum(int num1, int num2) { int result = 0; result = num1 + num2; return result; } 20
  • 27. 40 60 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 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. 28 5-29 Sometimes we need to write methods to test arguments for validity and return true or false public static boolean isValid( int number ) {
  • 28. 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.4 Returning a boolean Value Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 29 5-30 5.4 Returning a Reference to a String Object customerName = fullName("John“, "Martin“); public static String fullName(String first, String last) {
  • 29. String name = null; name = first + " " + last; return name; } See example: ReturnString.java 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. address “John Martin” Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. These are literal arguments.
  • 30. 30 © 1992-2015 by Pearson Education, Inc. All Rights Reserved. © 1992-2015 by Pearson Education, Inc. All Rights Reserved. 5-33 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
  • 31. 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.4 Value-Receiving & Value-Returning Methods: Summary 33 5-34 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
  • 32. 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. . ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.4 Value-Receiving & Value-Returning Methods: Summary (cont) 34 5-35 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 Source: Gaddis, Tony, Starting Out with Java From Control
  • 33. Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 1,2Linda Shepherd, Dept. of ISCS, COB, UTSA 5.7 Passing Arguments to a Value-Receiving Method 35 5-36 5.7 Passing 5 to the displayValue Method displayValue(5); 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5.
  • 34. 36 5-37 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 Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 37
  • 35. 5-38 5.7 Passing Multiple Arguments 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); } The argument 5 is copied to the num1 parameter. The argument 10 is copied to the num2 parameter. NOTE: Order matters! method call Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5.
  • 36. 38 5-39 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 39 5-40
  • 37. 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.7 Passing Method Arguments: Summary 40 5-41 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
  • 38. 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. 5.11 Scope of Variable Declarations Local Variables 41 5-42 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
  • 39. 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA 5.11 Scope of Variable Declarations Global Variables 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 © 1992-2015 by Pearson Education, Inc. All Rights Reserved. 5-43
  • 40. © 1992-2015 by Pearson Education, Inc. All Rights Reserved. 5.11 Scope of Declarations © 1992-2010 by Pearson Education, Inc. All Rights Reserved. 5-45 5.11 Scope of Declarations 5-46 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.
  • 41. 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.11 Variable Scope: Summary 46 6-47 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 6.
  • 42. 47 6-48 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; } Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 6. 48
  • 43. 6-49 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 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.
  • 44. © 1992-2015 by Pearson Education, Inc. All Rights Reserved. 5-52 5.12 Method Overloading Error © 1992-2010 by Pearson Education, Inc. All Rights Reserved. 5-53 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.
  • 45. 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. ©Linda Shepherd, Dept. of ISCS, COB, UTSA. 5.12 Method Overloading: Summary 53 5-54 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5.
  • 46. 54 /** 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 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5.
  • 47. 55 5-56 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. Source: Gaddis, Tony, Starting Out with Java From Control Structures through Objects 4th Edition, Pearson Education Inc., 2010, Chapter 5. /** 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. */
  • 48. 56