Day 5 and 6
Day 5 and 6
Methods in Java
A method is a block of code that performs a specific task. You define a method once, and
then it can be called (or invoked) multiple times throughout the program, helping in code
reusability and modularization.
Syntax of a Method:
returnType methodName(parameters) {
// method body
returnType: The type of value the method returns. It can be any data type or void if it does
not return anything.
methodName: The name of the method. It should be meaningful and follow camel case
(e.g., calculateSum).
parameters: Input values passed to the method. If no input is required, the parameter list is
empty.
// Method definition
In this example, the greet() method doesn't take any arguments and doesn't return any value
(its return type is void).
Example:
int a = 10;
int b = 20;
Here, the method addNumbers takes two int parameters and returns their sum.
Return Statement:
The return statement is used to return a value from the method to the caller.
Example:
return a * b;
The return type of the method is int, and it returns the product of a and b.
3. Method Overloading
3. Method Overloading allows you to define multiple methods with the same name but
different parameter lists. This is useful when you want the same functionality with different
types of input.
Example:
return a + b;
return a + b;
In this example, both methods are named add, but they differ in the type of parameters they
accept (one accepts integers, the other accepts doubles).
4. Recursion
Recursion is a process where a method calls itself in order to solve a problem. A recursive
function typically has two parts:
int num = 5;
if (n == 0) {
} else {
In this example, the method factorial calls itself to compute the factorial of a number.
Write a method that takes two numbers as arguments and returns their sum.
if (result) {
} else {
if (n <= 1) {
return false;
if (n % i == 0) {
return false;
return true;
}
Problem 3: Fibonacci Series Using Recursion
int n = 10;
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
System.out.println("GCD of " + num1 + " and " + num2 + " is " + result);
if (b == 0) {
} else {
Method Overloading: Multiple methods can have the same name if they differ in the
number or type of parameters.
Recursion: A method that calls itself. Make sure to define a base case to avoid infinite
recursion.
Parameters: Methods can take input in the form of parameters, and the values of these
parameters are passed when the method is called.
Return Statement: If a method returns a value, you must specify the return type in the
method signature.