SlideShare a Scribd company logo
1
***INVALID & VALID PARTY & FAVOR CHOICES***
Party Themes
1. Anniversary
2. Birthday
3. Graduation
Enter your theme: 4
Invalid theme! Try again.
Party Themes
1. Anniversary
2. Birthday
3. Graduation
Enter your theme: 1
How many people will be invited to your Anniversary party? 10
Make your party favor selections. The cost is per guest.
1. Party Favors for Women $3.00
2. Party Favors for Men $3.00
3. Party Favors for Kids $2.00
4. Party Favors for Teenages $3.00
5. Exit
Enter your choice: 1
How many of your guests are women? 4
Do you want to make another party favor selection?
Enter Y or N: Y
Make your party favor selections. The cost is per guest.
1. Party Favors for Women $3.00
2. Party Favors for Men $3.00
3. Party Favors for Kids $2.00
4. Party Favors for Teenages $3.00
5. Exit
Enter your choice: 2
How many of your guests are men? 5
Do you want to make another party favor selection?
Enter Y or N: N
The number of favors you bought doesn't equal the number of
guests.
Run through the selection of the favors again.
Make your party favor selections. The cost is per guest.
1. Party Favors for Women $3.00
2. Party Favors for Men $3.00
3. Party Favors for Kids $2.00
2
4. Party Favors for Teenages $3.00
5. Exit
Enter your choice: 1
How many of your guests are women? 5
Do you want to make another party favor selection?
Enter Y or N: y
Make your party favor selections. The cost is per guest.
1. Party Favors for Women $3.00
2. Party Favors for Men $3.00
3. Party Favors for Kids $2.00
4. Party Favors for Teenages $3.00
5. Exit
Enter your choice: 2
How many of your guests are men? 5
Do you want to make another party favor selection?
Enter Y or N: n
Party: Anniversary
Cost: $150.00
IS 2031: LE 5.3 - Methods Student
Name:
1. Write the following static methods. Assume the reference
variable input for the Scanner class and any global variables
mentioned are already declared. All other variables will have to
be declared as local unless they are parameter variables. Use
printf.
a. A method that prompts for the party theme and returns the
theme. Print the message “Invalid theme! Try again.” if the
theme is out of range. Re-prompt until a valid entry is made.
Prompt: Party Themes
1. Anniversary
2. Birthday
3. Graduation
Enter your theme:
b. A value-receiving method that accepts the theme, and asks
for the number of guests and returns that number.
Prompt: How many people will be invited to your
xxxxxxxxxxxx party? where the Xs is the name of the theme
from 1a. The variable storing the name of the theme is global.
c. A value-receiving method that accepts the number of guests
and returns the cost for the food. Assume the cost per guest is
$12.00.
d.
A method that accepts the number of guests, prompts for party
favors and returns the cost. Allow for multiple party favors to
be chosen.
Prompt: Make your party favor selections. The cost is per
guest.
1. Party Favors for Women $3.00
2. Party Favors for Men $3.00
3. Party Favors for Kids $2.00
4. Party Favors for Teenagers $3.00
5. Exit
Enter your choice:
e. A method that accepts the cost for the food and the party
favors and calculates the total cost for the party and prints it:
(
where
the Xs is the
party theme
and the Zs is the total cost.
)
Party: Xxxxxxxxxxxxxxx
Cost: $Z,ZZ9.99
2. Write statements that will call each of the methods you
coded above. Store the values returned by the value-returning
methods in variables local to the main() where main() is in the
same class.
a.
b.
c.
d.
e.
1
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 1 INVALID & VALID PARTY & FAVOR CHOICES P.docx

Main Task Submit the Following 1. Calculate the sample size.docx
Main Task Submit the Following 1. Calculate the sample size.docxMain Task Submit the Following 1. Calculate the sample size.docx
Main Task Submit the Following 1. Calculate the sample size.docx
infantsuk
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
Cs141 mid termexam2_fall2017_v1.1
Cs141 mid termexam2_fall2017_v1.1Cs141 mid termexam2_fall2017_v1.1
Cs141 mid termexam2_fall2017_v1.1
Fahadaio
 
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
Eduardo Bergavera
 
Sample prac exam2013
Sample prac exam2013Sample prac exam2013
Sample prac exam2013
hccit
 
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
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
Md Showrov Ahmed
 
Lecture Slides (1).pptx
Lecture Slides (1).pptxLecture Slides (1).pptx
Lecture Slides (1).pptx
HumzaWaris1
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
Hemajava
HemajavaHemajava
Hemajava
SangeethaSasi1
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
sanya6900
 
12422, 744 PM Assignment_3localhost8888nbconverthtml.docx
12422, 744 PM Assignment_3localhost8888nbconverthtml.docx12422, 744 PM Assignment_3localhost8888nbconverthtml.docx
12422, 744 PM Assignment_3localhost8888nbconverthtml.docx
robert345678
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
IIUM
 
JAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptx
JAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptxJAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptx
JAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptx
JohnMarkDeJesus4
 
Business Research Methods. data collection preparation and analysis
Business Research Methods. data collection preparation and analysisBusiness Research Methods. data collection preparation and analysis
Business Research Methods. data collection preparation and analysis
Ahsan Khan Eco (Superior College)
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
Abid Kohistani
 
Examf cs-cs141-2-17 solution
Examf cs-cs141-2-17 solutionExamf cs-cs141-2-17 solution
Examf cs-cs141-2-17 solution
Fahadaio
 
9781439035665 ppt ch07
9781439035665 ppt ch079781439035665 ppt ch07
9781439035665 ppt ch07
Terry Yoast
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
Ahmad Idrees
 

Similar to 1 INVALID & VALID PARTY & FAVOR CHOICES P.docx (20)

Main Task Submit the Following 1. Calculate the sample size.docx
Main Task Submit the Following 1. Calculate the sample size.docxMain Task Submit the Following 1. Calculate the sample size.docx
Main Task Submit the Following 1. Calculate the sample size.docx
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Cs141 mid termexam2_fall2017_v1.1
Cs141 mid termexam2_fall2017_v1.1Cs141 mid termexam2_fall2017_v1.1
Cs141 mid termexam2_fall2017_v1.1
 
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
 
Sample prac exam2013
Sample prac exam2013Sample prac exam2013
Sample prac exam2013
 
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 present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
Lecture Slides (1).pptx
Lecture Slides (1).pptxLecture Slides (1).pptx
Lecture Slides (1).pptx
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
Hemajava
HemajavaHemajava
Hemajava
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 
12422, 744 PM Assignment_3localhost8888nbconverthtml.docx
12422, 744 PM Assignment_3localhost8888nbconverthtml.docx12422, 744 PM Assignment_3localhost8888nbconverthtml.docx
12422, 744 PM Assignment_3localhost8888nbconverthtml.docx
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
JAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptx
JAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptxJAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptx
JAVA METHOD AND FUNCTION DIVIDE AND SHORT.pptx
 
Business Research Methods. data collection preparation and analysis
Business Research Methods. data collection preparation and analysisBusiness Research Methods. data collection preparation and analysis
Business Research Methods. data collection preparation and analysis
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 
Examf cs-cs141-2-17 solution
Examf cs-cs141-2-17 solutionExamf cs-cs141-2-17 solution
Examf cs-cs141-2-17 solution
 
9781439035665 ppt ch07
9781439035665 ppt ch079781439035665 ppt ch07
9781439035665 ppt ch07
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 

More from mercysuttle

1 Question Information refinement means taking the system requi.docx
1 Question Information refinement means taking the system requi.docx1 Question Information refinement means taking the system requi.docx
1 Question Information refinement means taking the system requi.docx
mercysuttle
 
1 pageApaSourcesDiscuss how an organization’s marketing i.docx
1 pageApaSourcesDiscuss how an organization’s marketing i.docx1 pageApaSourcesDiscuss how an organization’s marketing i.docx
1 pageApaSourcesDiscuss how an organization’s marketing i.docx
mercysuttle
 
1 R120V11Vac0Vdc R2100VC13mE.docx
1 R120V11Vac0Vdc R2100VC13mE.docx1 R120V11Vac0Vdc R2100VC13mE.docx
1 R120V11Vac0Vdc R2100VC13mE.docx
mercysuttle
 
1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx
1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx
1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx
mercysuttle
 
1 Politicking is less likely in organizations that have· adecl.docx
1 Politicking is less likely in organizations that have· adecl.docx1 Politicking is less likely in organizations that have· adecl.docx
1 Politicking is less likely in organizations that have· adecl.docx
mercysuttle
 
1 page2 sourcesReflect on the important performance management.docx
1 page2 sourcesReflect on the important performance management.docx1 page2 sourcesReflect on the important performance management.docx
1 page2 sourcesReflect on the important performance management.docx
mercysuttle
 
1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx
1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx
1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx
mercysuttle
 
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
mercysuttle
 
1 Objectives Genetically transform bacteria with for.docx
1 Objectives Genetically transform bacteria with for.docx1 Objectives Genetically transform bacteria with for.docx
1 Objectives Genetically transform bacteria with for.docx
mercysuttle
 
1 of 8 Student name ……………. St.docx
1 of 8 Student name …………….               St.docx1 of 8 Student name …………….               St.docx
1 of 8 Student name ……………. St.docx
mercysuttle
 
1 MATH 106 QUIZ 4 Due b.docx
1 MATH 106 QUIZ 4                                 Due b.docx1 MATH 106 QUIZ 4                                 Due b.docx
1 MATH 106 QUIZ 4 Due b.docx
mercysuttle
 
1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx
1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx
1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx
mercysuttle
 
1 NAME__________________ EXAM 1 Directi.docx
1 NAME__________________ EXAM 1  Directi.docx1 NAME__________________ EXAM 1  Directi.docx
1 NAME__________________ EXAM 1 Directi.docx
mercysuttle
 
1 Name .docx
1 Name                                                 .docx1 Name                                                 .docx
1 Name .docx
mercysuttle
 
1 pageapasources2Third Party LogisticsBriefly describe .docx
1 pageapasources2Third Party LogisticsBriefly describe .docx1 pageapasources2Third Party LogisticsBriefly describe .docx
1 pageapasources2Third Party LogisticsBriefly describe .docx
mercysuttle
 
1 Pageapasources2Review the Food Environment Atlas maps for.docx
1 Pageapasources2Review the Food Environment Atlas maps for.docx1 Pageapasources2Review the Food Environment Atlas maps for.docx
1 Pageapasources2Review the Food Environment Atlas maps for.docx
mercysuttle
 
1 Lab 3 Newton’s Second Law of Motion Introducti.docx
1 Lab 3 Newton’s Second Law of Motion  Introducti.docx1 Lab 3 Newton’s Second Law of Motion  Introducti.docx
1 Lab 3 Newton’s Second Law of Motion Introducti.docx
mercysuttle
 
1 Marks 2 A person can be prosecuted for both an attempt and .docx
1 Marks 2 A person can be prosecuted for both an attempt and .docx1 Marks 2 A person can be prosecuted for both an attempt and .docx
1 Marks 2 A person can be prosecuted for both an attempt and .docx
mercysuttle
 
1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx
1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx
1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx
mercysuttle
 
1 List of Acceptable Primary Resources for the Week 3 .docx
1 List of Acceptable Primary Resources for the Week 3 .docx1 List of Acceptable Primary Resources for the Week 3 .docx
1 List of Acceptable Primary Resources for the Week 3 .docx
mercysuttle
 

More from mercysuttle (20)

1 Question Information refinement means taking the system requi.docx
1 Question Information refinement means taking the system requi.docx1 Question Information refinement means taking the system requi.docx
1 Question Information refinement means taking the system requi.docx
 
1 pageApaSourcesDiscuss how an organization’s marketing i.docx
1 pageApaSourcesDiscuss how an organization’s marketing i.docx1 pageApaSourcesDiscuss how an organization’s marketing i.docx
1 pageApaSourcesDiscuss how an organization’s marketing i.docx
 
1 R120V11Vac0Vdc R2100VC13mE.docx
1 R120V11Vac0Vdc R2100VC13mE.docx1 R120V11Vac0Vdc R2100VC13mE.docx
1 R120V11Vac0Vdc R2100VC13mE.docx
 
1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx
1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx
1 PSYC499SeniorCapstoneTheImpactoftheSocial.docx
 
1 Politicking is less likely in organizations that have· adecl.docx
1 Politicking is less likely in organizations that have· adecl.docx1 Politicking is less likely in organizations that have· adecl.docx
1 Politicking is less likely in organizations that have· adecl.docx
 
1 page2 sourcesReflect on the important performance management.docx
1 page2 sourcesReflect on the important performance management.docx1 page2 sourcesReflect on the important performance management.docx
1 page2 sourcesReflect on the important performance management.docx
 
1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx
1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx
1 of 402.5 PointsUse Cramer’s Rule to solve the following syst.docx
 
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx1 of 6  LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
1 of 6 LAB 5 IMAGE FILTERING ECE180 Introduction to.docx
 
1 Objectives Genetically transform bacteria with for.docx
1 Objectives Genetically transform bacteria with for.docx1 Objectives Genetically transform bacteria with for.docx
1 Objectives Genetically transform bacteria with for.docx
 
1 of 8 Student name ……………. St.docx
1 of 8 Student name …………….               St.docx1 of 8 Student name …………….               St.docx
1 of 8 Student name ……………. St.docx
 
1 MATH 106 QUIZ 4 Due b.docx
1 MATH 106 QUIZ 4                                 Due b.docx1 MATH 106 QUIZ 4                                 Due b.docx
1 MATH 106 QUIZ 4 Due b.docx
 
1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx
1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx
1 MN6003 Levis Strauss Case Adapted from Does Levi St.docx
 
1 NAME__________________ EXAM 1 Directi.docx
1 NAME__________________ EXAM 1  Directi.docx1 NAME__________________ EXAM 1  Directi.docx
1 NAME__________________ EXAM 1 Directi.docx
 
1 Name .docx
1 Name                                                 .docx1 Name                                                 .docx
1 Name .docx
 
1 pageapasources2Third Party LogisticsBriefly describe .docx
1 pageapasources2Third Party LogisticsBriefly describe .docx1 pageapasources2Third Party LogisticsBriefly describe .docx
1 pageapasources2Third Party LogisticsBriefly describe .docx
 
1 Pageapasources2Review the Food Environment Atlas maps for.docx
1 Pageapasources2Review the Food Environment Atlas maps for.docx1 Pageapasources2Review the Food Environment Atlas maps for.docx
1 Pageapasources2Review the Food Environment Atlas maps for.docx
 
1 Lab 3 Newton’s Second Law of Motion Introducti.docx
1 Lab 3 Newton’s Second Law of Motion  Introducti.docx1 Lab 3 Newton’s Second Law of Motion  Introducti.docx
1 Lab 3 Newton’s Second Law of Motion Introducti.docx
 
1 Marks 2 A person can be prosecuted for both an attempt and .docx
1 Marks 2 A person can be prosecuted for both an attempt and .docx1 Marks 2 A person can be prosecuted for both an attempt and .docx
1 Marks 2 A person can be prosecuted for both an attempt and .docx
 
1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx
1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx
1 Marks 1 Post Traumatic Stress Disorder (PTSD)Choose one .docx
 
1 List of Acceptable Primary Resources for the Week 3 .docx
1 List of Acceptable Primary Resources for the Week 3 .docx1 List of Acceptable Primary Resources for the Week 3 .docx
1 List of Acceptable Primary Resources for the Week 3 .docx
 

Recently uploaded

Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 

Recently uploaded (20)

Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 

1 INVALID & VALID PARTY & FAVOR CHOICES P.docx

  • 1. 1 ***INVALID & VALID PARTY & FAVOR CHOICES*** Party Themes 1. Anniversary 2. Birthday 3. Graduation Enter your theme: 4 Invalid theme! Try again. Party Themes 1. Anniversary 2. Birthday 3. Graduation Enter your theme: 1 How many people will be invited to your Anniversary party? 10 Make your party favor selections. The cost is per guest. 1. Party Favors for Women $3.00 2. Party Favors for Men $3.00 3. Party Favors for Kids $2.00 4. Party Favors for Teenages $3.00
  • 2. 5. Exit Enter your choice: 1 How many of your guests are women? 4 Do you want to make another party favor selection? Enter Y or N: Y Make your party favor selections. The cost is per guest. 1. Party Favors for Women $3.00 2. Party Favors for Men $3.00 3. Party Favors for Kids $2.00 4. Party Favors for Teenages $3.00 5. Exit Enter your choice: 2 How many of your guests are men? 5 Do you want to make another party favor selection? Enter Y or N: N The number of favors you bought doesn't equal the number of guests. Run through the selection of the favors again. Make your party favor selections. The cost is per guest. 1. Party Favors for Women $3.00 2. Party Favors for Men $3.00 3. Party Favors for Kids $2.00
  • 3. 2 4. Party Favors for Teenages $3.00 5. Exit Enter your choice: 1 How many of your guests are women? 5 Do you want to make another party favor selection? Enter Y or N: y Make your party favor selections. The cost is per guest. 1. Party Favors for Women $3.00 2. Party Favors for Men $3.00 3. Party Favors for Kids $2.00 4. Party Favors for Teenages $3.00 5. Exit Enter your choice: 2 How many of your guests are men? 5 Do you want to make another party favor selection? Enter Y or N: n Party: Anniversary Cost: $150.00 IS 2031: LE 5.3 - Methods Student Name:
  • 4. 1. Write the following static methods. Assume the reference variable input for the Scanner class and any global variables mentioned are already declared. All other variables will have to be declared as local unless they are parameter variables. Use printf. a. A method that prompts for the party theme and returns the theme. Print the message “Invalid theme! Try again.” if the theme is out of range. Re-prompt until a valid entry is made. Prompt: Party Themes 1. Anniversary 2. Birthday 3. Graduation Enter your theme: b. A value-receiving method that accepts the theme, and asks for the number of guests and returns that number. Prompt: How many people will be invited to your xxxxxxxxxxxx party? where the Xs is the name of the theme from 1a. The variable storing the name of the theme is global.
  • 5. c. A value-receiving method that accepts the number of guests and returns the cost for the food. Assume the cost per guest is $12.00. d. A method that accepts the number of guests, prompts for party favors and returns the cost. Allow for multiple party favors to be chosen. Prompt: Make your party favor selections. The cost is per guest. 1. Party Favors for Women $3.00 2. Party Favors for Men $3.00 3. Party Favors for Kids $2.00 4. Party Favors for Teenagers $3.00 5. Exit Enter your choice: e. A method that accepts the cost for the food and the party favors and calculates the total cost for the party and prints it: ( where the Xs is the party theme and the Zs is the total cost.
  • 6. ) Party: Xxxxxxxxxxxxxxx Cost: $Z,ZZ9.99 2. Write statements that will call each of the methods you coded above. Store the values returned by the value-returning methods in variables local to the main() where main() is in the same class. a. b. c. d. e. 1 Chapter 5, Methods Java How to Program, Late Objects Version, 10/e © 1992-2015 by Pearson Education, Inc. All Rights Reserved.
  • 7. 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
  • 8. 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).
  • 9. 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“);
  • 10. } 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,
  • 11. 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
  • 12. 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.
  • 13. 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;
  • 14. 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.
  • 15. 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);
  • 16. }//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
  • 17. 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.
  • 18. 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
  • 19. 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)
  • 20. 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();
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. { 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 {
  • 26. 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.
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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;
  • 31. } 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
  • 32. 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
  • 33. 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.
  • 34. 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.
  • 35. 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.
  • 36. 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
  • 37. 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.
  • 38. 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.
  • 39. 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.
  • 40. 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.
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. © 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
  • 45. 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.
  • 46. 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.
  • 47. 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
  • 48. © 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.
  • 49. 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
  • 50. 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.,
  • 51. 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. */
  • 52. 56