knowledge-kitchen

Object-Orientation - Methods (in Java)

“Take a method and try it. If it fails, admit it frankly, and try another. But by all means, try something.”

-Franklin D. Roosevelt

  1. Overview
  2. Simple Methods
  3. Parameters & Arguments
  4. Return Values
  5. Overloading
  6. Conclusions

Overview

Concept

Methods are modular reusable blocks of code.

Simple Methods

Super simple

At their simplest, methods can have no parameters and no return value.

For example, a method named ‘doSomething1’:

public static void doSomething1() {
    System.out.println("Running  doSomething1");
    // imagine some useful stuff happens in the middle here
    System.out.println("Exiting  doSomething1");
}

Methods calling methods

Of course, methods can call other methods, as our doSomething1 already displayed - it called the System.out.println method several times.

Note the order in which the print statements are executed.

public static void doSomething1() {
    System.out.println("Begin doSomething1");
    // imagine some useful stuff happens in the middle here
    System.out.println("End doSomething1");
}

public static void doSomething2() {
    System.out.println("Begin doSommething2");
    doSomething1(); // call the method
    System.out.println("End doSomething2");
}

Call stack

The order is determined by the control flow of the program.

Parameters

Concept

Methods can accept ‘arguments’ - values sent into the method.

public static void doSomething1(int x) {
    x++; // increment x
    System.out.println("Begin doSomething1, x=" + x);
    System.out.println("End doSomething1, x=" + x);
}

Return values

Concept

Methods can return a single value in Java.

public static int doSomething1(int x) {
    x++; // increment x
    System.out.println("Begin doSomething1, x=" + x);
    System.out.println("End doSomething1, x=" + x);
    return x;
}

Overloading

Concept

Java allows multiple methods with the same name but different parameter sets. These are called overloaded methods.

public static void foo() {
    ...
}

public static void foo(String bar) {
    ...
}

public static void foo(String bar, boolean baz) {
    ...
}

Conclusions

You now have a basic understanding of methods in Java.