Data, referred to as parameters, can be passed into a method.
Methods, also termed as functions, are employed to execute specific actions.
The primary purpose of using methods is to enable code reuse: defining functionality once and utilizing it multiple times.
In Java, a method must be enclosed within a class. It is characterized by its name followed by parentheses (). While Java offers pre-defined methods like System.out.println(), you also have the flexibility to define your own methods for executing specific actions.
Generate a method within the Main class.
|
To invoke a method in Java, simply write the method’s name followed by a pair of parentheses ( ) and a semicolon.
In the given example, the method myMethod() is utilized to print a text (the action) whenever it is invoked.
Invoke the myMethod() method within the main method.
|
A method can be invoked multiple times as well:
|
In the upcoming chapter, Method Parameters, you’ll explore how to transmit data (parameters) into a method. |