FUNCTIONS (METHODS)
Java Programming
Java Programming — Course Module
METHODS IN JAVA
In Java, functions are called methods and must belong to a class. They implement the structured / modular
programming approach.
■ Methods provide: Modularity · Code reuse · Easier testing · Data encapsulation · Readability
Type Description Invocation
Instance method Called on an object [Link]()
Static method Called on the class [Link]()
Constructor Special initialisation method new ClassName()
Abstract method No body — must be overridden (OOP — advanced)
METHOD DECLARATION SYNTAX
accessModifier returnType methodName(paramType param1, ...) {
// method body
return value; // omit if returnType is void
// Examples:
public static int sum(int a, int b) { return a + b; }
public void printHello() { [Link]("Hello"); }
private double average(int[] arr) { ... }
Access Modifiers:
Modifier Scope
public Accessible everywhere
private Same class only
protected Same package + subclasses
(default) Same package only
BUILT-IN METHODS — [Link]
Method Return Description
[Link](x) int/double Absolute value
[Link](x) double Square root
[Link](x,y) double x raised to y
[Link](x) double Natural log
Math.log10(x) double Log base 10
[Link]/cos/tan(x) double Trig functions (radians)
[Link](x) double Ceiling
[Link](x) double Floor
[Link](x) long Nearest integer
[Link](a,b) same Larger of two values
[Link]() double Random [0.0, 1.0)
USER-DEFINED METHODS — 4 CASES
Case Type Signature Call
1 No params, No return void fun() fun();
2 No params, Returns value int fun() int r = fun();
3 Params, No return void fun(int a, int b) fun(x, y);
4 Params, Returns value int fun(int a, int b) int r = fun(x, y);
EXAMPLE — ARMSTRONG & PERFECT NUMBER
import [Link];
public class NumberChecks {
static boolean isArmstrong(int n) {
int orig = n, digits = [Link](n).length(), sum = 0;
while (n != 0) { sum += [Link](n%10, digits); n /= 10; }
return sum == orig;
static boolean isPerfect(int n) {
int sum = 0;
for (int i = 1; i < n; i++) if (n%i==0) sum += i;
return sum == n;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link](isArmstrong(n) ? "Armstrong" : "Not Armstrong");
[Link](isPerfect(n) ? "Perfect" : "Not Perfect");
PASS BY VALUE vs PASS BY REFERENCE
■■ Java is always pass-by-value. For primitives, the value is copied. For objects/arrays, the reference (address)
is copied — so you can modify the object's contents but cannot reassign the caller's variable.
// Primitives — NOT modified // Arrays — MODIFIED
static void add(int n) { static void fill(int[] a) {
n = n + 10; a[0] = 99;
} }
int x = 5; int[] arr = {1,2,3};
add(x); fill(arr);
// x is still 5 // arr[0] is now 99
SWAP — VALUE vs ARRAY WRAPPER
// Does NOT swap in caller // Swaps via array wrapper
static void swap(int a, int b){ static void swap(int[] v) {
int t=a; a=b; b=t; int t=v[0]; v[0]=v[1];
} v[1]=t;
// a, b unchanged after call }
int[] v={10,20};
swap(v);
// v[0]=20, v[1]=10
PASSING ARRAYS TO METHODS
Type Declaration Call
1D array void sort(int[] a, int n) sort(arr, n);
2D array void assign(int[][] a, int m, int n) assign(matrix, m, n);
Return array int[] buildArr(int n) int[] r = buildArr(n);
// Bubble sort on a 1D array
static void sort(int[] a) {
int n = [Link];
for (int i=0;i<n-1;i++)
for (int j=0;j<n-1-i;j++)
if (a[j] > a[j+1]) {
int t=a[j]; a[j]=a[j+1]; a[j+1]=t;
RECURSION
A method that calls itself. Every recursive solution needs:
Component Role
Base case Terminates recursion — prevents infinite loop
Recursive call Reduces problem to a smaller sub-problem
// Factorial — recursive
static int fact(int n) {
if (n == 0 || n == 1) return 1; // base case
return n * fact(n - 1); // recursive call
// Fibonacci — recursive
static int fib(int n) {
if (n == 0 || n == 1) return n;
return fib(n-1) + fib(n-2);
RECURSION — CALL STACK TRACE (fact(4))
Call Value
fact(4) → 4 * fact(3)
fact(3) → 3 * fact(2)
fact(2) → 2 * fact(1)
fact(1) → returns 1 (base case)
Unwinding 1 → 2 → 6 → 24
RECURSION — PRINT ALL SUBSEQUENCES
static void subseq(int[] arr, int n, int idx, int[] sub, int size) {
if (idx == n) {
for (int i=0;i<size;i++) [Link](sub[i]+" ");
[Link]();
return;
sub[size] = arr[idx]; // include current
subseq(arr, n, idx+1, sub, size+1);
subseq(arr, n, idx+1, sub, size); // exclude current
// Call: subseq(new int[]{1,2,3}, 3, 0, new int[10], 0);
METHOD OVERLOADING (Java-specific)
Java allows multiple methods with the same name but different parameter lists.
static int add(int a, int b) { return a+b; }
static double add(double a, double b) { return a+b; }
static int add(int a, int b, int c) { return a+b+c; }
// Java picks the right version at compile time
[Link](add(2, 3)); // calls first
[Link](add(2.0, 3.5)); // calls second
[Link](add(1, 2, 3)); // calls third
RECURSION — PROS & CONS
Aspect Detail
Pro Elegant, concise code Easier to reason about tree/divide problems
Matches mathematical
Pro definitions Factorial, Fibonacci, etc.
Con Overhead of function call stack Slower than iterative for simple loops
Con Risk of StackOverflowError If base case is missing or wrong
Con Higher memory usage Each call frame stored on stack