Java Tutorial/Methods

From Wikiversity
Jump to navigation Jump to search

So far, we've been putting all our code into one method or function, main. However, we can also have more than one method! To make a new method, just write something like:

public class MultiMethod {
    public static void main (String[] args) {
        //main method
    }

    public static void anotherMethod() {
        //anotherMethod method
    }
}

Note that there is nothing in the parentheses. Anything within it is called a parameter. But first, lets learn how to use our new method...

//class declaration
public static void main(String[] args) {
    anotherMethod();
}

public static void anotherMethod() {
    System.out.println("Printing from anotherMethod");
}

The main method calls anotherMethod(), by writing its name. Now, say you wanted the main method to tell anotherMethod what to write. Then...

//...
public static void main(String[] args) {
    anotherMethod("Print this");
}

public static void anotherMethod(String what_to_print) {
    System.out.println(what_to_print);
}

As you can see, anotherMethod takes in a String (what_to_print) as a parameter, and then accesses its value. However, this is not all that methods can do. As you can see, we are using something called void. This means, essentially, nothing. What if we wanted anotherMethod() to tell the main method what to print? Well, look at this:

//...
public static void main(String[] args) {
    System.out.println(anotherMethod());
}

public static String anotherMethod() {
   return "print this";
}

anotherMethod returns a string for main to print. Because it does this, anotherMethod() is just like a variable, except that it's code is being executed instead of its value being accessed. You can change what it returns, but it has to be a String, as that's what we specified it would return.

Excercises[edit | edit source]

  • Change what anotherMethod returns to an integer
  • Try removing main's parameter, and see what errors you get

Answer:

public class MultiMethod {
    public static void main(String[] args) {
        System.out.println(anotherMethod()); 
        //System.out.println can also print integers, floats, and more
    }

    public static int anotherMethod() {
        return 5;
    }
}
Previous: Control Structures II - Looping Up: Java Tutorial Next: Arrays