The topic of today’s lesson is Java methods, which will help us to achieve our learning objectives.
Methods are blocks of code that only run when they are invoked.
A Java method accepts parameters, which are in the form of data and are passed into the method.
Java Methods and functions are both terms used to describe how certain actions are performed.
Why do we need Java methods?
By using them, it is possible to reuse code by defining it once and then using it repeatedly. Methods in Java can be classified into two types:
Generally, predefined methods in Java are those methods that are already defined in the Java class libraries.
This method is also known as a built-in or standard library method.
At any point in the program, we can call these methods directly.
The length(), equals(), compareTo(), sqrt(), and other pre-defined methods are examples.
An already stored series of code is executed in the background when we call any of the predefined methods in our program.
Predefined methods are defined within classes. Java.io.PrintStream contains methods such as print().
This method prints the statement that we write inside it. As an example, print(“mr examples”) prints mr examples on the console.
Our example below uses three predefined methods: main(), print(), and max().
User-defined methods are those that are developed by users or programmers. Depending on the requirements, these methods are modified.
Create User Defined Method:
As far as Java methods are concerned, then, they must be declared within the class.
Create a user-defined method to determine whether the number is even or odd:
Another example is defined by putting the name of the method followed by parentheses ().
There are some predefined methods in Java, such as System.out.println(), but you can also create your own methods to perform certain actions:
Example:  You will need to create a method inside Main:
- first_Method() is the name of the method
- A static method is one that belongs to the Main class and not an object of it. As the tutorial progresses, you will learn more about objects and how to access methods through them.
- void indicates that this method does not return anything. This chapter will explain return values in more detail.
Call a Method
Java methods is called by writing its name followed by two parentheses () and a semicolon ;
A text (the action) is printed when first_Method() is invoked, as shown below:
Call first_Method() inside main:
In the main method, we call second_Method():
It is also possible to call a method more than once:
You will learn how to pass data into a method (parameters) in the next chapter, Method Parameters.