LearnFrenzy
Sign in Take a free test

Java Programming · Topic 6 of 28

Methods and Recursion

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Methods and Recursion · Study material

Methods in Java package a piece of logic under a name so it can be reused, tested and understood on its own: calculateGst(amount), isValidEmail(text), sendOtp(phone). Good programs are built from many small methods that each do one thing. This topic covers how to define and call methods, parameters and return values, static vs instance methods, method overloading and how the compiler chooses an overload, varargs, why Java is always pass-by-value (the most misunderstood rule in Java), and recursion – a method that calls itself – with the call stack, StackOverflowError and memoization. These are core interview topics. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all compiled and run on Java 21.

On this page

  • Defining and calling methods; parameters, return values and void
  • Static vs instance methods
  • Method overloading and overload resolution
  • Varargs
  • Pass-by-value for primitives and references
  • Recursion, the call stack, StackOverflowError and memoization

Defining and calling methods

A method declaration has modifiers (public, static, …), a return type (or void), a name, a parameter list and a body. return sends a value back and ends the method; a non-void method must return a value on every path. The signature is the name plus the parameter types – the return type is not part of it.

public class Main {
    // modifiers  return-type  name(parameters)
    static double area(double radius) {
        return Math.PI * radius * radius;
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }

    static void greet(String name, int times) {          // void: returns nothing
        for (int i = 0; i < times; i++) System.out.print("Hi " + name + "! ");
        System.out.println();
    }

    static int max(int a, int b, int c) {
        return Math.max(a, Math.max(b, c));               // methods can call other methods
    }

    public static void main(String[] args) {
        System.out.printf("%.2f%n", area(2));
        System.out.println(isEven(10) + " " + isEven(7) + " " + max(4, 19, 7));
        greet("Asha", 2);
    }
}

Output

12.57
true false 19
Hi Asha! Hi Asha!

Static vs instance methods

A static method belongs to the class and is called as ClassName.method(); it cannot use instance fields or call instance methods directly, because there is no this. An instance method belongs to an object and works with that object's fields.

public class Main {
    private int count = 0;                       // belongs to each object

    void increment() { count++; }                // instance method: needs an object, can use fields
    int getCount() { return count; }

    static int square(int x) { return x * x; }   // static method: belongs to the class, no object needed

    public static void main(String[] args) {
        System.out.println(square(9) + " " + Main.square(3));
        Main a = new Main(), b = new Main();
        a.increment(); a.increment(); b.increment();
        System.out.println(a.getCount() + " " + b.getCount());
        // increment();      compile error: non-static method cannot be referenced from a static context
    }
}

Output

81 9
2 1

Method overloading

Several methods may share a name if their parameter lists differ (number, types or order). The compiler picks the most specific match in three phases: first exact matches and widening conversions, then boxing/unboxing, and only then varargs. Overloading is compile-time polymorphism; different return types alone are not enough.

public class Main {
    static String show(int x)        { return "int " + x; }
    static String show(long x)       { return "long " + x; }
    static String show(double x)     { return "double " + x; }
    static String show(Integer x)    { return "Integer " + x; }
    static String show(String s)     { return "String " + s; }
    static String show(int... xs)    { return "varargs of " + xs.length; }

    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) {
        byte b = 5;
        System.out.println(show(7));          // exact match
        System.out.println(show(b));          // widening byte → int beats boxing
        System.out.println(show(7L));
        System.out.println(show(2.5f));       // float widens to double
        System.out.println(show("hi"));
        System.out.println(show(1, 2, 3));    // varargs is tried last
        System.out.println(add(1, 2) + " " + add(1, 2, 3) + " " + add(1.5, 2));
    }
}

Output

int 7
int 5
long 7
double 2.5
String hi
varargs of 3
3 6 3.5

Varargs

type... name accepts zero or more arguments, which arrive in the method as an array. It must be the last parameter, and a method can have only one.

public class Main {
    static int sum(int... nums) {                     // nums is an int[]
        int total = 0;
        for (int n : nums) total += n;
        return total;
    }

    static String tag(String name, String... classes) {   // varargs must be the last parameter
        return "<" + name + (classes.length > 0 ? " class=\"" + String.join(" ", classes) + "\"" : "") + ">";
    }

    public static void main(String[] args) {
        System.out.println(sum() + " " + sum(5) + " " + sum(1, 2, 3, 4) + " " + sum(new int[]{10, 20}));
        System.out.println(tag("div") + " " + tag("p", "lead", "text-center"));
        System.out.printf("%s has %d items%n", "cart", 3);    // printf itself uses varargs
    }
}

Output

0 5 10 30
<div> <p class="lead text-center">
cart has 3 items

Java is always pass-by-value

A method receives copies of its arguments. For a primitive, the copy is the value – changing it does not affect the caller. For an object or array, the copy is the reference: the method can change the object the caller sees, but re-pointing the parameter to a new object does not affect the caller's variable.

import java.util.Arrays;

public class Main {
    static void bump(int n) { n++; }                              // changes a copy

    static void fill(int[] arr) { Arrays.fill(arr, 7); }          // copy of the reference → same array

    static void reassign(int[] arr) { arr = new int[]{0}; }       // only the local copy is re-pointed

    static void rename(StringBuilder sb) { sb.append(" Rao"); }   // the object is changed

    public static void main(String[] args) {
        int x = 5;
        int[] a = {1, 2, 3};
        StringBuilder name = new StringBuilder("Asha");
        bump(x);
        fill(a);
        reassign(a);
        rename(name);
        System.out.println(x + " " + Arrays.toString(a) + " " + name);
    }
}

Output

5 [7, 7, 7] Asha Rao

Recursion

A recursive method solves a problem by calling itself on a smaller version of it. Every recursive method needs a base case that returns without recursing, and each call must move towards it. Recursion fits naturally for factorials, GCD, tree and directory traversal, divide-and-conquer algorithms (binary search, merge sort) and generating combinations.

public class Main {
    static long factorial(int n) {
        if (n <= 1) return 1;              // base case: stops the recursion
        return n * factorial(n - 1);       // recursive case: a smaller problem
    }

    static int sumDigits(int n) {
        return n < 10 ? n : n % 10 + sumDigits(n / 10);
    }

    static long power(long base, int exp) {             // fast exponentiation: O(log exp)
        if (exp == 0) return 1;
        long half = power(base, exp / 2);
        return exp % 2 == 0 ? half * half : half * half * base;
    }

    static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static void countdown(int n) {
        if (n == 0) { System.out.println("liftoff"); return; }
        System.out.print(n + " ");
        countdown(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(factorial(10) + " " + sumDigits(98765) + " " + power(2, 40) + " " + gcd(84, 36));
        countdown(5);
    }
}

Output

3628800 35 1099511627776 12
5 4 3 2 1 liftoff

The call stack and StackOverflowError

Each call gets a stack frame holding its parameters and local variables. Frames are removed in reverse order as calls return. Recursion without a reachable base case (or simply too deep) exhausts the stack and throws StackOverflowError. Java does not optimise tail calls, so very deep recursion should be rewritten as a loop.

public class Main {
    static int depth = 0;

    static void trace(int n, String indent) {
        System.out.println(indent + "enter " + n);
        if (n > 0) trace(n - 1, indent + "  ");
        System.out.println(indent + "leave " + n);       // runs as the calls return, in reverse order
    }

    static void forever() {
        depth++;
        forever();                                        // no base case
    }

    public static void main(String[] args) {
        trace(2, "");
        try {
            forever();
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError after many calls: " + (depth > 1000));
        }
    }
}

Output

enter 2
  enter 1
    enter 0
    leave 0
  leave 1
leave 2
StackOverflowError after many calls: true

Recursion vs iteration

RecursionIteration
Codeoften shorter for tree-like problemsoften clearer for simple counting
Memoryone stack frame per active callconstant
RiskStackOverflowError on deep inputinfinite loops
Best fortrees, graphs, divide and conquer, backtrackinglinear scans, simple repetition

Common mistakes

  • Missing return on some path of a non-void method – compile error.
  • Calling an instance method from static main without an object.
  • Overloads that differ only in return type – not allowed.
  • Expecting a method to change a primitive argument – Java passes copies.
  • Recursion without a base case – StackOverflowError.
  • Naive recursive Fibonacci – exponential time; use memoization or a loop.
  • Ambiguous overloads with null or varargs.

Key points to remember

  • Signature = name + parameter types; return type is not part of it.
  • Static methods have no this; instance methods work on an object.
  • Overload resolution: widening, then boxing, then varargs.
  • Varargs arrive as an array and must be the last parameter.
  • Java is pass-by-value; for objects, the reference is copied.
  • Recursion needs a base case; deep recursion risks StackOverflowError.

Frequently asked questions

Is Java pass-by-reference for objects?

No. The reference is passed by value. You can change the object through it, but you cannot make the caller's variable point to a different object.

Can main be overloaded?

Yes, but the JVM only calls public static void main(String[]).

What is the difference between overloading and overriding?

Overloading: same name, different parameters, in the same class, chosen at compile time. Overriding: a subclass redefines an inherited method with the same signature, chosen at run time (see Polymorphism).

Where can I learn more?

Read Java Methods, Java Method Overloading and Varargs and Java Recursion and Pass-by-Value, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links