Skip to main content
  • Statement = a line of code that performs a basic operation
  • Method = a named sequence of statements
  • Usage:
    • to do non-simple operations repeatedly
    • to break complex problems into smaller, simpler parts

Types of Methods

VOID MethodVALUE Method
Does not return a valueReturns a value
Often referred to as a procedureOften referred to as a function

Void Method

public static void sayHello() {
    System.out.println("Hello");
}

public static void sayHello(String name) {
    System.out.println("Hello " + name);
}

public static void main(String[] args) {
    sayHello();
    sayHello("Ani");
}
  • Method Names Method Names
  • Parameters and Arguments Parameters and Arguments
  • Statements Statements
  • Overloading Overloading

Exercise Void Method

Write one or several methods to do the following
  1. Prints a String n times
  2. Display the message “Good Morning” in various languages
  3. Display an alphanumeric character as an ASCII art

Value Method

public static double computeBMI(double weight, double height) {
    double bmi = weight / height / height;
    return bmi;
}

public static void main(String[] args) {
    double weight = 40;
    double height = 1.65;
    double bmi = computeBMI(weight, height);

    System.out.println("Ani's BMI is: " + bmi);
}
  • Return type and value Return type and value
  • 2

Exercise Value Method

Write one or several methods to do the following
  1. Calculates the distance between two coordinates
  2. Determines whether a number is prime or not
  3. Determines the number of days in a year

Method Composition

public static double computeTax(double price) {
    double tax = 0;
    if (price > 100) {
        tax = 0.2 * price;
    }
    return tax;
}

public static double computePayment(double price) {
    return price + computeTax(price);
}

public static void main(String[] args) {
    double itemPrice = 600;
    double payment = computePayment(itemPrice);
}

Recursive Methods

https://keenformatics.blogspot.com/2013/08/how-to-solve-json-infinite-recursion.html

  • A method that invokes itself
  • example:
    0! = 1
    n! = n ∙ (n – 1)!

    factorial(5) = 5 _ factorial(4)
    factorial(4) = 4 _ factorial(3)
    factorial(3) = 3 _ factorial(2)
    factorial(2) = 2 _ factorial(1)
    factorial(1) = 1 * factorial(0)
    factorial(0) = 1

  • Write the base case:
if (n == 0) {
    return 1;
}
  • Write the reduction step. Ensure that the base case can be reached:
return n * factorial(n - 1);

Recursion vs Iteration

  • Recursion is not always needed
  • Everything that can be done with recursion can be done using iterations (loops)
  • Recursion
    • consumes more memory and slower than iterations
    • elegant, shorter code

Documentation

True