Methods
© luv2code LLC
Methods
• A method is a block of code that is executed when you call i
• You can add your own custom code to a metho
• Methods are useful for code reuse, readability and maintenance
www.luv2code.com © luv2code LLC
Development Process
• Step 1: De ne the metho
fi
d
• Step 2: Call the method
www.luv2code.com © luv2code LLC
Basic Example
Reusable block of code
Step 1: Define the method
static void displayGreetings()
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
System.out.println("Please make yourself at home.")
Step 2: Call the method
public static void main(String[] args)
Hello world
displayGreetings() Welcome, welcome
Please make yourself at home.
;
www.luv2code.com © luv2code LLC
General Syntax
primitive data types
public, private, protected static for or class Any collection of
Any method name
or nothing class methods (predefined or custom) parameters
[access modifier] [static] [return type] [method name]([params])
// code to execut
}
code to execute
We will cover
public, private, protected
in detail later in the course
www.luv2code.com © luv2code LLC
Applying Syntax to our example
primitive data types or
class
public, private, protected (predefined or custom) Any collection of
static for Any method name
or nothing parameters
class methods
void: returns nothing
static void displayGreetings()
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
System.out.println("Please make yourself at home.")
code to execute
www.luv2code.com © luv2code LLC
Pulling it all together
public class MethodDemo
public static void main(String[] args)
// call the metho
displayGreetings()
Hello world
// define the metho Welcome, welcome
d
static void displayGreetings() Please make yourself at home.
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
System.out.println("Please make yourself at home.")
www.luv2code.com © luv2code LLC
Method Parameters and Method Overloading
© luv2code LLC
Method Parameters
• We can pass parameters to a metho
• The method can perform a task based on the inpu
• computeGradeAverage( …
• displayManyGreetings( …
• searchForCustomersWithLastName(“Davis”)
• This promotes code reus
e
• Reuse the same method in different contexts based on the input / method parameters
www.luv2code.com © luv2code LLC
Passing parameter to methods
<type> <param name>
Step 1: Define the method
static void displayManyGreetings(int count)
Display our greeting 3 times
for (int i=1; i <= count; i++)
System.out.println("Hello world!")
System.out.println("Welcome, welcome.")
System.out.println("Please make yourself at home.")
Hello world
System.out.println() ;
Welcome, welcome
Please make yourself at home
}
Hello world
Step 2: Call the method
Welcome, welcome
Please make yourself at home
public static void main(String[] args)
Hello world
displayManyGreetings(3) Welcome, welcome
Please make yourself at home.
}
www.luv2code.com © luv2code LLC
Pulling it all together
public class MethodDemo
public static void main(String[] args)
// call the metho Display our greeting 3 times
displayManyGreetings(3)
static void displayManyGreetings(int count)
Hello world
for (int i=1; i <= count; i++) Welcome, welcome
System.out.println("Hello world!") Please make yourself at home
System.out.println("Welcome, welcome.")
System.out.println("Please make yourself at home.")
Hello world
System.out.println()
Welcome, welcome
;
Please make yourself at home
}
static void displayGreetings()
{
System.out.println("Hello world!") Hello world
;
System.out.println("Welcome, welcome.")
Welcome, welcome
;
System.out.println("Please make yourself at home.")
Please make yourself at home.
}
www.luv2code.com © luv2code LLC
Did you notice anything???
public class MethodDemo
public static void main(String[] args)
// call the metho
displayManyGreetings(3)
static void displayManyGreetings(int count)
for (int i=1; i <= count; i++)
System.out.println("Hello world!")
Same code from method:
System.out.println("Welcome, welcome.")
System.out.println("Please make yourself at home.")
displayGreetings()
System.out.println()
;
static void displayGreetings()
{
System.out.println("Hello world!")
;
System.out.println("Welcome, welcome.")
;
System.out.println("Please make yourself at home.")
www.luv2code.com © luv2code LLC
Refactor: Call existing method
public class MethodDemo
public static void main(String[] args)
// call the metho
displayManyGreetings(3)
static void displayManyGreetings(int count)
for (int i=1; i <= count; i++)
displayGreetings(); Call existing method:
System.out.println()
displayGreetings()
;
static void displayGreetings()
{
System.out.println("Hello world!")
;
System.out.println("Welcome, welcome.")
;
System.out.println("Please make yourself at home.")
www.luv2code.com © luv2code LLC
Method Overloading
• We can have multiple methods with the same nam
• This is known as method overloading
• Simply provide different parameters
• Different parameter types and number of parameters
• In our example, we can overload the method name: displayGreetings
www.luv2code.com © luv2code LLC
Overloaded method example: displayGreetings
public class MethodDemo Call the displayGreetings method
public static void main(String[] args) that has
one parameter of type int
// call the metho
displayGreetings(3)
static void displayGreetings(int count)
Both methods have the same name: displayGreetings
for (int i=1; i <= count; i++)
displayGreetings();
Differ in the parameter types and number of parameters
System.out.println() Java will match on the appropriate method
;
and call accordingly
}
static void displayGreetings() If there is an issue, you will have a compilation error
{
System.out.println("Hello world!")
;
System.out.println("Welcome, welcome.")
;
System.out.println("Please make yourself at home.")
www.luv2code.com © luv2code LLC
Methods: Return Value
© 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( … )
• Return type can be a
• primitive: int, double,
…
• class: prede ned or custom,
fi
…
• …
www.luv2code.com © luv2code LLC
Example: Summation
• Create a method to calculate a summation of a numbe
• A summation adds all numbers from 1 to a given numbe
• For example
:
• summation(3) = 1+2+3 =
• summation(5) = 1+2+3+4+5 = 15
www.luv2code.com © luv2code LLC
Example: Summation
Step 1: Define the method
A summation adds all numbers from
static int summation(int num) 1 to a given number
int result = 0
;
for (int i=1; i <= num; i++)
result += i
result = result + i;
;
return result
Return the result from the method
;
Step 2: Call the method
public static void main(String[] args)
{
int val = 5
;
int output = summation(val)
Summation of 5 is 15
;
System.out.println("Summation of " + val + " is " + output)
www.luv2code.com © luv2code LLC
Pulling it all together
public class MethodReturnDataDemo
public static void main(String[] args)
int val = 5
;
int output = summation(val)
System.out.println("Summation of " + val + " is " + output)
static int summation(int num)
int result = 0
;
for (int i=1; i <= num; i++) {
result += i Summation of 5 is 15
;
return result
;
www.luv2code.com © luv2code LLC
Refactor: Use a mathematical formula
public class MethodReturnDataDemo
public static void main(String[] args)
int val = 5;
int output = summation(val)
System.out.println("Summation of " + val + " is " + output)
static int summation(int num)
{
int result = num * (num + 1) / 2
return result
;
} Summation of 5 is 15
www.luv2code.com © luv2code LLC
Methods: Recursion
© luv2code LLC
Recursion
• Recursion is an approach where a method calls itself to solve a proble
• Breaks a complex problem into smaller problems
www.luv2code.com © luv2code LLC
Recursion: Use Cases
• Mathematical operations: factorial, bonacci,
fi
…
• Sorting and searching algorithms: quicksort, mergesort,
• Graphics: fractals, mandelbrot,
• Arti cial intelligence: supervised learning, natural language processing, …
fi
www.luv2code.com © luv2code LLC
Recursion: Key Components
• Base Case
• Condition that stops the recursio
• Very important, without base case, code will run in nitely
fi
• Recursive Case
:
• Break the problem into a smaller proble
• Methods calls itself using modi ed parameters for smaller problem
fi
www.luv2code.com © luv2code LLC
Example: Factorial
• Create a method to calculate a factorial of a numbe
• A factorial multiples all numbers from 1 to a given number
• For example
:
• factorial(3) = 3*2*1 =
• factorial(5) = 5*4*3*2*1 = 12
• factorial(0) = 1 Special case: 0! = 1
www.luv2code.com © luv2code LLC
Factorial Approaches
• There are two approaches for computing the factoria
• Iterativ
e
• Recursive
• We will focus on the recursive approach to demonstrate recursion
www.luv2code.com © luv2code LLC
Compute Factorial using Recursion
Recursive case
factorial(5) = 5 * factorial(4 Recursive case
= 5 * 4 * factorial(3 Recursive case
= 5 * 4 * 3 * factorial(2 Recursive case
= 5 * 4 * 3 * 2 * factorial(1 Base case
= 5 * 4 * 3 * 2 * 1 * factorial(0
= 5 * 4 * 3 * 2 * 1 *
= 120
www.luv2code.com © luv2code LLC
Example: Factorial
Step 1: Define the method
static int factorial(int num)
// base case: 0! = 1
if (num == 0)
{
return 1
;
else
{
// recursive case: num! = num * (num-1)!
return num * factorial(num - 1)
Step 2: Call the method
public static void main(String[] args)
{
int val = 5
Factorial of 5 is 120
;
int result = factorial(val)
;
System.out.println("Factorial of " + val + " is " + result)
www.luv2code.com © luv2code LLC
Pulling it all together
public class RecursionDemo
public static void main(String[] args)
int val = 5
;
int result = factorial(val)
System.out.println("Factorial of " + val + " is " + result)
static int factorial(int num)
// base case: 0! = 1
if (num == 0)
{
return 1
;
else
{
// recursive case: num! = num * (num-1)!
return num * factorial(num - 1) Factorial of 5 is 120
;
www.luv2code.com © luv2code LLC