Skip to content

🧩 Java Methods – Writing Reusable Code

🔖 Introduction

One of the most powerful features of any programming language is the ability to reuse code. In Java, this is done using methods (also called functions in other languages). They allow you to break your program into smaller, manageable pieces.

In this lesson, you’ll learn how to define, call, and work with methods in Java.


🛠️ What is a Method?

A method is a block of code that only runs when it is called. It can:

  • Take input (parameters)
  • Perform an operation
  • Return a value

📌 Method Syntax

returnType methodName(parameter1, parameter2, ...) {
    // method body
    return value; // (optional)
}

🔹 Example 1: A Simple Method

public class HelloMethod {
    public static void main(String[] args) {
        sayHello(); // method call
    }

    static void sayHello() {
        System.out.println("Hello from the method!");
    }
}

🔸 Example 2: Method with Parameters

public class GreetUser {
    public static void main(String[] args) {
        greet("Raaz");
    }

    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

📥 You can pass values (arguments) into the method.

🔹 Example 3: Method with Return Value

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

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

✅ The return keyword sends back a result from the method.

🔁 Method Overloading

You can define multiple methods with the same name but different parameters. This is called method overloading.

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

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

    public static void main(String[] args) {
        System.out.println(add(2, 3));      // 5
        System.out.println(add(2.5, 3.5));  // 6.0
    }
}

🔍 Java’s main() Method Breakdown

public static void main(String[] args)

public: visible to all

static: runs without object

void: returns nothing

main: entry point

String[] args: accepts command-line arguments

🎯 Practice Exercise

Try creating a method called isEven(int number) that returns true if the number is even.

public class EvenCheck {
    public static void main(String[] args) {
        System.out.println(isEven(4));  // true
        System.out.println(isEven(7));  // false
    }

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

✅ What You Learned

  • How to create and call methods in Java
  • Method parameters and return types
  • Method overloading
  • The anatomy of the main() method

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *