Java - OOP - Methods
Methods in Java are a block of code that performs a specific task or action. It is a set of instructions that are combined to perform a specific task. In Java, a method is defined inside a class and can be called from any other class in the same program.
Here's a tutorial on methods in Java:
Defining a method: A method is defined inside a class using the following syntax:
<access-modifier> <return-type> <method-name> (<parameters>) {
// method body
}
- The access modifier can be public, private, protected, or default.
- The return type specifies the type of data that the method will return, and it can be a primitive data type or an object.
- The method name is the name of the method.
- Parameters are the variables that the method takes as input. They are separated by commas, and their types must be specified.
Method overloading: In Java, you can define two or more methods with the same name in a class. This is known as method overloading. The methods must have different parameters or different numbers of parameters.
Calling a method: To call a method in Java, you need to use the following syntax:
<method-name> (<arguments>);
- The method name is the name of the method you want to call.
- Arguments are the values that you want to pass to the method. They must match the data type of the parameters specified in the method definition.
Return statement: The return statement is used to return a value from a method. The syntax of the return statement is as follows:
return <value>;
The value is the data that the method returns.
Void methods: A void method is a method that does not return a value. Instead, it performs a specific task. The syntax of a void method is as follows:
void <method-name> (<parameters>) {
// method body
}
Recursion: In Java, a method can call itself. This is known as recursion. It is useful when you need to solve a problem that can be broken down into smaller sub-problems.
public class Example {
public static int sum(int a, int b) {
int result = a + b;
return result;
}
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
int result = sum(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is " + result);
}
}
In this example, we have defined a method named sum that takes two integers as input parameters and returns their sum. The main method calls this sum method and prints
Methods are a key part of object-oriented programming in Java, as they allow us to encapsulate behavior into reusable blocks of code. In this example, the sum method encapsulates the behavior of adding two integers together, and can be reused throughout the program wherever we need to perform that operation. Additionally, methods can have access modifiers like public, private, and protected that determine their visibility and accessibility to other parts of the program.