Ugenz Academy/Tutorial

Function

11 min read2,070 words

Reading progress

Keep learning

Java Functions (Methods)

Introduction

In Java, a function is generally called a method.

A method is a block of code that performs a specific task. Methods help us divide a large program into smaller, reusable parts.

Instead of writing the same code multiple times, we can define a method once and call it whenever needed.

Example

public class FunctionExample { static void greet() { System.out.println("Hello, Java!"); } public static void main(String[] args) { greet(); greet(); } }

Output

Hello, Java! Hello, Java!

Why Use Methods?

Methods are used to:

  1. Reuse code.
  2. Reduce code duplication.
  3. Make programs easier to understand.
  4. Make programs easier to maintain.
  5. Divide a large program into smaller tasks.
  6. Make debugging easier.
  7. Improve program organization.

Basic Syntax of a Method

accessModifier static returnType methodName(parameters) { // method body }

Example

public static int add(int a, int b) { return a + b; }

Here:

PartMeaning
publicAccess modifier
staticMethod belongs to the class
intReturn type
addMethod name
int a, int bParameters
returnReturns a value

Creating a Simple Method

public class MethodExample { static void display() { System.out.println("Welcome to Java"); } public static void main(String[] args) { display(); } }

Output

Welcome to Java

Calling a Method

A method is executed when we call it.

Example:

display();

Complete example:

public class MethodCall { static void display() { System.out.println("This is a method."); } public static void main(String[] args) { display(); display(); } }

Output

This is a method. This is a method.

Method Without Parameters

A method can be created without parameters.

Example

public class NoParameter { static void message() { System.out.println("Hello Java"); } public static void main(String[] args) { message(); } }

Output

Hello Java

Method With Parameters

A method can receive data through parameters.

Example

public class ParameterExample { static void greet(String name) { System.out.println("Hello " + name); } public static void main(String[] args) { greet("Anuradha"); greet("Ram"); } }

Output

Hello Anuradha Hello Ram

Here:

String name

is a parameter.

The values:

"Anuradha" "Ram"

are arguments.

Parameters vs Arguments

ParameterArgument
Variable defined in the methodActual value passed to the method
Receives the valueSupplies the value
Example: String nameExample: "Anuradha"

Example:

static void greet(String name) { System.out.println(name); } greet("Anuradha");

Here name is the parameter and "Anuradha" is the argument.

Method With Return Value

A method can return a value to the caller.

Example

public class ReturnExample { static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = add(10, 20); System.out.println("Sum = " + result); } }

Output

Sum = 30

return Statement

The return statement sends a value back to the method caller.

Example:

static int square(int number) { return number * number; }

Calling the method:

int result = square(5);

The returned value is:

25

Void Method

A method with void as its return type does not return a value.

Example

static void display() { System.out.println("Hello Java"); }

There is no value returned from this method.

Non-Void Method

A non-void method returns a value.

Example:

static int multiply(int a, int b) { return a * b; }

The return type is:

int

because the method returns an integer.

Types of Methods Based on Parameters and Return Value

There are four common combinations.

1. No Parameter and No Return Value

static void display() { System.out.println("Hello"); }

2. Parameter but No Return Value

static void displayName(String name) { System.out.println(name); }

3. No Parameter but Return Value

static int getNumber() { return 100; }

4. Parameter and Return Value

static int add(int a, int b) { return a + b; }

Summary Table

ParameterReturn ValueExample
NoNovoid display()
YesNovoid displayName(String name)
NoYesint getNumber()
YesYesint add(int a, int b)

Static Method

A static method belongs to the class rather than to an individual object.

It can be called directly using the class name, or directly from another static method in the same class.

Example

public class StaticMethod { static void display() { System.out.println("Static method"); } public static void main(String[] args) { display(); } }

You can also call it using the class name:

StaticMethod.display();

Instance Method

An instance method belongs to an object.

An object must be created before calling an instance method.

Example

public class InstanceMethod { void display() { System.out.println("Instance method"); } public static void main(String[] args) { InstanceMethod obj = new InstanceMethod(); obj.display(); } }

Output

Instance method

Static Method vs Instance Method

Static MethodInstance Method
Uses static keywordDoes not use static
Belongs to the classBelongs to an object
Can be called using class nameCalled using an object
No object required for invocationObject is normally required

Method Overloading

Method overloading means having multiple methods with the same name but different parameter lists.

The methods may differ in:

  • Number of parameters
  • Type of parameters
  • Order of parameter types

Example

public class MethodOverloading { static int add(int a, int b) { return a + b; } static int add(int a, int b, int c) { return a + b + c; } static double add(double a, double b) { return a + b; } public static void main(String[] args) { System.out.println(add(10, 20)); System.out.println(add(10, 20, 30)); System.out.println(add(10.5, 20.5)); } }

Output

30 60 31.0

Method overloading is an example of compile-time polymorphism.

Passing Multiple Parameters

A method can accept multiple parameters.

public class MultipleParameters { static void student(String name, int age, double marks) { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Marks: " + marks); } public static void main(String[] args) { student("Anuradha", 21, 85.5); } }

Output

Name: Anuradha Age: 21 Marks: 85.5

Passing an Array to a Method

An array can be passed as a method argument.

public class ArrayMethod { static void display(int[] numbers) { for (int number : numbers) { System.out.println(number); } } public static void main(String[] args) { int[] numbers = {10, 20, 30, 40}; display(numbers); } }

Output

10 20 30 40

Returning an Array from a Method

A method can return an array.

public class ReturnArray { static int[] getNumbers() { return new int[]{10, 20, 30, 40}; } public static void main(String[] args) { int[] numbers = getNumbers(); for (int number : numbers) { System.out.println(number); } } }

Recursive Method

A method that calls itself is called a recursive method.

Example: Factorial

public class RecursionExample { static int factorial(int n) { if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); } public static void main(String[] args) { int result = factorial(5); System.out.println("Factorial = " + result); } }

Output

Factorial = 120

How it works

factorial(5) ↓ 5 × factorial(4) ↓ 5 × 4 × factorial(3) ↓ 5 × 4 × 3 × factorial(2) ↓ 5 × 4 × 3 × 2 × factorial(1) ↓ 120

A recursive method must have a base condition to stop recursion.

Method Scope

Variables declared inside a method are local to that method.

Example:

public class MethodScope { static void display() { int number = 10; System.out.println(number); } public static void main(String[] args) { display(); // System.out.println(number); // Error } }

The variable number exists only inside display().

Java Passes Arguments by Value

Java uses pass-by-value.

For primitive values, the method receives a copy of the value.

Example

public class PassByValue { static void change(int number) { number = 100; } public static void main(String[] args) { int number = 10; change(number); System.out.println(number); } }

Output

10

Changing the parameter inside the method does not change the original primitive variable.

Method Calling Another Method

One method can call another method.

public class MethodCalling { static void first() { System.out.println("First method"); second(); } static void second() { System.out.println("Second method"); } public static void main(String[] args) { first(); } }

Output

First method Second method

Complete Example

The following program uses methods to calculate the total and average marks of a student.

public class StudentResult { static int calculateTotal(int[] marks) { int total = 0; for (int mark : marks) { total += mark; } return total; } static double calculateAverage(int total, int count) { return (double) total / count; } static void displayResult(int total, double average) { System.out.println("Total Marks = " + total); System.out.println("Average Marks = " + average); } public static void main(String[] args) { int[] marks = {80, 75, 90, 85, 70}; int total = calculateTotal(marks); double average = calculateAverage(total, marks.length); displayResult(total, average); } }

Output

Total Marks = 400 Average Marks = 80.0

Advantages of Methods

  1. Code Reusability A method can be called multiple times.

  2. Reduces Code Duplication The same code does not need to be written repeatedly.

  3. Easy Maintenance Changes can be made in one method.

  4. Improves Readability Large programs can be divided into smaller tasks.

  5. Easy Debugging Individual methods can be tested separately.

  6. Supports Modularity A large program can be divided into logical components.

Disadvantages of Methods

  1. Too many small methods can make a program harder to follow.
  2. Method calls have some execution overhead.
  3. Poorly designed methods can make code difficult to maintain.
  4. Recursive methods can use significant memory if recursion becomes deep.

Real-Life Applications of Methods

Methods are used for:

  • Calculating student results
  • Processing employee salaries
  • Validating user input
  • Performing calculations
  • Reading and writing files
  • Connecting to databases
  • Searching data
  • Sorting data
  • Processing user requests
  • Building reusable application features

Method Naming Rules

Java method names should follow these conventions:

  • Use meaningful names.
  • Use camelCase.
  • Start with a lowercase letter.
  • Do not use spaces.
  • Avoid Java reserved keywords.

Good names

calculateTotal() displayStudent() findLargest() calculateAverage()

Poor names

a() x() method1()

Meaningful names make programs easier to understand.

Method vs Function

In Java, the term method is normally used because executable behavior is defined inside classes.

FunctionMethod
General programming termCommon Java term
May exist independently in some languagesDefined inside a class or interface
Performs a specific taskPerforms a specific task
Java commonly calls it a methodExample: calculateTotal()

So, when learning Java:

Function in Java is generally called a method.

Summary

A method is a block of code that performs a specific task.

Important points:

  • Methods improve code reuse.
  • Methods can have parameters.
  • Methods can return values.
  • void methods do not return a value.
  • static methods belong to the class.
  • Instance methods are called through objects.
  • Methods can be overloaded.
  • Methods can call other methods.
  • A method can accept and return arrays.
  • Recursive methods can call themselves.
  • Java uses pass-by-value for method arguments.
  • Good method names should clearly describe what the method does.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy