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:
- Reuse code.
- Reduce code duplication.
- Make programs easier to understand.
- Make programs easier to maintain.
- Divide a large program into smaller tasks.
- Make debugging easier.
- 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:
| Part | Meaning |
|---|---|
public | Access modifier |
static | Method belongs to the class |
int | Return type |
add | Method name |
int a, int b | Parameters |
return | Returns 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
| Parameter | Argument |
|---|---|
| Variable defined in the method | Actual value passed to the method |
| Receives the value | Supplies the value |
Example: String name | Example: "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
| Parameter | Return Value | Example |
|---|---|---|
| No | No | void display() |
| Yes | No | void displayName(String name) |
| No | Yes | int getNumber() |
| Yes | Yes | int 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 Method | Instance Method |
|---|---|
Uses static keyword | Does not use static |
| Belongs to the class | Belongs to an object |
| Can be called using class name | Called using an object |
| No object required for invocation | Object 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
-
Code Reusability A method can be called multiple times.
-
Reduces Code Duplication The same code does not need to be written repeatedly.
-
Easy Maintenance Changes can be made in one method.
-
Improves Readability Large programs can be divided into smaller tasks.
-
Easy Debugging Individual methods can be tested separately.
-
Supports Modularity A large program can be divided into logical components.
Disadvantages of Methods
- Too many small methods can make a program harder to follow.
- Method calls have some execution overhead.
- Poorly designed methods can make code difficult to maintain.
- 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.
| Function | Method |
|---|---|
| General programming term | Common Java term |
| May exist independently in some languages | Defined inside a class or interface |
| Performs a specific task | Performs a specific task |
| Java commonly calls it a method | Example: 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.
voidmethods do not return a value.staticmethods 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.