3.5 Java Method
Learning Outcome
(a) Introduction to Java Method
2
3.5.1 Introduction to Java Method
Method - Example of Diagram
How is method is invoked or called in a program?
3
What is Method?
Cara method:
import java.util.Scanner;
class Tambah {
public static void main(String [ ] args )
{
Scanner sc=new Scanner(System.in);� Tambah mc=new Tambah();
int num1, num2, result;
System.out.print(“Enter 2 numbers”);
num1 = sc.nextInt();
num2 = sc.nextInt();
result = mc.kiraadd(num1 , num2);
System.out.println(result);
} // close main
int kiraadd(int number1, int number2)
{
return number1 + number2;
} // close method
} // close class
Cara biasa:
import java.util.Scanner;
class Tambah {
public static void main(String [ ] args)
{
Scanner sc=new Scanner(System.in);�
int num1, num2, result;
System.out.print(“Enter 2 numbers”);� num1 = sc.nextInt();
num2 = sc.nextInt();
result = num1 + num2;
System.out.println(result);
} // close main
} // close class
4
So why do we need a method?
import java.util.Scanner;
class Tambah {
public static void main(String [ ] args )
{
Scanner sc=new Scanner(System.in);�Tambah mc=new Tambah();
int num1, num2, mark1, mark2, salary1, salary2,
add, totalmark, totalsalary;
�num1 = sc.nextInt();
num2 = sc.nextInt();
mark1 = sc.nextInt();
mark2 = sc.nextInt();
salary1 = sc.nextInt();
salary2 = sc.nextInt();
5
add = mc.kiraadd(num1, num2);
totalmark = mc.kiraadd(mark1, mark2);
totalsalary = mc.kiraadd(salary1, salary2);
System.out.println(add);
System.out.println(totalmark);
System.out.println(totalsalary);
} // close main
int kiraadd(int number1, int number2)
{ int total;
total = number2 + number2 ;
return total;
} // close method
} // close class
So why do we need a method?
A method in Java is a group of code defined with a name, so instead of repeatedly writing that same group of code everywhere , we can execute that group of code by just calling the name of the method.
FUNCTION METHOD:
This helps in reuse of the code and also it helps to organize and simplify coding.
So, advantages of method is :
time saver, reusability of code and make code more readable and
easier to debug /find error.
6
Types of Java Methods
There are two (2) types of method:
7
Standard Library Methods
The standard library methods are built-in methods in Java that are readily available for use.
Java has standard library of classes and methods, organized in packages
(e.g java.util.Scanner).In order to use them, we “import” the packages.
For example : import java.util.Scanner;
By default, java.lang package is automatically imported, in any java programs.
In particular, classes String, Math and Character are included in java.lang.
For example,
8
Standard Library Method
import java.util.Scanner;
public class Square1
{
public static void main(String[ ] args)
{
System.out.print("Square of 7 is: " + Math. pow(7, 2) );
}
}
9
Output:
Square of 7 is: 49
Standard Library Method : pow(7,2)
User-defined Methods
User-defined method is a method that is defined by the programmer.
Before you can call a method, you need to define it based on the general structure of methods containing:
10
3.5.2 Method Definitions and Calls
Learning Outcomes
At the end of this topic, you should be able to:
(b) Method Definitions and Calls
11
Method Definitions
General Format to define Method
returnType methodName (int parameters, char parameter)
{
// method-body
}
A user-defined method must first be defined before it is called.
Method definition consists of:
12
Example 1:
void cetakNo (int num) {
System.out.println(num);
}
Example 2:
boolean logicA (char huruf)
{
if ( huruf == ‘a’ )
return true;
else
return false;
}
Examples of method definition
This method:
13
void displayMessage()
{
System.out.print(“Hello, World!”);
}
Method Return Types
return type is based on the type of value returned by the method
14
Example ( return value integer):
int add (int num1, int num2)
{
return num1 + num2;
}
Example (return value character):
char semakGred(int mark)
{ char grade;
if (mark>=80)
grade = ‘A’;
return grade;
}
Example ( return value double):
double bahagi (int num1, int num2)
{
return num1 / num2 ;
}
Method Return Types
return type is based on the type of value returned by the method
15
Example 2 (return value char):
char hantarAksara( )
{ char huruf;
Scanner sc= new Scanner(System.in);
huruf = sc.next().charAt(0);
return huruf ;
}
Example 1 (No return value):
void add (int num1, int num2)
{
System.out.println(num1 + num2) ;
}
Method Name
The name of the method is an identifier.
You can give any name to a method. However, it is more conventional to name it after the tasks it performs.
For example:
compareNumbers, computePrice, calculateArea, findMinimum, paparStatus, kiraJumlah
usually represents the task performed by the method.
16
Parameters
A parameter is a placeholder in the called method to hold value of the passed arguments.
If there are values passed, then the values will be assigned to the parameters accordingly.
You can pass any number of arguments to a method.
However, methods may or may not have parameters.
17
Example:
int add(int num1, int num2)
{
return num1 + num2;
}
Example:
void paparStatus(double mark, char grade) {
System.out.println(“mark is :” +mark) ;
System.out.println(“grade is :” +grade) ;
}
void displayMessage( )
{ System.out.print(“No parameter ”); }
Method Calls
A method must be called based on exactly how the method was defined.
18
General Format of Method Calls
objectName.methodName(arguments);
Example:
NamaClass mc=new NamaClass(); // create object
mc.add(num1, num2); // method call
Method Calls
There are two ways to call a method, which depends on whether:
19
If a method returns a value, then the method should either:
Be assigned to (=) a variable of the same data type,
variableName = obj.methodName();
Printed using
System.out.print(obj.methodName());
Method call with return value
import java.util.Scanner;
class Tambah {
public static void main(String [ ] args )
{
Scanner sc=new Scanner(System.in);
Tambah mc=new Tambah( ); // create objectName
int num1, num2, result;
�num1 = sc.nextInt();
num2 = sc.nextInt();
result= mc.kiraadd(num1, num2); // method call
System.out.println(result);
}
int kiraadd(int num1M, int num2M){ // method definition
return num1M + num2M;
}}
20
General Format of Method Calls
objectName.methodName(arguments);
Example:
NamaClass mc=new NamaClass();
// create object
mc.add(num1, num2); // method call
Method call with no return value
import java.util.Scanner;
class Tambah {
public static void main(String [ ] args )
{
Scanner sc=new Scanner(System.in);
Tambah mc=new Tambah( ); // create objectName
int num1, num2, result;
�num1 = sc.nextInt();
num2 = sc.nextInt();
mc.kiraadd(num1, num2); // method call
} // close main
void kiraadd(int num1M, int num2M){
int result= num1M + num2M;
System.out.println(result);
} // close method
}// close class
21
General Format of Method Calls
objectName.methodName(arguments);
Example:
NamaClass mc=new NamaClass();
// create object
mc.add(num1, num2); // method call
Quick Check Method
22
public
int
(int num1, int num2) {
max
Method name
Method parameter
Method return type
Method Header
int result;
if (num1 >num2)
result = num1;
else
result = num2;
return result; }
Method body
Return value
larger = mc.max(num1, num2);
Method call
Difference between Static Methods and Instance Methods
23
Instance (non-static) Method | Static Method |
Instance method is not with static keyword. | Static method is declared with static keyword. |
In a program, it has to be called by using object of the class | In a program, it can be called directly by using method name |
Belong to the class | Belong to the object of the class |
Instance methods exist as multiple copies depending on the number of instances created for that class. | Static method means which will exist as a single copy for a class. |