0% found this document useful (0 votes)
2 views43 pages

Java Functions

The document provides an overview of Java functions, detailing their definition, syntax, and usage within classes. It explains how to define functions with various parameters, return types, and the importance of functions for code reusability and organization. Additionally, it covers method overloading, types of methods, and examples of calling both predefined and user-defined methods in Java.

Uploaded by

sharmila.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views43 pages

Java Functions

The document provides an overview of Java functions, detailing their definition, syntax, and usage within classes. It explains how to define functions with various parameters, return types, and the importance of functions for code reusability and organization. Additionally, it covers method overloading, types of methods, and examples of calling both predefined and user-defined methods in Java.

Uploaded by

sharmila.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Java Function

Java is one of the most popular programming languages in the world, and
one of its key features is its ability to define and use functions. Functions
in Java are blocks of code that perform a specific task, and they are used
to organize code and make it more modular and reusable.

Defining a Java Function


In order to define a function in Java, you use the keyword "public" (or
"private" or "protected") followed by the return type of the function, then
the name of the function, and finally a set of parentheses containing any
parameters the function may take. For example, here is a simple function
that takes no parameters and returns nothing:

1. public void sayHello() {


2. System.out.println("Hello, world!");
3. }

In this case, the function is called "sayHello", it takes no parameters (i.e.,


the parentheses are empty), and it returns nothing (i.e., the return type is
"void"). To call this function from another part of your code, you simply
write its name followed by a set of parentheses, like this:

1. sayHello();
Passing Parameters to a Java Function
Functions can also take one or more parameters, which are passed in as
values when the function is called. To define a function that takes one or
more parameters, you simply list them inside the parentheses when you
define the function. Here's an example of a function that takes two
parameters (both of type "int") and returns their sum:

Backward Skip 10sPlay VideoForward Skip 10s

1. public int add(int a, int b) {


2. return a + b;
3. }

In this case, the function is called "add", it takes two parameters (both of
type "int"), and it returns their sum (also of type "int"). To call this
function and pass in two values, you would write:/p>

1. int result = add(5, 7);


In this case, the values 5 and 7 are passed in as the values of the "a" and
"b" parameters, respectively, and the result of the function (12) is
assigned to the "result" variable.

Returning Values from a Java Function


Functions in Java can also return a value, which is specified by the return
type of the function. To define a function that returns a value, you simply
specify the return type (which can be any data type, including objects)
before the function name, like this:

1. public int doubleValue(int a) {


2. return a * 2;
3. }

In this case, the function is called "doubleValue", it takes one parameter


(an integer), and it returns twice the value of that parameter. To call this
function and get the result, you would write:

1. int result = doubleValue(5);

In this case, the value 5 is passed in as the value of the "a" parameter,
and the result of the function (10) is assigned to the "result" variable.

Functions are an important part of any programming language, and Java is


no exception. With Java functions, you can organize your code into
modular, reusable blocks, and pass in values and return results as
needed. By mastering the basics of Java functions, you will be well on your
way to becoming a skilled Java programmer. Functions in Java are also
commonly known as methods, and they play a key role in structuring and
organizing code. By encapsulating blocks of code into functions, you can
create reusable and modular code that can be called from other parts of
the program.

Java functions can take zero or more parameters as input, and they can
return a value or perform an action without returning a value. The return
type of a function is specified by placing the data type of the return value
before the name of the function.

Here's an example Java program with input and output that demonstrates
Java functions:

FunctionExample.java

1. import java.util.Scanner;
2. public class FunctionExample {
3. public static void main(String[] args) {
4. Scanner scanner = new Scanner(System.in);
5.
6. System.out.print("Enter a number: ");
7. int num1 = scanner.nextInt();
8.
9. System.out.print("Enter another number: ");
10. int num2 = scanner.nextInt();
11. int sum = add(num1, num2);
12. System.out.println("The sum of " + num1 + " and " + num2 + " is " +
sum + "."); public static int add(int a, int b) {
13. return a + b;
14. }
15. }

Output:

Enter a number: 5
Enter another number: 7
The sum of 5 and 7 is 12.

In this program, the user is prompted to enter two numbers, which are
then passed to the add function. The function calculates their sum and
returns it, which is then printed to the console along with a message that
includes the original numbers.

The goal of every programmer is to save time in both programming


and debugging. However, there comes a time when you write
hundreds of lines of code. It’s very frustrating having to repeat the
same code now and then. It is more frustrating when your code gets
some error, and you will need to debug the whole program.

Improve your programming expertise by using functions. Functions


help in avoiding ambiguity. You will agree that breaking down the
code into smaller chunks in functions will help you organize your
work, and debugging becomes easy. Why repeat the same lines of
code several places where you can put it inside a function and call it
whenever you need to perform that task. Code reusability saves a
lot of time.

All the functions must be defined within a class. By that, we


can summarize by defining a Java method as a function belonging to
a class. A function is a named unit of code that can be invoked
anywhere in the class.
Example:

Java
public class Main {
public static void myFuntion() {
// Do something here
}
}

Java
public class Main {
public static void myFuntion() {
// Do something here
}
}

Structure-of-a-

Syntax of a function
Java
Public static void myFuction(String name, int age )
{
// fuction code
}

 Access specifier – this shows the scope of availability of a


fuction. ‘Public’ means that the function can be called from
aywhere in the program. We have other access specifiers such
as private and protected.Protected, the method can only be
called within the class and its subslcasses. Private can oly be
called inside the class
 Modifier – ‘static’ is optional in a fuction defination. In this
case static means the function is a not an object of the main
class but a method that belongs to the main class.
 Return type – We have functions that return a value and
functions that do not return anything. Void, means that the
function does not have a return value. If the fuction was to
return a value, replace void with the data type of the returned
value.
 Function name – This the name of the function
 Parameter list – it informs the compiler about the data type it
will receive and the value to be returned.

Advantages of functions in Java


1. Reusability of code – functions help in removing repetition of
code in a program. With functions you can define it once and
call it anywhere in the program to perform the task you need
and you are not limited to the number of times you call the
function. Lastly it’s simple to relace the functions into libraries.
This allows them to be used by more than one program.

2. Divide and conquer – Using functions helps break a program


into smaller manageable chunks, hence making debugging and
testing easier. Functions help in collaboration by breaking up the
work into tasks for team development.

Types of fuctions
Computational functions – these functions perform mathematical
operations and return the result. e.g., Math. sqrt. ()

Manipulative functions – they return 0 or 1, representing the


success or failure of an operation.

Procedural functions – these are mostly the inbuilt functions.


They perform an action but do not return a value, e.g.,
System.out.print()

How to call a functio in java


Calling a static method
We can call a method by writing the method’s name followed by the
parenthesis and a semicolon. When a method is called, the program
task to be performed is transferred to the method.
Example:

Java
public class myFunction {

static void functionExample() {


System.out.println("You have called me! My name is: functionExample!");
}

public static void main(String[] args) {


fuctionExample();
}
}

Output:

You have called me! My name is: functionExample!


From the above example, we called a static method. To call a static
method, we do not need to create an object of the class in which the
method is defined.

Calling a pre-defined method


These are methods that are pre-defined in classes. To call this
method, you can call them by their name. You will need to create an
object because it’s a method of the class object.

Java
public class myfunction
{
public static void main(String[] args)
{
int a = 49;
double ans=Math.sqrt(a);
System.out.println("The square root of the object is: "+ans);
}
}

Calling a user defined method


This is where we create a method and then call it when we need to
use it. The user-defined method can be a static method or a non-
static method.

Java
public class functionExample
{
//user-defined static method
static void show()
{
System.out.println("This is a static method.");
}
//user-defined non-static method
void display()
{
System.out.println("This is a non-static method.");
}
public static void main(String[] args)
{
//calling static method without using the object
show();

//creating an object of the class


functionExample fun=new functionExample();
//calling non-static method
fun.display();
}
}

From the above example, we created a static user-defined


method show() and non-static user-defined methods display(). We
call a static method directly without creating an object, but for a
non-static method, we created an object of the class to call it.

Method overloading
Method overloading is when the class contains two or more methods
with the same name. The methods can be differentiated by the
number of parameters, return type, or the type of parameters.
Example:

Java
int sum( int a, int b);
double sum( double a, double b);

Java
int sum( int a, int b);
double sum( double a, double b);

The two above methods have the same name but different return
types. The first method will return an int while the second method
returns a double.

Java
int function(double number);
int function(double number, int position);

Java
int function(double number);
int function(double number, int position);

From the above example, the two functions have the same name
but differ in the number of parameters. The first method has 1
parameter, while the second method contains 2 parameters.

The compiler distinguishes which function is called based on what is


passed during the function call.
Example:

Java
public class Main
{
static int sum(int a, int b)
{
return a + b;
}
static double sum(double a, double b)
{
return a + b;
}

public static void main(String[] args)


{

int x = sum(10, 20);


double y = sum(10.20,20.10);

System.out.println("Summation of integer values = " +x);


System.out.println("Summation of double values = " +y);
}
}

Java
public class Main
{
static int sum(int a, int b)
{
return a + b;
}
static double sum(double a, double b)
{
return a + b;
}

public static void main(String[] args)


{

int x = sum(10, 20);


double y = sum(10.20,20.10);

System.out.println("Summation of integer values = " +x);


System.out.println("Summation of double values = " +y);
}
}
Output:

Summation of integer values = 30


Summation of double values = 30.3

Conclusion
In java, static methods belong to a class; hence we do not need to
create an object when calling these methods. However, for the non-
static method, we need to create an object because the methods
belong to objects. Functions describe an action to be performed.
Creating functions helps in avoiding code ambiguity in your program
and allows code reusability. In this tutorial, we have discussed what
functions in java are, creating the functions and calling the function.

Java Methods
Last Updated : 08 Apr, 2024



The method in Java or Methods of Java is a collection of
statements that perform some specific tasks and return the result
to the caller. A Java method can perform some specific tasks
without returning anything. Java Methods allows us to reuse the
code without retyping the code. In Java, every method must be
part of some class that is different from languages like C, C++,
and Python.
 A method is like a function i.e. used to expose the
behavior of an object.
 It is a set of codes that perform a particular task.
Syntax of Method
<access_modifier> <return_type>
<method_name>( list_of_parameters)
{
//body
}
Advantage of Method
 Code Reusability
 Code Optimization
Note: Methods are time savers and help us to reuse the code
without retyping the code.
Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from
where it can be accessed in your application. In Java, there 4
types of access specifiers.
 public: It is accessible in all classes in your application.
 protected: It is accessible within the class in which it is
defined and in its subclasses.
 private: It is accessible only within the class in which it is
defined.
 default: It is declared/defined without using any modifier.
It is accessible within the same class and package within
which its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the
method or void if does not return a value. It is Mandatory in
syntax.
3. Method Name: the rules for field names apply to method
names as well, but the convention is a little different. It
is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input
parameters is defined, preceded by their data type, within the
enclosed parenthesis. If there are no parameters, you must use
empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can
throw; you can specify these exception(s). It is Optional in
syntax.
6. Method body: it is enclosed between braces. The code you
need to be executed to perform your intended operations. It
is Optional in syntax.

Types of Methods in Java


There are two types of methods in Java:
1. Predefined Method
In Java, predefined methods are the method that is already
defined in the Java class libraries is known as predefined
methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling
them in the program at any point.
2. User-defined Method
The method written by the user or programmer is known as a
user-defined method. These methods are modified according to
the requirement.
Ways to Create Method in Java
There are two ways to create a method in Java:
1. Instance Method: Access the instance data using the object
name. Declared inside a class.
Syntax:
// Instance Method
void method_name(){
body // instance area
}
2. Static Method: Access the static data using class name.
Declared inside class with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area
}
Method Signature:
It consists of the method name and a parameter list (number of
parameters, type of the parameters, and order of the
parameters). The return type and exceptions are not considered
as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2, Type of
parameter is int.
Naming a Method
A method name is typically a single word that should be a verb in
lowercase or a multi-word, that begins with a verb in lowercase
followed by an adjective, noun. After the first word, the first
letter of each word should be capitalized.
Rules to Name a Method:
 While defining a method, remember that the method
name must be a verb and start with a lowercase letter.
 If the method name has more than two words, the first
name must be a verb followed by an adjective or noun.
 In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For
example, findSum, computeMax, setX, and getX.
Generally, a method has a unique name within the class in which
it is defined but sometimes a method might have the same name
as other method names within the same class as method
overloading is allowed in Java.
Method Calling
The method needs to be called for use its functionality. There can
be three situations when a method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method.
 It reaches a return statement.
 Throws an exception.
Example:
Java
// Java Program to Illustrate Methods

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Addition {

// Initially taking sum as 0


// as we have not started computation
int sum = 0;

// Method
// To add two numbers
public int addTwoInt(int a, int b)
{

// Adding two integer value


sum = a + b;

// Returning summation of two values


return sum;
}
}

// Class 2
// Helper class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of class 1 inside main() method


Addition add = new Addition();

// Calling method of above class


// to add two integer
// using instance created
int s = add.addTwoInt(1, 2);

// Printing the sum of two numbers


System.out.println("Sum of two integer values :"
+ s);
}
}

Output
Sum of two integer values :3

Example 2:
Java
// Java Program to Illustrate Method Calling
// Via Different Ways of Calling a Method

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Test {

public static int i = 0;

// Constructor of class
Test()
{

// Counts the number of the objects of the class


i++;
}

// Method 1
// To access static members of the class and
// and for getting total no of objects
// of the same class created so far
public static int get()
{
// statements to be executed....
return i;
}

// Method 2
// Instance method calling object directly
// that is created inside another class 'GFG'.

// Can also be called by object directly created in the


// same class and from another method defined in the
// same class and return integer value as return type is
// int.
public int m1()
{

// Display message only


System.out.println(
"Inside the method m1 by object of GFG class");

// Calling m2() method within the same class.


this.m2();

// Statements to be executed if any


return 1;
}

// Method 3
// Returns nothing
public void m2()
{

// Print statement
System.out.println(
"In method m2 came from method m1");
}
}

// Class 2
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of above class inside the class


Test obj = new Test();

// Calling method 2 inside main() method


int i = obj.m1();

// Display message only


System.out.println(
"Control returned after method m1 :" + i);

// Call m2() method


// obj.m2();
int no_of_objects = Test.get();

// Print statement
System.out.print(
"No of instances created till now : ");

System.out.println(no_of_objects);
}
}

Output
Inside the method m1 by object of GFG class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1

The control flow of the above program is as follows:


Passing Parameters to a method
There are some cases when we don’t know the number of
parameters to be passed or an unexpected case to use more
parameters than declared number of parameters. In such cases
we can use
 Passing Array as an Argument
 Passing Variable-arguments as an Argument
 Method Overloading.
Memory Allocation for Methods Calls
Methods calls are implemented through a stack. Whenever a
method is called a stack frame is created within the stack area
and after that, the arguments passed to and the local variables
and value to be returned by this called method are stored in this
stack frame and when execution of the called method is finished,
the allocated stack frame would be deleted. There is a stack
pointer register that tracks the top of the stack which is adjusted
accordingly.
Example: pseudo-code for implementing methods
Java
// Define a class
public class Example {

// Define instance variables


private int number;
private String name;

// Define accessor (getter) methods


public int getNumber() {
return number;
}

public String getName() {


return name;
}

// Define mutator (setter) methods


public void setNumber(int number)
{
this.number = number;
}

public void setName(String name) { this.name = name; }

// Define other methods


public void printDetails()
{
System.out.println("Number: " + number);
System.out.println("Name: " + name);
}
}

// Use the methods in another part of the code


Example example = new Example();
example.setNumber(123);
example.setName("GFG Write");
example.printDetails();
There are several advantages to using methods in Java,
including:
 Reusability: Methods allow you to write code once and
use it many times, making your code more modular and
easier to maintain.
 Abstraction: Methods allow you to abstract away
complex logic and provide a simple interface for others to
use. This makes your code more readable and easier to
understand.
 Improved readability: By breaking up your code into
smaller, well-named methods, you can make your code
more readable and easier to understand.
 Encapsulation: Methods allow you to encapsulate
complex logic and data, making it easier to manage and
maintain.
 Separation of concerns: By using methods, you can
separate different parts of your code and assign different
responsibilities to different methods, improving the
structure and organization of your code.
 Improved modularity: Methods allow you to break up
your code into smaller, more manageable units, improving
the modularity of your code.
 Improved testability: By breaking up your code into
smaller, more manageable units, you can make it easier
to test and debug your code.
 Improved performance: By organizing your code into
well-structured methods, you can improve performance
by reducing the amount of code that needs to be
executed and by making it easier to cache and optimize
your code.
Q. What is a method in Java programming?
Java Method is a collection of statements that perform some
specific task and return the result to the caller.
Java Program to Illustrate a Method Without
Parameters and Return Type
Last Updated : 17 Apr, 2023



Functions are a way to break a program into different modules
which are executed one by one. To use a function in Java we need
to:
 Declare the function i.e. declare a prototype of the
function.
 Define the function
 Call the function
It is important that we declare the function before calling it and
the definition can be kept at any portion of the program.
Declaring, Defining and Calling a function
Now we will be creating a function with no return type and no
parameters. While declaring a function we need to specify the
return type of the functions and the number and types of
parameters it is going to accept. For the return type, we have
options such as int, float, char etc. But sometimes we don’t have
to return anything in such scenario we have to use
the void return type. And since we are not going to pass any
parameter too, so we have to specify it while declaring by
keeping the parenthesis empty.
Example:
 Java

// Java Program to Illustrate a Method with No Parameters


// and Return Type

public class Main {

// Declaration and Definition of the function


public static void greet()
{
System.out.println(
"Hey Geeks! Welcome to NoWhere.");

/* Optional program will work same


without this return statement */
return;
}
public static void main(String args[])
{
// Calling of the function without any parameters
greet();
}
}

Output
Hey Geeks! Welcome to NoWhere.
The time complexity and auxiliary space are both
constant, O(1).

Java Method Parameters


❮ PreviousNext ❯

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.

Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

ExampleGet your own Java Server


public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {


myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

Try it Yourself »

When a parameter is passed to the method, it is called an argument. So,


from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.

Multiple Parameters
You can have as many parameters as you like:

Example
public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age);

public static void main(String[] args) {

myMethod("Liam", 5);
myMethod("Jenny", 8);

myMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31

Try it Yourself »

Note that when you are working with multiple parameters, the method call
must have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.

Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:

Example
public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

System.out.println(myMethod(3));

}
}

// Outputs 8 (5 + 3)

Try it Yourself »

This example returns the sum of a method's two parameters:

Example
public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

System.out.println(myMethod(5, 3));

// Outputs 8 (5 + 3)

Try it Yourself »

You can also store the result in a variable (recommended, as it is easier to


read and maintain):

Example
public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);


System.out.println(z);

// Outputs 8 (5 + 3)

Try it Yourself »

ADVERTISEMENT

A Method with If...Else


It is common to use if...else statements inside methods:

Example
public class Main {

// Create a checkAge() method with an integer variable called


age

static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old


enough!");

// If age is greater than, or equal to, 18, print "access


granted"

} else {

System.out.println("Access granted - You are old enough!");

}
public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along an


age of 20

// Outputs "Access granted - You are old enough!"

Java Method Overloading


❮ PreviousNext ❯

Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:

ExampleGet your own Java Server


int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

Consider the following example, which has two methods that add numbers of
different type:

Example
static int plusMethodInt(int x, int y) {

return x + y;

static double plusMethodDouble(double x, double y) {


return x + y;

public static void main(String[] args) {

int myNum1 = plusMethodInt(8, 5);

double myNum2 = plusMethodDouble(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

Try it Yourself »

Instead of defining two methods that should do the same thing, it is better to
overload one.

In the example below, we overload the plusMethod method to work for


both int and double:

Example
static int plusMethod(int x, int y) {

return x + y;

static double plusMethod(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);

double myNum2 = plusMethod(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);


}

Try it Yourself »

Note: Multiple methods can have the same name as long as the number
and/or type of parameters are different.

Java Program to Illustrate a Method without


Parameters But with Return Type
Last Updated : 12 Sep, 2022



The task is to illustrate a method that does not contain any
parameter but should return some value. Methods are used to
break a complete program into a number of modules that can be
executed one by one. Considering any random shape to illustrate:
Circle
Example: First a class named ‘Circle’ is supposed to be
created, then with the help of this class, it can calculate the area
and circumference of a circle.
1. Area calculation
2. Circumference calculation
Inside the class Circle, we will declare a variable called radius to
take the value of the radius from the user so that by using this
value of radius we will be able to calculate the area and
circumference of a circle. Now, for calculating the area and
circumference, we need to create two separate methods
called area() and circumference(), which does not take any
value as a parameter but will definitely return some value, and
the value which this method will return are the final values of
area and circumference of the circle. The methods will return the
values after calculating it with the help of the values of variables.
The most important thing to calculate the area and
circumference, and to use these methods are first to need is to
call those methods which are known as calling a function, for this
we have to create an object of Circle class because in the main
method, and we want to access them, methods of another class
hence we need to make the object of that class which contains
our methods area() and circumference() and by using the
object of the class Circle, we will easily call the methods and
those methods will return some value, and we will display it by
using our predefined function.
Syntax:
class name
{
datatype MethodName()
{
statements....
..
..
return value;
}
}
Implementation:
Example 1: Area calculation
 Java

// Java Program to Illustrate a Method


// without Parameters but with Return Type

// Importing generic java classes


import java.util.*;
// Importing Scanner class if
// input is from user (optional)*/
import java.util.Scanner;

// Auxiliary Class (Sample class)


// class which contains the method area()
class Circle {

// initializing the variable radius


double radius;

// functions calculating area


double area()
{
double r = 7;

// Area of circle will be calculate and


// will store into the variable ar
double ar = 3.14 * r * r;
// Method returning the area
return ar;
}
}

// Main Class
public class GFG {

// Main driver method


public static void main(String args[])
{
// Object of circle is created
Circle c = new Circle();

// Big type variable to hold area value


double area;

// Area method is called and


// will store the value in variable area
area = c.area();

// Printing area of circle


System.out.println("Area of circle is : " + area);
}
}

Output
Area of circle is : 153.86

Example 2: Circumference calculation


 Java

// Java Program to Illustrate a Method


// without Parameters but with Return Type

// Importing java generic classes


import java.util.*;

class Circle {

double radius;

// method which does not contain


// parameter but will return
// the circumference of circle
double circumference()
{

double r = 7;
double circum = 2 * 3.14 * r;

// Method returning the circumference of circle


return circum;
}
}
public class GFG {

public static void main(String args[])


{
// the object of circle is created to call the
// method circumference()
Circle c = new Circle();
double circum;

// the value returned from method will store into


// the variable circum
circum = c.circumference();
System.out.println("Circumference of circle is : "
+ circum);
}
}

Output
Circumference of circle is : 43.96
Time complexity: O(1) as constant operations have been done
Auxiliary space: O(1)

Recursion in Java



In Java, Recursion is a process in which a function calls itself
directly or indirectly is called recursion and the corresponding
function is called a recursive function. Using a recursive
algorithm, certain problems can be solved quite easily. A few Java
recursion examples are Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph,
etc.

Base Condition in Recursion

In the recursive program, the solution to the base case is


provided and the solution to the bigger problem is expressed in
terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, the base case for n < = 1 is defined and
the larger value of a number can be solved by converting it to a
smaller one till the base case is reached.

Working of Recursion

The idea is to represent a problem in terms of one or more


smaller sub-problems and add base conditions that stop the
recursion. For example, we compute factorial n if we know the
factorial of (n-1). The base case for factorial would be n = 0. We
return 1 when n = 0.
Java Recursion Programs

1. Factorial Using Recursion

The classic example of recursion is the computation of the


factorial of a number. The factorial of a number N is the product
of all the numbers between 1 and N. The below-given code
computes the factorial of the numbers: 3, 4, and 5.
 3= 3 *2*1 (6)
 4= 4*3*2*1 (24)
 5= 5*3*2*1 (120)
 Here the first few factorial values to give you an
idea of how this works:

FACTORI RESUL
AL MULTIPLICATION T
0! 1 1
1! 1 1
2! 1×2 2
3! 1×2×3 6
4! 1×2×3×4 24
5! 1×2×3×4×5 120
6! 1×2×3×4×5×6 720
1×2×3×4×5×6×
7! 7 5040
1×2×3×4×5×6×
8! 7×8 40,320
1×2×3×4×5×6× 362,88
9! 7×8×9 0

Below is the implementation of the factorial:
 Java
// Java Program to implement

// Factorial using recursion

class GFG {
// recursive method

int fact(int n)

int result;

if (n == 1)

return 1;

result = fact(n - 1) * n;

return result;

// Driver Class

class Recursion {

// Main function

public static void main(String[] args)

GFG f = new GFG();

System.out.println("Factorial of 3 is "

+ f.fact(3));

System.out.println("Factorial of 4 is "

+ f.fact(4));

System.out.println("Factorial of 5 is "

+ f.fact(5));

Output
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

3. Fibonacci Series

4. Fibonacci series are 0 and 1 and are used to generate the


Fibonacci series.
5.

6. Fibonacci Series

7. How to Find the Nth term of Fibonacci Series ?


8. In mathematical terms, the number at the nth position can
be represented by:
9. Fn = Fn-1 + Fn-2
10.

Fibonacci Numbers are the numbers is the integer sequence


where Fib(N) = Fib(N-2) + Fib(N-1). Below is the example to find
3,4,5.
 Fib(3) = Fib(2) + Fib(1) = Fib(1) + 0 + 1 = 1+1 = 2
 Fib(4) = Fib(3) + Fib(2) = 2+1 = 3
 Fib(5) = Fib(4) + Fib(3) = 3 + 2 = 5
Recursion Tree Diagram for Fibonacci Series

Below is the implementation of the Fibonacci Series:


 Java
// Java Program to implement
// Fibonacci Series

import java.io.*;

// Driver Function

class GFG {

// Function to return Fibonacci value

static int Fib(int N)

if (N == 0 || N == 1)

return N;

return Fib(N - 1) + Fib(N - 2);

// Main function

public static void main(String[] args)

// Factorial of 3

System.out.println("Factorial of " + 3 + " "

+ Fib(3));

// Factorial of 4

System.out.println("Factorial of " + 4 + " "

+ Fib(4));

// Factorial of 3

System.out.println("Factorial of " + 5 + " "

+ Fib(5));

}
}

Output
Factorial of 3 2
Factorial of 4 3
Factorial of 5 5
Stack Overflow error
If the base case is not reached or not defined, then the stack
overflow problem may arise. Let us take an example to
understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but
the number will never reach 100. So, the base case is not
reached. If the memory is exhausted by these functions on
the stack, it will cause a stack overflow error.
How is memory allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated
to it on the stack. A recursive function calls itself, the memory for
the called function is allocated on top of memory allocated to the
calling function and a different copy of local variables is created
for each function call. When the base case is reached, the
function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.
Let us take the example of recursion by taking a simple function.

 Java
// A Java program to demonstrate
// working of recursion

class GFG {

static void printFun(int test)

if (test < 1)

return;

else {

System.out.printf("%d ", test);

// Statement 2

printFun(test - 1);

System.out.printf("%d ", test);

return;

public static void main(String[] args)

int test = 3;

printFun(test);

Output
3 2 1 1 2 3
Explanation of the above Program

When printFun(3) is called from main(), memory is allocated


to printFun(3), a local variable test is initialized to 3, and
statements 1 to 4 are pushed on the stack as shown below
diagram. It first prints ‘3’.
In statement 2, printFun(2) is called and memory is allocated
to printFun(2), a local variable test is initialized to 2, and
statements 1 to 4 are pushed in the stack.
Similarly, printFun(2) calls printFun(1) and printFun(1) calls p
rintFun(0). printFun(0) goes to if statement and it return
to printFun(1).
The remaining statements of printFun(1) are executed and it
returns to printFun(2) and so on. In the output, values from 3 to
1 are printed and then 1 to 3 are printed.
The memory stack is shown in the below diagram:
Memory Stack Representation of Java Recursive Program

Advantages of Recursive Programming


The advantages of recursive programs are as follows:
 Recursion provides a clean and simple way to write code.
 Some problems are inherently recursive like tree
traversals, Tower of Hanoi, etc. For such problems, it is
preferred to write recursive code.
Disadvantages of Recursive Programming
The disadvantages of recursive programs is as follows:
The recursive program has greater space requirements
than the iterative program as all functions will remain in
the stack until the base case is reached.
 It also has greater time requirements because of function
calls and returns overhead.
Note: Both recursive and iterative programs have the same
problem-solving powers, i.e., every recursive program can be
written iteratively and vice versa is also true.

Java Recursion
❮ PreviousNext ❯

Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how
it works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range
of numbers together by breaking it down into the simple task of adding two
numbers:

ExampleGet your own Java Server


Use recursion to add all of the numbers up to 10.
public class Main {

public static void main(String[] args) {

int result = sum(10);

System.out.println(result);

public static int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

Try it Yourself »

Example Explained
When the sum() function is called, it adds parameter k to the sum of all
numbers smaller than k and returns the result. When k becomes 0, the
function just returns 0. When running, the program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0

Since the function does not call itself when k is 0, the program stops there
and returns the result.
Halting Condition
Just as loops can run into the problem of infinite looping, recursive functions
can run into the problem of infinite recursion. Infinite recursion is when the
function never stops calling itself. Every recursive function should have a
halting condition, which is the condition where the function stops calling
itself. In the previous example, the halting condition is when the
parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the


concept. In this example, the function adds a range of numbers between a
start and an end. The halting condition for this recursive function is
when end is not greater than start:

Example
Use recursion to add all of the numbers between 5 to 10.

public class Main {

public static void main(String[] args) {

int result = sum(5, 10);

System.out.println(result);

public static int sum(int start, int end) {

if (end > start) {

return end + sum(start, end - 1);

} else {

return end;

Try it Yourself »

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

You might also like