Index

Working with Methods

Java for Beginners

3.1 Defining and Calling Methods

In Java, methods are blocks of code that perform specific tasks. They help you organize code, avoid repetition, and make your programs more readable and reusable.

This section introduces how to define your own methods, how to give them names and parameters, and how to call them from the main method.

What Is a Method?

A method in Java is a group of statements that performs a task. It may accept input, do some processing, and optionally return a value.

Here is the general structure of a method:

returnType methodName(parameters) {
    // method body
}

Example 1: A Method That Adds Two Numbers

Let’s define a method that takes two integers as input and returns their sum.

public class AddExample {

    // Method that returns the sum of two integers
    public static int add(int a, int b) {
        int result = a + b;
        return result;
    }

    public static void main(String[] args) {
        int x = 5;
        int y = 7;
        int sum = add(x, y); // Method call
        System.out.println("The sum is: " + sum);
    }
}

Explanation:

Example 2: A Method That Returns a Greeting

Now let’s define a method that returns a personalized greeting using a String parameter.

public class GreetingExample {

    // Method that returns a greeting message
    public static String greet(String name) {
        return "Hello, " + name + "!";
    }

    public static void main(String[] args) {
        String message = greet("Alice");
        System.out.println(message);
    }
}

Explanation:

This method improves reusability — you can greet anyone by just changing the name.

Example 3: A Method That Calculates Area

Let’s write a method to calculate the area of a rectangle.

public class AreaCalculator {

    // Method to calculate the area of a rectangle
    public static double calculateArea(double width, double height) {
        return width * height;
    }

    public static void main(String[] args) {
        double w = 4.5;
        double h = 3.2;
        double area = calculateArea(w, h);
        System.out.println("Area: " + area);
    }
}

Key Concepts:

Notes on Method Structure and Readability

When defining methods:

Calling Methods from main

All Java programs start from the main method:

public static void main(String[] args) {
    // This is where your program starts
}

You call methods from main by using their name and passing any required arguments. The method’s return value (if any) can be stored in a variable or printed directly.

Why Use Methods?

Index

3.2 Parameters and Return Values

In Java, parameters and return values are essential parts of how methods communicate with the rest of your program. Parameters let you pass input into a method, and return values allow the method to pass results back.

This section builds on what you learned in Section 1 by expanding how methods handle input and output. You’ll learn how to define methods with multiple parameters, use void when no return is needed, and return various types like int, String, and boolean.

What Are Parameters and Return Values?

Method with Multiple Parameters

You can define a method that accepts more than one parameter by separating them with commas.

Example: Sum of Three Numbers

public class MultiParameterExample {

    // Method with three parameters
    public static int addThreeNumbers(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        int result = addThreeNumbers(5, 10, 15); // Passing three arguments
        System.out.println("Sum: " + result);    // Output: Sum: 30
    }
}

Method with No Return (void)

Sometimes, you don’t need a method to return a value — you just want it to perform an action, like printing something.

Example: Displaying a Welcome Message

public class VoidExample {

    // Method with no return value
    public static void showWelcomeMessage(String name) {
        System.out.println("Welcome, " + name + "!");
    }

    public static void main(String[] args) {
        showWelcomeMessage("Alice"); // Output: Welcome, Alice!
    }
}

Methods Returning Different Types

Java methods can return any data type. Let’s look at a few examples:

a. Method Returning int

public static int square(int number) {
    return number * number;
}

Usage:

int result = square(6);  // result = 36

b. Method Returning String

public static String getFullName(String firstName, String lastName) {
    return firstName + " " + lastName;
}

Usage:

String name = getFullName("John", "Doe");  // name = "John Doe"

c. Method Returning boolean

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

Usage:

if (isEven(4)) {
    System.out.println("The number is even.");
}

These examples show how return types allow your methods to send different kinds of data back to the caller.

Interactive Example: Age Checker

Let’s create a small program that checks if someone is an adult based on their age.

import java.util.Scanner;

public class AgeChecker {

    // Method that returns a boolean
    public static boolean isAdult(int age) {
        return age >= 18;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your age: ");
        int userAge = scanner.nextInt();

        if (isAdult(userAge)) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are not an adult.");
        }
    }
}

Breakdown:

This shows how methods with parameters and return values can interact with user input to make decisions.

Passing Arguments and Capturing Returns

When you call a method, the arguments must match the parameters in both type and order.

public static double average(int a, int b) {
    return (a + b) / 2.0;
}

// Calling the method
double result = average(8, 10);  // result = 9.0

Always ensure:

Index

3.3 Method Overloading

In Java, you can define multiple methods with the same name as long as they have different parameter lists. This is called method overloading. It allows a class to perform similar tasks in slightly different ways without creating completely different method names.

What Is Method Overloading?

Method overloading means defining more than one method in the same class with the same name, but with different:

Important: The method name stays the same, but the parameter list must differ in some way.

Why overload methods?

Overloading in Action: Calculating Area

Let’s look at a practical example: calculating the area of different shapes using overloaded methods.

Method 1: Area of a Square

public static double calculateArea(double side) {
    return side * side;
}

Method 2: Area of a Rectangle

public static double calculateArea(double length, double width) {
    return length * width;
}

Method 3: Area of a Circle

public static double calculateArea(double radius, boolean isCircle) {
    if (isCircle) {
        return Math.PI * radius * radius;
    } else {
        return -1; // Invalid input
    }
}

Putting It Together: Full Example

public class AreaOverload {

    // Square
    public static double calculateArea(double side) {
        return side * side;
    }

    // Rectangle
    public static double calculateArea(double length, double width) {
        return length * width;
    }

    // Circle
    public static double calculateArea(double radius, boolean isCircle) {
        if (isCircle) {
            return Math.PI * radius * radius;
        } else {
            return -1;
        }
    }

    public static void main(String[] args) {
        System.out.println("Area of square (5): " + calculateArea(5));
        System.out.println("Area of rectangle (4, 6): " + calculateArea(4, 6));
        System.out.println("Area of circle (radius 3.0): " + calculateArea(3.0, true));
    }
}

Output:

Area of square (5): 25.0  
Area of rectangle (4, 6): 24.0  
Area of circle (radius 3.0): 28.274333882308138

How Does Java Know Which Method to Call?

Java determines which overloaded method to execute using method signature, which includes:

At compile time, Java checks the arguments you pass and chooses the method whose parameters match best.

Examples:

Rules of Overloading

Invalid Example (doesn't compile):

public static int example() { return 1; }
public static double example() { return 2.0; } // ❌ Error: duplicate method

Benefits of Method Overloading

Improves readability

Using the same method name for similar operations makes code easier to understand.

Enhances reusability

You can handle multiple input variations without rewriting code.

Simplifies interfaces

Users of your method don’t have to remember different method names for similar tasks.

Index

3.4 The main Method Explained

Every Java program begins execution from a special method called the main method. This method acts as the entry point — the place where the program starts running.

If your class doesn't have a correctly defined main method, the Java Virtual Machine (JVM) won’t know where to begin, and your program won’t run.

The Full Syntax

public static void main(String[] args)

Let’s break down each part of this line:

public

This is an access modifier. It means the main method is accessible from anywhere, including by the JVM when the program starts.

static

This means the method belongs to the class rather than to any specific object. Since the JVM needs to call this method before any objects exist, main must be static.

void

This indicates that the method does not return a value. The main method simply starts the program — it doesn't give back a result.

main

This is the name of the method. It must be spelled exactly like this — lowercase main — because the JVM looks for it when launching a program.

String[] args

This is an array of Strings. It holds any command-line arguments passed when the program is run. If you don’t provide any, the array is simply empty.

Example: Printing Command-Line Arguments

Here’s a simple program that prints whatever arguments you pass to it:

public class CommandLineDemo {

    public static void main(String[] args) {
        System.out.println("Arguments received:");

        for (int i = 0; i < args.length; i++) {
            System.out.println("Arg " + i + ": " + args[i]);
        }
    }
}

How to Run:

If you compile and run the program from a command line:

java CommandLineDemo Hello 123 Java

Output:

Arguments received:
Arg 0: Hello
Arg 1: 123
Arg 2: Java

Whats Happening?

Why Is the main Method Crucial?

Can You Have Other Methods Too?

Yes! In addition to the main method, you can define and use other methods to organize your code and avoid repetition.

public class Welcome {

    public static void printGreeting() {
        System.out.println("Welcome to Java!");
    }

    public static void main(String[] args) {
        printGreeting(); // Call to another method
    }
}
Index