What is Method?
In Java, a method is a block of code that performs a specific task and can be called or invoked to execute that task. It is a fundamental building block of Java programs and is used to organize and structure code into reusable and modular units.
Note: Without a Method, you can not execute any Logic.
A method consists of a method signature and a method body:
Method signature: It defines the method's name, return type, and parameters (if any). The signature determines how the method can be called and what values it can return.
Method body: It contains the code that defines the behavior or functionality of the method. It is enclosed within curly braces {}.
How To Create a Method?
Declare the method: Start by declaring the method using the following syntax:
java<access modifier> <return type> <method name>(<parameter list>) { // Method body }
<access modifier>
: Specifies the accessibility of the method (e.g.,public
,private
,protected
, or no modifier for package-private).<return type>
: Specifies the data type of the value returned by the method (void
if the method doesn't return a value).<method name>
: The name of the method.<parameter list>
: The input parameters, if any, separated by commas. If the method doesn't take any parameters, leave it empty.
Implement the method body: Within the method, write the code that defines what the method does.
Return a value (optional): If the method has a return type other than
void
, use thereturn
keyword to return a value of that type.
Here's an example of a method that takes two integers as parameters, adds them, and returns the sum:
javapublic class MyClass {
public static void main(String[] args) {
int a = 5;
int b = 10;
int sum = addNumbers(a, b);
System.out.println("The sum is: " + sum);
}
public static int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
}
In this example, the method addNumbers
is declared with the public
access modifier, a return type of int
, and two int
parameters num1
and num2
. The method body calculates the sum of the two numbers and returns the result using the return
keyword.
When the addNumbers
method is called from the main
method, it returns the sum, which is then printed to the console. Output: The sum is: 15
.
Types of Method?
1. Parameterised method
2. Non-Parameterised method
3. Static Methods
4. Instance Methods
5. Constructor Methods
6 . Getter and Setter Methods
7. Method Overloading
8. Method Overriding
0 Comments