A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
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:
public class MyClass { static void myMethod() { // code to be executed } }
References: Click Here
Example:
class Main { // create a method public static int divideNumbers(int a, int b) { int div = a / b; // return value return div; } public static void main(String[] args) { int num1 = 25; int num2 = 15; // create an object of Main Main obj = new Main(); // calling method int result = obj.addNumbers(num1, num2); System.out.println("Sum is: " + result); } }
Task:
You need to define two functions in the code below:
First function should be named add and it must accept two integer arguments and it must return sum of both the integer arguments.
Second function should be named multiply and it must accept two integer arguments and it must return multiplication of both the integer arguments.
The given code take two integers as input and print their sum and multiplication on separate lines.
You just need to define two functions as mentioned above.