A method in Java is a block of code that performs a specific task. It has a name, a return type, and a list of parameters.
Java methods are used to perform repetitive tasks, to return values, and to group related code together.
Syntax:
modifier returnType methodName(parameter list) {
// code to be executed
}
Where:
- modifier defines the access level of the method (public, private, protected)
- returnType is the type of value returned by the method, or void if the method does not return a value
- methodName is the name of the method
- parameter list is a comma-separated list of parameters (optional)
Returning a value:
A method can return a value of any type (primitive or object type).
To return a value, use the return keyword followed by the value to be returned:
int addTwoNumbers(int a, int b) {
int result = a + b;
return result;
}
Void Methods:
A method that does not return a value is known as a void method.
The keyword void is used in the method declaration to specify that no value is returned:
void printMessage(String message) {
System.out.println(message);
}
Access Modifiers:
Java provides access modifiers to control the visibility of a method:
- public : The method can be accessed from anywhere.
- private : The method can only be accessed within the same class.
- protected : The method can be accessed within the same class and its subclasses.
Overloading Methods:
Java allows methods to have the same name within the same class, as long as the parameters are different.
This is known as method overloading.
class MathOperation {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Method Arguments:
Java methods can accept arguments or parameters, which are values passed to the method.
The data type of the parameter must be specified, followed by the parameter name:
void printSum(int a, int b) {
int sum = a + b;
System.out.println("The sum is: " + sum);
}
In conclusion, Java methods are a key aspect of the Java programming language and are used to organize code and perform repetitive tasks.
Understanding the syntax and how to use methods is essential for any Java programmer.