5.1 Introduction to Methods

A method in Java is a block of statements that has a name and can be executed by calling it from some other place in your program. Methods are used to divide complicated programs into manageable pieces. Using methods has several advantages:

  • Different people can work on different methods simultaneously.
  • If a method is needed in more than one place in a program, or in different programs, you can write it once and use it many times.
  • Using methods greatly enhances the program’s readability because it reduces the complexity of the method main.

There are both predefined methods, methods that are already written and provided by Java, and user-defined methods, methods that you create. In section 2.2 we have discussed how to use predefined methods. Because Java does not provide every method that you will ever need, you must learn to write your own methods. User-defined methods in Java are classified into two categories:

  • Void methods - methods that do not have a return data type. These methods do not use a return statement to return a value.
  • Value-returning methods - methods that have a return data type. These methods return a value of a specific data type using the return statement.