So far we have used methods from Java libraries, but it is also possible to add new methods. We have already seen one method definition: main. The method named main is special, but the syntax is the same for other methods:
public static void NAME( LIST OF PARAMETERS ) {
STATEMENTS
}
You can make up any name you want for your method, except that you can't call it main or any Java keyword. By convention, Java methods start with a lower case letter and use “camel caps," which is a cute name for jammingWordsTogetherLikeThis.
The list of parameters specifies what information, if any, you have to provide to use (or invoke) the new method.
The parameter for main is String[] args, which means that whoever invokes main has to provide an array of Strings (we'll get to later). The first couple of methods we are going to write have no parameters, so the syntax looks like this:
public static void newLine() {
System.out.println("");
}
This method is named newLine, and the empty parentheses mean that it takes no parameters. It contains one statement, which prints an empty String, indicated by "". Printing a String with no letters in it may not seem all that useful, but println skips to the next line after it prints, so this statement skips to the next line.
In main we invoke this new method the same way we invoke Java methods:
public static void main(String[] args) {
System.out.println("First line.");
newLine();
System.out.println("Second line.");
}
The output of this program is
First line.
Second line.
Notice the extra space between the lines. What if we wanted more space between the lines? We could invoke the same method repeatedly:
public static void main(String[] args) {
System.out.println("First line.");
newLine();
newLine();
newLine();
System.out.println("Second line.");
}
Or we could write a new method, named threeLine, that prints three new lines:
public static void threeLine() {
newLine(); newLine(); newLine();
}
public static void main(String[] args) {
System.out.println("First line.");
threeLine();
System.out.println("Second line.");
}
You should notice a few things about this program:
You might wonder why it is worth the trouble to create all these new methods. There are several reasons; this example demonstrates two:
Later we will list some additional benefits of dividing programs into methods.