Skip to content

Latest commit

 

History

History
85 lines (62 loc) · 2.56 KB

File metadata and controls

85 lines (62 loc) · 2.56 KB

Methods

In this lesson, we will learn about methods in Java. Methods are like little helpers that do specific tasks in your program. They make your code easier to read and manage. Let's dive in!

Defining Methods

A method is a block of code that performs a specific task. Here's how you define a method in Java:

public class Main {
    // This is a method
    public static void sayHello() {
        System.out.println("Hello, World!");
    }

    public static void main(String[] args) {
        // Calling the method
        sayHello();
    }
}

In this example, sayHello is a method that prints "Hello, World!" to the screen. We call this method inside the main method to execute it.

Method Parameters and Return Values

Methods can take inputs, called parameters, and can also return a value. Here's an example:

public class Main {
    // Method with parameters
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Method that returns a value
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        // Calling the method with a parameter
        greet("Alice");

        // Calling the method that returns a value
        int sum = add(5, 3);
        System.out.println("The sum is: " + sum);
    }
}

In this example, greet takes a String parameter called name and prints a greeting. The add method takes two int parameters and returns their sum.

Overloading Methods

You can have multiple methods with the same name but different parameters. This is called method overloading. Here's an example:

public class Main {
    // Overloaded methods
    public static void printNumber(int number) {
        System.out.println("Number: " + number);
    }

    public static void printNumber(double number) {
        System.out.println("Number: " + number);
    }

    public static void main(String[] args) {
        // Calling overloaded methods
        printNumber(5);
        printNumber(5.5);
    }
}

In this example, there are two printNumber methods: one that takes an int and one that takes a double. Java knows which one to call based on the type of the argument.

Summary

Methods are essential for organizing your code and making it reusable. You can define methods to perform specific tasks, pass parameters to them, and even return values. Method overloading allows you to have multiple methods with the same name but different parameters.

Navigation

<< Previous | Home | Next >>