TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
CHAPTER 4.5.1 : Introduction to Java method
At the end of this lessons, students should be able to:
a) Explain the meaning and advantages of method
b) Explain types of method: predefined and user-defined.
a) Explain the meaning and advantages of the method.
1. Explain the meaning of the method.
A Java method is a collection of statements that are grouped together to perform an operation.
2. What are the benefits of using the method?
a. time saver,
b. To reuse code : define the code once, and use it many [Link]
c. make code more readable and
d. easier to debug / find errors.
3. The diagram below shows a Java program.
Based on the diagram above, state which diagram uses the Java method. Justify your answer.
Diagram B because it has kiraadd( ) method
1
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
b) Explain types of method: predefined and user-defined.
1. State two types of methods.
predefined method and user-defined method.
2. State two types of user-defined method.
User-defined Methods with return value with or without parameter
User-defined Methods without return value with or without parameter
3. Explain one (1) difference between standard library (package) and user-defined
methods in Java programming.
Predefined Methods User-defined Methods
Built-in methods in Java that are A method that is defined by the
readily available for use. programmer.
CHAPTER 4.5.2 : Predefined method
At the end of this lessons, students should be able to:
a) Identify the use of a common predefined method: pow(x,y), sqrt(x).
1. Identify the use of predefined methods in the table below.
Predefined method Function
a) [Link] ( “ I love Method “); Display the message between “ ” and
value of the variable.
b) charAt(0) ; Returns the character at the specified
index from this string.
c) [Link]( 30, 90); This method returns the max of the
arguments 30 and 90 passed to it.
d) [Link] ( 81 ); This method returns the square root of
the arguments 81 passed to it.
2
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
2. The diagram below shows a Java program.
Based on the diagram above,
i) Which statement defines the main method?
public static void main(String[] args){ }
ii) State class name involved to execute method in class Example2?
PrintStream class, Scanner class
iii) List one example of a method for each of the classes in (ii)
PrintStream class - [Link]
Scanner class - next(), charAt(0), next(), nextInt(), nextDouble(), nextBoolean()
iv) What type of method is used in P?
Predefined method
3
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
CHAPTER 4.5.3 : Static user-defined method
At the end of this lessons, students should be able to:
a) Explain two (2) types of static user-defined methods.
b) Explain the general structure of static user-defined method: method header, method body
c) Write a method definition with a return value, with or without formal parameters.
d) Write a method definition without a return value, with or without formal parameters.
e) Write a method call with a return value, with or without actual parameters.
f) Write a method call with no return value, with or without actual parameters.
g) Write a static user-defined method to perform simple computations.
a) Explain two (2) types of static user-defined methods.
1. From the coding below explain the role for each method.
Coding Role
a) public static boolean isNotDivisible (int p, int q) { Method isNotDivisible
if(p%q!=0) will return status boolean
return true; true when p can be
else divisible by q to main
return false; method, otherwise return
} false value.
b) public static double calcSquareArea(int a , int b) { Calculate area of square
return a * b ;
}
c) public static void countDiscount (double sale) { Method calculate
double discount; discount of 10% sale and
discount = 10.0 * sale ; display the discount.
[Link](“ discount of the sale is:” + discount);
}
d) public static void cetakMesej ( ) { Print the message
[Link](“ You are marvelous! ”);
}
e) public static void findOutcome(int no1, int no2 ) { Find the largest of two
int outcome ; numbers
if (no1 < no2)
outcome = no2 ;
else
outcome = no1;
[Link](“ The largest is ” + outcome );
}
4
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
2. From the coding in the table below, state type of method
Coding Method type
a) public static boolean isNotDivisible (int p, int q) { User-defined static
if ( p % q != 0) Methods with return
return true; value with parameter
else
return false;
}
b) public static double calcVolume (double l, double w, double User-defined static
h) { Methods with return
return l* w* h ; value with parameter
}
c) public static void countDiscount (double sale) { User-defined static
double discount; Methods without return
discount = 10.0 * sale ; value with parameter
[Link](“ discount of the sale is:” + discount);
}
d) public static void cetakMesej ( ) { User-defined static
[Link](“ You are marvelous! ”); Methods without return
} value without parameter
b) Explain the general structure of static user-defined method: method header, method body
1. Explain each part of the structure in each static method header below.
Method header Structure
a) public static void isEvenOdd (int x ) {
if ( x % 2 != 0) Method Structure Identify part of
[Link] (“Odd number”) ; structure
else
[Link] (“Even number”) ; modifier public
} Method type Static void (no return
value)
Method name isEvenOdd
Parameter list for int x
5
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
user-defined method
Return type void , no return value
Formal parameter x
b) public static void main(String[ ] args){
int num1 = 3, num2 = 5; Method Identify part of
int z = getMax (num1, num2); Structure structure
[Link](“Max is “+z);
} modifier public
public static int getMax(int a, int b){
if (a > b) Method type Static int ( return a
value)
return a;
else Method name getMax
return b;
} Parameter list for int a, int b
user-defined method
Return type integer
2. a) What type are the methods getSum and getProduct?
public static int getSum(int i, int j){
return i + j;
}
public static int getProduct(int x, int y){
return x * y;
}
getSum and getProduct method is User-defined static Methods with return value with
parameter
b) State all structure in the method getSum and GetProduct.
Method Structure Identify part of structure
modifier public
Method type Static int ( return value)
Method name getSum, getProduct
Parameter list for user-defined method int i, int j int x, int y
6
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
Return type integer
3. State all the sections in the header of the method.
modifier
Method type
Method name
Parameter list for user-defined method
Return type
4. What are arguments?
Arguments are the value(s) we pass to a method.
5. Define parameters.
A parameter is a placeholder in the called method to hold value of the passed arguments.
6. Explain return type.
Return type is based on the type of value returned by the method
Return type : void
● If the method does not return a value, its return type is void.
● Do not put a return statement at the end of a non-value returning function.
Return type : value to be return:
● It can return value of primitive data types (int, double, boolean, and char).
7. Explain Method type.
Method types 1 . Predefined methods (Standard Library Methods /default method ) are built-in methods
in Java that are readily available for use.
Method type 2 : User-defined Methods is a method written by the user to write any program code and
execute specific actions.
8. What is the return type of a main method?
void (no return value method)
c) Write a method definition with a return value, with or without formal parameters.
d) Write a method definition without a return value, with or without formal parameters.
1. Write method headers (not the bodies) for the following methods:
a) Return a sales commission, given the sales amount and the commission rate.
public static double saleCommision (double sale , double rate ){ }
b) Display the calendar for a month, given the month and year.
7
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
static void displayCalendar (int month , int year ){ }
c) Return a square root of a number.
static void findSquareRoot (double number ){ }
d) Test whether a number is even, and returning true if it is.
static boolean IdentifyEven (int number ){ }
e) Display a message a specified number of times.
static void displayMessage (int notimes ) { }
f) Return the monthly payment, given the loan amount, number of years, and annual interest rate.
public static double monthPayment (double loanAmount , int year , double rateAnnual ) { }
2. Fill in the blank for below questions.
public static void volumeSphere ( double radius ) {
double volume = 4.0 / 3.0 * 3.142 * [Link] (radius,3);
[Link] (“volume circle is :” + volume );
}
public static void displayPattern ( ){
[Link] (“*\t*\t*\t*” );
}
public static void showTimetables( int number ) {
int product ;
for (int i = 1 ; i < = 12 ; i=i+1) {
product = i*number;
[Link]( i + “ x ” + number + “ = ” + product );
}
}
public static double findMax ( double num1, double num2) {
double maximum ;
maximum = [Link] (num1,num2);
return maximum;
}
public static double findMin ( ){
double minimum ;
minimum = [Link] (43 ,70);
return minimum;
}
public static void findStatus ( char letter ) {
if ( letter >= ‘a’ && letter <= ‘z’)
[Link] (“ letter is small letter”);
else if ( letter >= ‘A’ && letter <= ‘Z’)
8
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
[Link] (“ letter is capital letter”);
}
public static boolean findStatus2 ( char letter ) {
if ( letter == ‘y’ || letter == ‘Y’)
return true;
else
return false;
}
public static double smallest(double x, double y, double z )
{
return [Link]([Link](x, y), z);
}
3. Write the first line of a static method named myMethod that takes three parameters: an
int and two Strings.
public static void myMethod(int i, String s1, String s2) {
}
4. Write a static method named printAmerican that takes the day, date, month and year as
parameters and that displays them in American format.
Saturday, July 22, 2015
class printAmerican {
public static void printAmerican (String day, int date, String month, int year) {
[Link](day+", "+month+" "+date+","+year);
}
}
5. Write a static method named square that takes an integer and returns an approximation of the
square of the parameter.
public static double square(int a) {
return [Link](a,2);
}
6. Write a static method named isNotDivisible that takes two integers, p and q, and that returns
true if p is not divisible by q, and false otherwise.
9
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
public static boolean isNotDivisible(int p, int q) {
if ( p % q != 0)
return true;
else
return false;
}
7. Write a static method named oddSum that takes a positive odd integer n and returns the
sum of odd integers from 1 to n.
public static int OddSum (int from, int to) {
if (from>to){
[Link]("from should be < to!");
[Link](-1);
}
int sum =0;
for (int i = from; i <= to ; i++) {
if (i%2 != 0)
sum = sum+i;
}
return sum;
}
e) Write a method call with a return value, with or without actual parameters.
f) Write a method call with no return value, with or without actual parameters.
1. Write a method call for each method definition below questions.
Method definition Method call
public static void calcArea (int w, int length ) calcArea ( width , length);
{
double area = w *length ;
[Link] (“area is :” + area );
}
public static void displayPattern ( ){ displayPattern ( );
[Link] (“*\t*\t*\t*” );
}
10
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
public static void showTimetables( int y ) { showTimetables( no );
int product ;
for (int i = 1 ; i < = 12 ; i=i+1) {
product = i* y;
[Link]( i + “ x ” + y + “ = ” + product );
}
}
public static double findMax (double n1, double n2 ) { high=findMax ( n1, n2 );
double maximum ;
maximum = [Link] (n1,n2);
return maximum;
}
public static double findMin ( ){ [Link]( findMin (
double minimum ; ));
minimum = [Link] (43 ,70);
return minimum;
lowest=findMin ( );
}
public static void findStatus ( int mark ) { findStatus ( mark ) ;
if ( mark >=80)
[Link] (“ You are excellent”);
else if (mark >= 65)
[Link] (“ Nice job”);
}
public static boolean yourAnswer ( char letter ) { boolean status =
if ( letter == ‘y’ || letter == ‘Y’) yourAnswer ( letter );
return true;
else
return false;
}
public static double smallest(double x, double y, double z) low=smallest( x, y, z);
{
return [Link]([Link](x, y), z);
}
2. What are arguments involved in this method call :
a. computeInterest ( sale ) ;
sale
b. countAge ( name, yearNow, yearBirth );
name, yearNow, yearBirth
c. displayMessage ( ) ;
No argument
11
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
d. displayStatus (age, married);
age, married
3. How is an argument passed to a method? Can the argument have the same name as its
parameter?
Arguments passed to a method using call method in paranthesis. Arguments can have the
same name as its parameter because both are declared in main method and in its method
header.
4. Identify and correct the errors in the following program:
The arguments must match the parameters in order, number, and compatible type, as defined in the
method signature.
1 public class Test {
2 public static void main(String[] args) {
3 nPrintln(5, "Welcome to Java!");
4 }
5
6 public static void nPrintln(String message, int n) {
7 int n = 1;
8 for (int i = 0; i < n; i++)
9 [Link](message);
10 }
11 }
5. What is the name of the method for each method call?
a. computeInterest ( sale ) ;
computeInterest
b. countAge ( name, yearNow, yearBirth );
countAge
c. displayMessage ( ) ;
displayMessage
d. displayStatus (age, married);
displayStatus
g) Write a static user-defined method to perform simple computations.
Write a complete Java static method for below questions.
1. To find the smallest number among three numbers.
Input the first number: 25
Input the Second number: 37
Input the third number: 29
Expected Output:
The smallest value is 25.0
12
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
import [Link];
public class Exercise1 {
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the Second number: ");
double y = [Link]();
[Link]("Input the third number: ");
double z = [Link]();
[Link]("The smallest value is " + smallest(x, y,
z)+"\n" );
}
public static double smallest(double x, double y, double z)
{
return [Link]([Link](x, y), z);
}
}
import [Link];
class Exercise1 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the Second number: ");
double y = [Link]();
[Link]("Input the third number: ");
double z = [Link]();
[Link]("The smallest value is "+
smallest(x, y, z));
}
public static double smallest(double a, double b, double
13
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
c)
{
if (a<b && b<c)
return a;
else if (b<a && b<c)
return b;
else
return c;
}
}
2. Compute the average of three numbers.
import [Link];
public class Exercise2 {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the second number: ");
double y = [Link]();
[Link]("Input the third number: ");
double z = [Link]();
[Link](“The average value is “+ average(x,y,z));
}
public static double average(double a, double b,double c)
{
return (a + b + c) / 3.0;
}
}
14
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
3. Compute the sum of the digits in an integer less than 100.
Input Sample / Test Data Output Sample / Expected Output
Input an integer: 25 The sum is 7
import [Link];
public class Exercise3 {
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Input an integer less than 100: ");
int digits = [Link]();
[Link]("The sum digits "+ sumDigits(digits));
}
public static int sumDigits(int n) {
int result = 0;
while(n > 0)
{
result =result + n % 10;
n = n/10;
}
return result;
}
}
4. Check whether a year (integer) entered by the user is a leap year or not.
15
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
import [Link];
public class Exercise4 {
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Input a year: ");
int year = [Link]();
[Link](is_LeapYear(year));
}
public static boolean is_LeapYear(int y){
boolean a = (y % 4) == 0;
boolean b = (y % 100) != 0;
boolean c = ((y % 100 == 0) && (y % 400 == 0));
return a && (b || c);
}
}
5. Write a Java static method to:
a) Find the largest number among three numbers.
b) Compute the average of three numbers.
import [Link];
public class Exercise5 {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the second number: ");
double y = [Link]();
[Link]("Input the third number: ");
double z = [Link]();
[Link](“ largest number among three numbers is “+
16
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
largest(x,y,z));
[Link](“The average value is “+ average(x,y,z));
public static double largest(double a, double b,double c)
{ if( a> b && a> c)
return a;
if( b > a && b> c)
return b;
else
return c;
public static double average(double a, double b,double c)
{
return (a + b + c) / 3;
}
}
import [Link];
class PrintHighestMethod{
static float highest = 0; // global static variable
public static void main(String[] args){
Scanner obj = new Scanner([Link]);
float marks, max;
for(int i=1; i < 4; i++){
[Link] ("Enter mark : ");
marks =[Link]();
max = findMax (marks);
} // close for
[Link]("Highest: "+ highest);
}
public static float findMax ( float mark )
{ if(mark > highest)
highest = mark;
17
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
return highest;
}
6. Write a complete java program that consists of three (3) static methods to compute the sum of
the two numbers, product of two numbers and division of two numbers.
import [Link];
public class Exercise6 {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the second number: ");
double y = [Link]();
[Link]("sum of the two number is : "+ sum(x,y));
[Link]("The product of the two number is : "+
product(x,y));
[Link]("The division between two number is : "+
division(x,y));
public static double sum(double a, double b)
{ double total = a + b;
return total;
}
public static double product(double a, double b)
{ double product= a * b;
return product;
}
public static double division(double a, double b)
{ double divi= a / b;
return divi;
}
18
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
7. Create a new program called [Link]. Write a method called multadd that takes three
doubles as parameters like 1.0, 2.0, 3.0 and returns a * b + c. Write a main method to display
output.
class MultAdd {
public static void main(String[] args) {
[Link] ("The multadditionization of 1.0, 2.0, and 3.0 is:
"+ multadd(1.0, 2.0, 3.0));
}
public static double multadd(double a, double b, double c) {
return a * b + c;
}
8. Write a recursive method named oddSum that takes a positive odd integer n and returns the
sum of odd integers from 1 to n.
import [Link];
class Odd {
public static void main(String[]args){
Scanner sc=new Scanner([Link]);
[Link]("Enter n : ");
int n= [Link]();
[Link]("Sum of odd number from 1 to n is " +
oddSum(n));
}
19
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
public static int oddSum (int x) {
int sum=0;
for(int counter = 1; counter<= x; counter = counter + 2)
{
sum = sum + counter;
}
return sum;
}
}
9. Write a complete Java program that consist a static method to solve the following problem:
a. The factorial of an integer number n is the product of all numbers from 1 up to n.
i. Read an integer number n, calculate and display its factorial value.
import [Link];
class Factorial {
public static void main(String[]args){
Scanner sc=new Scanner([Link]);
[Link]("Enter n : ");
int n= [Link]();
factor ( n );
}
public static void factor (int n) {
factorial = 1;
for (i=1; i<=n; i=i+1){
factorial = factorial * i;
20
TUTORIAL
SC025 2022/2023 - 4.0 : Java Language
}
[Link]("factorial value from 1 to ” + n “is : "
+ factorial);
}
} // close class
21