Simple User-defined Methods
Learn to divide a program into methods or subprograms in Java.
Methods
We can divide a program into procedural components or modules called methods in Java. We are already familiar with the main()
method. Methods can be copied and reused in a programming technique called a modular or procedural approach, also known as the divide and conquer approach. We should always try to design methods that can be reused in other programs too.
Broadly, there are two types of methods, which we’ll explore in the following sections.
The structure of a method
The following slides illustrate various parts of a method definition:
A function name can only contain letters (
A
—Z
anda
—z
) and the underscore symbol (_
). It may also contain digits (0
–9
), but the function name can’t start with those. For example,Key_2
is a valid function name, but2_key
is not. Function names are case-sensitive, meaning thatname
,Name
, andNAME
are three different functions.
There are two main parts of a method definition:
- Header: The first line, which ends with a closing parenthesis
)
. - Body: The block of statements below the method header, starting with an opening brace
{
and ending with a closing brace
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy