Section 04 Methods
Section 04 Methods
© luv2code LLC
Methods
• A method is a block of code that is executed when you call i
fi
d
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
// code to execut
}
code to execute
We will cover
public, private, protected
in detail later in the course
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
code to execute
displayGreetings()
Hello world
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
© luv2code LLC
Method Parameters
• We can pass parameters to a metho
• computeGradeAverage( …
• displayManyGreetings( …
• searchForCustomersWithLastName(“Davis”)
• Reuse the same method in different contexts based on the input / method parameters
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
System.out.println() ;
Welcome, welcome
Hello world
Hello world
displayManyGreetings(3)
System.out.println("Welcome, welcome.")
Hello world
System.out.println()
Welcome, welcome
;
System.out.println("Welcome, welcome.")
Welcome, welcome
;
displayManyGreetings(3)
System.out.println("Hello world!")
Same code from method:
System.out.println("Welcome, welcome.")
System.out.println()
;
System.out.println("Hello world!")
;
System.out.println("Welcome, welcome.")
;
displayManyGreetings(3)
System.out.println("Hello world!")
;
System.out.println("Welcome, welcome.")
;
displayGreetings(3)
displayGreetings();
Differ in the parameter types and number of parameters
static void displayGreetings() If there is an issue, you will have a compilation error
{
System.out.println("Hello world!")
;
System.out.println("Welcome, welcome.")
;
© luv2code LLC
Method Return Value
• A method can perform an operation based on the input and return a valu
• double computeGradeAverage( …
• int getInventoryCountForProduct( …
• Customer searchForCustomerWithId( … )
• …
• For example
:
• summation(3) = 1+2+3 =
• summation(5) = 1+2+3+4+5 = 15
int result = 0
;
result += i
result = result + i;
;
return result
Return the result from the method
;
int val = 5
;
int val = 5
;
int result = 0
;
result += i Summation of 5 is 15
;
return result
;
int val = 5;
return result
;
} Summation of 5 is 15
© luv2code LLC
Recursion
• Recursion is an approach where a method calls itself to solve a proble
fi
…
fi
• Recursive Case
:
• For example
:
• factorial(3) = 3*2*1 =
• factorial(5) = 5*4*3*2*1 = 12
• Iterativ
e
• Recursive
= 5 * 4 * 3 * 2 * 1 * factorial(0
= 5 * 4 * 3 * 2 * 1 *
= 120
// base case: 0! = 1
if (num == 0)
{
return 1
;
else
{
int val = 5
Factorial of 5 is 120
;
int val = 5
;
// base case: 0! = 1
if (num == 0)
{
return 1
;
else
{