4 Methods
4 Methods
lt4
Java Methods
• A method is a block of code which only runs when it is called.
• Methods are used to perform certain actions, and they are also
known as functions.
Java Methods…
• Why use methods?
• To reuse code:
• define the code once, and use it many times.
Create a Method
• A method must be declared within a class.
• It is defined with the name of the method, followed by parentheses
(). Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own methods to
perform certain actions:
Call a method
• To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
• int myMethod(int x)
• float myMethod(float x)
• double myMethod(double x, double y)