Chapter 3 Methods ObjectAzizah
Chapter 3 Methods ObjectAzizah
method
public static int max(int num1, int num2) { int z = max(x, y);
header
int result;
method actual parameters
body parameter list (arguments)
if (num1 > num2)
result = num1;
else
result = num2;
return value
return result;
}
Placement of Methods within a
Class
PURPOSE FOR USING
METHOD
• Work on one method can focus the action until you feel it efficient
• Different person can use different method
• Reusable
• Can enhance the program readability because method reduces
complexity.
First Class with main() Calling
nameAndAddress()
Calling Methods
This program demonstrates calling a method max
to return the largest of the int values
pass the value of i
pass the value of j
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
Types of method
• Predefined method
– Math.h
– Character-toString()
– charAt(0)
• User defined method
– one class
– Multiple classes- must create object object instance.
Predefined Classes
• Methods already written and provided by Java
• Organized as a collection of classes (class libraries)
• To use: import package
• Method type: data type of value returned by method
10
Predefined Classes
(continued)
11
User-Defined Methods
• Value-returning methods
– Used in expressions
– Calculate and return a value
– Can save value for later calculation or print value
• modifiers: public, private, protected, static, abstract, final
• returnType: type of the value that the method calculates and returns (using
return statement)
• methodName: Java identifier; name of method
12
Creating Methods that Return
Values
• Return type can be any type used in Java
– Primitive types
– Class types
– void
• Returns nothing
• Method’s type
• return statement
– Causes value to be sent from called method back to calling method
User Defined Method
• There are two types of method
– Void Method
• Defined as non returnable method. It will not return anything to the
calling statement. It will have void keyword in the method header
• Eg: public void Calculate( )
{
}
– Non-Void Method
• Defined as returnable method. It will return a value to the calling
statement. Consist of one return statement. It will have the data
types keyword in the method header.
• Eg: public int Calculate ( )
{
return 23;
}
The predictRaise() Method
The predictRaise() Method
Returning a double
Programming Example:
Largest Number (in single
class)
• Input: set of 10 numbers
• Output: largest of 10 numbers
• Solution
– Get numbers one at a time
– Method largest number: returns the larger of 2 numbers
– For loop: calls method largest number on each number received and
compares to current largest number
• Sample Run:
Enter 10 numbers:
10.5 56.34 73.3 42 22 67 88.55 26 62 11
The largest number is 88.55
• Example
– myEmployee .InfoDetail();
Class Diagram for Bicycle
Bicycle
Bicycle( )
Method
MethodListing
Listing
getOwnerName( ) We
We list the nameand
list the name andthe
the
data type of an argument
data type of an argument
passed
passedtotothe
themethod.
method.
setOwnerName(String)
Multiple Instances
• Once the Bicycle class is defined, we can create multiple instances.
There
Thereare
aretwo
twosource
sourcefiles.
files.
Each class definition
Each class definition isis
stored
storedininaaseparate
separatefile.
file.
BicycleTest.java Bicycle.java
• RoomType.java
• public class RoomType
• {
• // data declaration
• double length;
• double width;
• }
• public void info(){
• System.out.println(“ the hotel name is A++”);
• }
Method without parameter
:: Example ::
class Employee
{
public void CalSalary ( ) No parameter received
{
//…statements…
}
}
class EmployeeTest
{
public static void main (String[ ] args)
{
}
}
Method with parameter
:: Example ::
class Employee
{
public void CalSalary (int basic) //…statements… 1 parameter received
{ as integer
}
}
class EmployeeTest
{
public static void main(String[ ] args)
{
Employee myEmployee = new Employee( );
myEmployee.CalSalary ( 4000); 1 integer argument passed
}
}
Method with parameter
:: Example ::
class Employee
{
public void CalSalary (int basic, double rate) 2 parameters received
{ integer and double
//…statements…
}
}
class EmployeeTest
{
public static void main (String[ ] args)
{
Employee myEmployee = new Employee( );
myEmployee.CalSalary( 4000, 1.7); 2 arguments passed
integer and double
}
}
• NOTE: Argument is passed by location and with correspondence data type to the receiving
parameter
Method with parameter
:: Example ::
class Employee
{
public void CalSalary (int Basic, double Rate) 2 parameters received
{ integer and double
//…statements…
}
}
class EmployeeTest
{
public static void main (String[ ] args)
{
Employee myEmployee = new Employee( );
int Pay = 4000;
double PayRate= 1.7;
myEmployee.CalSalary (Pay, PayRate); 2 arguments passed
integer and double
}
}
::Example::
Non-void method without parameter
import java.util.*;
class Number class NumberTest
{ {
public int output; public static void main (String[ ]args)
{
public int CheckNumber( ) Number myNum = new Number();
{
int num; int result = myNum.CheckNumber();
Scanner sc = new System.out.println(“ The answer
Scanner(System.in); is” + result);
System.out.println(“Enter an }
integer”); }
num = sc.nextInt();
if (num >0)
output=1;
else
if (num < 0)
output= -1;
return output;
}
::Example::
Non-void method with parameter
import java.util.*;
class Number
{ class NumberTest{
public int output; public static void main(String[ ] args)
{
public int CheckNumber(int Scanner s= new Scanner(System.in);
num) Number myNum=new Number();
{ int num;
if (num >0) System.out.println(“Enter an integer”);
output=1; num = s.nextInt();
else int result = myNum.CheckNumber( num);
if (num < 0) System.out.println(“ The answer
is”+result);
output= -1;
}
return output; }
}
}
Example of void Method
Method declaration:
class Vehicle
{
public void DisplayMessage( ) //void method header
{
System.out.println(“Hello, welcome to Vehicle class”);
}
}
Hello, welcome to
Invocation/Calling statement:
Vehicle class
class VehicleTest
{
public static void main(String[ ] args)
{
Vechicle myVehicle = new Vehicle( );// declare and
create object
myVehicle.DisplayMessage( ); //invocation or method call
}
}
Example of Non-void Method
Method declaration:
class Vehicle
{
public int DisplayMessage( ) //non-void method header
{
System.out.println(“Hello, welcome to Vehicle class”);
return 123;
}
}
Hello, welcome to
Invocation/Calling statement: Vehicle class
The output is 123
class VehicleTest
{
public static void main(String[ ] args)
{
Vechicle myVehicle = new Vehicle( );
int result = myVehicle.DisplayMessage( );/invocation
or method call
System.out.println(“ The output is ”+ result);
}
::Check point::
• Create a method header and an invocation statement for the following:
1. In Class Employee, create public method named CalSalary that will
not return anything to the calling statement.
2. In Class Transportation, create a public method named
AirTransport, that will return an integer data type value to the
calling statement.
3. In Class Festival, create a public method named EidFitri that will
return a string data type value to the calling statement.
4. In Class RectangleArea, create a public method named
CalculateArea with no parameter that will return double data type
of area to the calling statement.
5. Modify question 4. Two parameters received of double data type
and return double data type to the calling statement.
::Check point 1::
• Create a method header and an invocation statement for the following:
– In Class Employee, create public method named CalSalary that will not return
anything to the calling statement.
Answer:
class Employee
{
public void CalSalary( )
{
}
}
class EmployeeTest
{
public static void main ( String[ ] args)
{
Employee myEmployee = new Employee( );
//create a class
myEmployee.CalSalary( );
}
::Check point 2::
• Create a method header and an invocation statement for the following:
– In Class Transportation, create a public method named AirTransport, that will return an integer data type
value to the calling statement.
Answer:
class Transportation
{
public int AirTransport( )
{
return 947;
}
}
class TransportationTest
{
public static void main(String[ ] args)
{
Transportation myTransport = new
Transportation( );
int result = myTransport. AirTransport( );
System.out.println (“The output is” + result);
}
::Check point 3::
• Create a method header and an invocation statement for the following:
– In Festival class, create a public method named EidFitri that will return a string data type value to the
calling statement.
Answer:
class Festival
{
public String EidFitri( )
{
return “Rendang”;
}
}
class FestivalTest
{
public static void main (String[ ] args)
{
Festival myFest= new Festival ( );
String raya = myFest. EidFitri( );
System.out.println(“The message is” +raya);
}
Summary
• Method
– Series of statements that carry out a task
– Declaration includes argument type and local name for argument
– Can pass multiple arguments to methods
– Has return type
• Class objects
– Have attributes and methods associated with them
• Instantiate objects that are members of class
B a = new B();