
208 views
Java Method
The Java method is a block of code within a class that performs a specific task or operation. Methods are used to organize and encapsulate behavior within a class, making the code more modular and reusable. Here are the key components and concepts related to methods in Java:
Method Signature:
- A method signature consists of the method’s name and its parameter list (if any). The return type is also part of the method’s signature.
- Example:
int add(int a, int b)
Method Declaration:
- The method declaration specifies the method’s name, return type, and the parameters it accepts. It also includes the method body enclosed within braces
{}
. - Example:
int add(int a, int b) {
int sum = a + b;
return sum;
}
Return Type:
- The return type indicates the data type of the value that the method will return. If a method doesn’t return a value, its return type is specified as
void
. - Example:
int
inint add(int a, int b)
Parameters:
- Parameters are variables that a method accepts to perform its task. They are specified in the method’s parameter list within parentheses.
- Example:
int a, int b
inint add(int a, int b)
Method Body:
- The method body is enclosed within curly braces
{}
and contains the statements that define the behavior of the method. - Example:
{
int sum = a + b;
return sum;
}
Method Invocation:
- To execute a method, you call it by its name followed by parentheses and provide the required arguments.
- Example:
int result = add(5, 3);
Method Overloading:
- Method overloading allows you to define multiple methods within the same class with the same name but different parameter lists. The compiler determines which method to call based on the arguments provided.
- Example:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
Method Return Statement:
- The
return
statement is used to exit a method and, optionally, return a value to the caller. The return value must match the method’s specified return type. - Example:
return sum;
Void Methods:
- Methods with a return type of
void
do not return any value. They perform an action or task but don’t produce a result. - Example:
void printMessage(String message) { System.out.println(message); }
Static Methods:
- Static methods belong to the class rather than an instance of the class. You can call them using the class name, without creating an object.
- Example:
static int multiply(int a, int b) {
return a * b;
}
Java methods are the building blocks of Java programs, enabling code reuse and the organization of functionality. They are crucial for implementing object-oriented concepts like encapsulation, inheritance, and polymorphism.