Creating your own methods

Intermediate Java

Jim White

Java Developer

Why we use methods

  • Great for repeated tasks
  • Reusing of code
  • Avoid repetition (and potential mistakes)
  • Easier to update and fix mistakes
  • Don't Repeat Yourself (DRY)
Intermediate Java

How to define methods

returnType methodName(){

  // Code to be run

}
Intermediate Java

void method

  • Only performs an action, doesn't return anything
  • void means nothing
void sayHello(){
    System.out.println("Hello there!");
  }
Intermediate Java

Method that produces result

  • Methods can produce a result
    • To store, to use later, to pass to another part of our program, ...
    • E.g., method that calculates square of a number
  • Need to:
    • Use specific return type like int or String
    • Include return statement
int getSquare() {
  return 5 * 5
}
Intermediate Java

Naming convention

Lower camel case

  • First letter lowercase, additional words start with capital letter
  • Examples:
    • getSquare()
    • sayHello()
Intermediate Java

Case sensitivity

Java is case sensitive!

If method is called getSquare(), getsquare() won't work!

Intermediate Java

Built-in vs. Custom methods

Built-in

  • Called using the dot notation
    • "JAVA".toLowerCase();

Custom methods

  • Called as-is
    • sayHello();
Intermediate Java

Using a custom method

Code showing the sayHello method defined outside of the main method, with the static keyword emphasized

"Hello there!"
Intermediate Java

Recap

class HelloMethod {
    public static void main (String[] args) {
        sayHello();
        int fiveSquared = getSquare(); // Saving the result of getSquare() as int
    }
    static void sayHello() { // Just prints a message
      System.out.println("Hello there!");
    }
    static int getSquare() { // Returns int 
      return 5*5; 
    }
}
Hello there!
Intermediate Java

Let's practice!

Intermediate Java

Preparing Video For Download...