Methods

Programming Languages · Java Loops & Arrays · 14 min

Package code into reusable methods that take inputs and give back answers.

Your first method

A method is a named block of code you can run whenever you like by calling it. main is one; now you'll write your own, inside Main but outside main.

static lets main call it directly. void means it doesn't hand anything back.

static void cheer() {
    System.out.println("Hooray!");
}
// call it inside main:
cheer();
  • Write a method static void greet() that prints Hello!

  • Call greet() twice from main.

Parameters

A parameter is an input to a method. Write its type and name inside the brackets. When you call the method, the value you pass in fills that name.

static void shout(String word) {
    System.out.println(word + "!");
}
shout("Hi"); // Hi!
  • Change greet so it takes a String name and prints "Hello, " + name.

  • In main, call greet("Ada") and then greet("Alan").

Giving back a value: return

Instead of void, a method can name the type of answer it gives back. return hands that answer to whoever called it.

static int triple(int n) {
    return n * 3;
}
System.out.println(triple(4)); // 12
  • Write static int square(int n) that returns n * n.

  • In main, print square(7).

Other return types

A method can return any type: double, String, boolean... A boolean method answers a yes/no question, and you can return a comparison directly.

static boolean isAdult(int age) {
    return age >= 18;
}
  • Write static boolean isEven(int n) that returns n % 2 == 0.

  • Print isEven(10), then isEven(7).

Using the answer

A returned value is just a value: store it in a variable, print it, or pass it into another call. A void method gives nothing back, so there's nothing to store.

int a = triple(2);   // 6
int b = triple(a);   // 18
  • Store doubleIt(5) in an int called x.

  • Print doubleIt(x).

Put it together: a tip calculator

Build a receipt printer from two methods: one that works out the tip and one that prints the receipt. For a 50 bill with a 15% tip, it prints:

Bill: 50.0
Tip: 7.5
Total: 57.5
  • Write static double tip(double bill, double percent) that returns bill * percent / 100.

  • Write static void printReceipt(double bill) that prints the three lines, using tip(bill, 15).

  • In main, call printReceipt(50).

More in Java Loops & Arrays

Previous: Arrays · Next: Classes and Objects