Java Functions
Java Functions
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.
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:
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>
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.
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.
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
}
Types of fuctions
Computational functions – these functions perform mathematical
operations and return the result. e.g., Math. sqrt. ()
Java
public class myFunction {
Output:
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);
}
}
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();
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.
Java
public class Main
{
static int sum(int a, int b)
{
return a + b;
}
static double sum(double a, double b)
{
return a + b;
}
Java
public class Main
{
static int sum(int a, int b)
{
return a + b;
}
static double sum(double a, double b)
{
return a + b;
}
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.
// Class 1
// Helper class
class Addition {
// Method
// To add two numbers
public int addTwoInt(int a, int b)
{
// Class 2
// Helper class
class GFG {
Output
Sum of two integer values :3
Example 2:
Java
// Java Program to Illustrate Method Calling
// Via Different Ways of Calling a Method
// Class 1
// Helper class
class Test {
// Constructor of class
Test()
{
// 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'.
// 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 {
// 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
Output
Hey Geeks! Welcome to NoWhere.
The time complexity and auxiliary space are both
constant, O(1).
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:
myMethod("Jenny");
myMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Try it Yourself »
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
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 {
return 5 + x;
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
Try it Yourself »
Example
public class Main {
return x + y;
System.out.println(myMethod(5, 3));
// Outputs 8 (5 + 3)
Try it Yourself »
Example
public class Main {
return x + y;
// Outputs 8 (5 + 3)
Try it Yourself »
ADVERTISEMENT
Example
public class Main {
} else {
}
public static void main(String[] args) {
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
float myMethod(float x)
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;
Try it Yourself »
Instead of defining two methods that should do the same thing, it is better to
overload one.
Example
static int plusMethod(int x, int y) {
return x + y;
return x + y;
Try it Yourself »
Note: Multiple methods can have the same name as long as the number
and/or type of parameters are different.
// Main Class
public class GFG {
Output
Area of circle is : 153.86
class Circle {
double radius;
double r = 7;
double circum = 2 * 3.14 * r;
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.
Working of Recursion
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
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
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
6. Fibonacci Series
import java.io.*;
// Driver Function
class GFG {
if (N == 0 || N == 1)
return N;
// Main function
// Factorial of 3
+ Fib(3));
// Factorial of 4
+ Fib(4));
// Factorial of 3
+ 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 {
if (test < 1)
return;
else {
// Statement 2
printFun(test - 1);
return;
int test = 3;
printFun(test);
Output
3 2 1 1 2 3
Explanation of the above Program
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:
System.out.println(result);
if (k > 0) {
} 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.
Example
Use recursion to add all of the numbers between 5 to 10.
System.out.println(result);
} 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.