Java Methods and Functions Explained in Depth with Examples

Java Methods and Functions Explained in Depth

Author: Gursehbaj Singh | Blog: DevMode

Methods in Java are blocks of code that perform a specific task. They help us write clean, reusable, and organized programs. In this guide, you will learn everything about Java methods in a simple and detailed way.

What is a Method in Java?

A method is a function that belongs to a class. It runs when it is called.


class Example {
    void showMessage() {
        System.out.println("Welcome to DevMode");
    }
}

Calling a Method


Example obj = new Example();
obj.showMessage();

Types of Methods in Java

1. Method Without Return Type


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

2. Method With Return Type


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

3. Static Method


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

4. Method With Parameters


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

Method Overloading

Same method name, different parameters.


int sum(int a, int b) {
    return a + b;
}

int sum(int a, int b, int c) {
    return a + b + c;
}

Recursion in Java

A method calling itself.


int factorial(int n) {
    if(n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

Real Example: Calculator Using Methods


class Calculator {

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

    int subtract(int a, int b) {
        return a - b;
    }

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

    int divide(int a, int b) {
        return a / b;
    }
}

Why Methods Are Important?

  • Code reuse
  • Easy debugging
  • Better readability
  • Structured programming

Common Mistakes

  • Forgetting return statement
  • Wrong parameter types
  • Calling non-static methods incorrectly

Conclusion

Methods are the backbone of Java programming. Once you master them, you can build large applications, create reusable logic, and write clean code easily.

Comments

Popular posts from this blog

Top 10 Free Coding Websites Every Beginner Should Use in 2026

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples

5 JavaScript Console Methods You're Not Using (But Should Be)