Introduction to Methods: Defining, Calling, void

Learn Java methods: how to define, call, and use void methods with examples. Day 11 Java tutorial for beginners.
Introduction to Methods: Defining, Calling, void

On Day 11, we learn about methods. Methods in Java are blocks of code designed to perform specific tasks. Instead of repeating code, we can write a method once and call it whenever needed. This improves code readability and reusability.

1. Defining a Method


public class MethodExample {
    // method definition
    static void greet() {
        System.out.println("Hello, welcome to Java!");
    }

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

Explanation: The method greet() is defined using static void. It prints a message and can be called multiple times.

2. void vs return methods

void means the method does not return any value. If we want a method to return something, we use a return type like int or String.


public class ReturnMethodExample {
    // void method
    static void sayHello() {
        System.out.println("Hello from void method!");
    }

    // method with return type
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        sayHello(); // calling void method

        int sum = add(5, 10); // calling return method
        System.out.println("Sum: " + sum);
    }
}

Explanation: sayHello() prints directly. add() returns the sum of two numbers, which we store in a variable and print.

3. Why use Methods?

  • Avoids code repetition
  • Makes programs easier to read
  • Helps in breaking large programs into smaller tasks

Summary

Methods are reusable code blocks. void methods perform an action without returning data, while other methods can return values for further use.

إرسال تعليق