Professional Documents
Culture Documents
Objectives
Understanding Methods.
Introduction
What is a Method?
A method is a collection of statements that performs a specific task.
Tasks:
Display Message (System.out.println())
Convert Data Types (Integer.parseInt)
Math.pow
Main method (To start any Java Project/Program)
Methods are commonly used to break a problem into small manageable
pieces.
One long method that contains all of the statements.
Several small methods that each solve a specific part of the problem
can be written (called divide and conquer). Divides a problem into
smaller problems, each of which are handled by separate method.
Figure:
void methods is one that simple performs a task and then terminates.
Ex: System.out.println() is void method.
Example
A value returning method not only perform a task, but also sends a value
back to the code that called it.
Ex: Integer.parseInt() method.
Example:
To create a method you must write its definition, which consists of two
general parts;
a header
a body
The method header, which appears at the beginning of a method definition,
list several important things about the method, including the method’s
name.
The method body is a collection of statements that are performed when the
method is executed. These statements are enclosed inside a set of curly
braces.
As you already know, every complete Java programs must have a main
method. Java program can have other methods as well.
Parts of the Method Header
Method Modifiers - for this lesson, every method that we write will begin
with public static)