Method in Java
Method in Java
In this tutorial, we will learn about Java methods, how to define methods, and
how to use methods in Java programs with the help of examples.
Java Methods
Dividing a complex problem into smaller chunks makes your program easy to
understand and reusable.
returnType methodName() {
// method body
}
Here,
If the method does not return a value, its return type is void.
methodName - It is an identifier that is used to refer to the particular method in
a program.
method body - It includes the programming statements that are used to perform
some tasks. The method body is enclosed inside the curly braces { }.
For example,
int addNumbers() {
// code
}
In the above example, the name of the method is adddNumbers(). And, the
return type is int. We will learn more about return types later in this tutorial.
This is the simple syntax of declaring a method. However, the complete syntax
of declaring a method is
Here,
modifier - It defines access types whether the method is public, private, and so
on. To learn more, visit Java Access Specifier.
static - If we use the static keyword, it can be accessed without creating objects.
For example, the sqrt() method of standard Math class is static. Hence, we can
directly call Math.sqrt() without creating an instance of Math class.
parameter1/parameter2 - These are values passed to a method. We can pass
any number of arguments to a method.
// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}
Output
Sum is: 40
Here, we have called the method by passing two arguments num1 and num2.
Since the method is returning some value, we have stored the value in
the result variable.
Note: The method is not static. Hence, we are calling the method using the
object of the class.
A Java method may or may not return a value to the function call. We use
the return statement to return any value. For example,
int addNumbers() {
...
return sum;
}
Here, we are returning the variable sum. Since the return type of the function
is int. The sum variable should be of int type. Otherwise, it will generate an
error.
Example 2: Method Return Type
class Main {
// create a method
public static int square(int num) {
// return statement
return num * num;
}
Output:
Squared value of 10 is: 100
In the above program, we have created a method named square(). The method
takes a number as its parameter and returns the square of the number.
Here, we have mentioned the return type of the method as int. Hence, the
method should always return an integer value.
Representation of the
Java method returning a value
Note: If the method does not return any value, we use the void keyword as the
return type of the method. For example,
public void square(int a) {
int square = a * a;
System.out.println("Square is: " + square);
}