Writing Methods

A method (like main) is a block of code within a class that can be called within the class.  The code within the block is executed when the method is called.

We often create a method when a block of code needs to be executed repeatedly.  Rather than have multiple copies of the same block of code, we can put one copy of the code in a method and repeatedly call the method.  We also create method simply to organize our code.

The General Form of a Method

modifier return_type  method_identifier(parameter_list) {
    ...
    return_statement;
}

Example 1

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int b = sc.nextInt();
    int h = sc.nextInt();
    int area = computeArea(b,h);  // method call
    if (area > 0) {
        printArea(area);
    }
}

static int computeArea(int base, int height) {  // method definition
    if (base <= 0 | height <= 0) {
        return -1;
    } else {
        return base * height;
    }
}

static void printArea(int a) { // method definition
    System.out.printf("Area: %d\n", a);
}

Variable Scope

  • Parameters (primitive vs. reference)
  • Local Variables
  • Returning values

Example 2

public static void main(String[] args) {
    String input = getName();
    greetPerson(input);
}

static String getName() {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your name: ");
    String name = sc.next();
    return name;
}

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

© 2017 – 2020, Eric. All rights reserved.