1 of 23

3.5 Java Method

2 of 23

Learning Outcome

(a) Introduction to Java Method

  • Explain the meaning and the use of functions(method)
  • Explain types of method
    • Standard library
    • User-defined
  • Explain the general structure of a user-defined method
    • Method name
    • Type
    • Parameters
  • Explain method return types based on return values

2

3 of 23

3.5.1 Introduction to Java Method

Method - Example of Diagram

How is method is invoked or called in a program?

3

  • A Java method is a collection of statements that are grouped together to perform an operation.
  • Methods are bound to a class and they define the behavior of a class.

4 of 23

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

5 of 23

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

6 of 23

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

7 of 23

Types of Java Methods

There are two (2) types of method:

  • Standard Library Methods (default method)
    • pow(a, b), sqrt(a), max(a, b), min(a, b)
  • User-defined Methods

7

8 of 23

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,

  • print() is a method defined in java.io.PrintStream. The print("...") prints the String inside quotation marks.
  • sqrt() and pow(x,y) is a method defined in Math class.
  • next(),nextInt(),nextDouble(),nextBoolean() is in a Scanner class.

8

9 of 23

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)

10 of 23

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:

  • return type
  • method name
  • Parameters
  • Body of method

10

11 of 23

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

  • Explain types and use of statements:
    • Method definition
    • Method calls
  • Explain the general format of method definition and method call.
  • Construct non-static user-defined methods.
  • Construct programs that use standard and/or user-defined methods based on given problem.

11

12 of 23

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:

  • Return type
  • Method name
  • Parameters
  • Body of method

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;

}

13 of 23

Examples of method definition

This method:

  • Method named displayMessage
  • did not return any values, void and
  • did not accept any parameters, ().

13

void displayMessage()

{

System.out.print(“Hello, World!”);

}

14 of 23

Method Return Types

return type is based on the type of value returned by the method

  • It can return value of primitive data types (int, double, boolean, and char).
  • If the method does not return a value, its return type is void.

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 ;

}

15 of 23

Method Return Types

return type is based on the type of value returned by the method

  • It can return value of primitive data types (int, double, boolean, and char).
  • If the method does not return a value, its return type is void.

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) ;

}

16 of 23

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

17 of 23

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 ”); }

18 of 23

Method Calls

A method must be called based on exactly how the method was defined.

  • Method name
  • Method type
  • Number of parameters
  • Sequence of data type for each parameter.

18

General Format of Method Calls

objectName.methodName(arguments);

  • objectName is the instance of the class (object for the class name),
  • methodName is the method defined in the same class, and
  • arguments is the value(s) we pass to a method.

Example:

NamaClass mc=new NamaClass(); // create object

mc.add(num1, num2); // method call

19 of 23

Method Calls

There are two ways to call a method, which depends on whether:

  • it returns a value, or
  • it returns nothing (no return value).then the method should be declared as void.

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());

20 of 23

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);

  • objectName is the instance of the class (object for the class name),
  • methodName is the method defined in the same class, and
  • arguments is the value(s) we pass to a method.

Example:

NamaClass mc=new NamaClass();

// create object

mc.add(num1, num2); // method call

21 of 23

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);

  • objectName is the instance of the class (object for the class name),
  • methodName is the method defined in the same class, and
  • arguments is the value(s) we pass to a method.

Example:

NamaClass mc=new NamaClass();

// create object

mc.add(num1, num2); // method call

22 of 23

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

23 of 23

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.