Functions in Java

Functions (or methods) in Java are blocks of reusable code that perform specific tasks. They help in organizing and reusing code efficiently. In this tutorial, we’ll cover how to create and use functions in Java.

Declaring a Function

Functions in Java must be declared inside a class. Here's a basic example:

public class Main {
        // Function declaration
        public static void sayHello() {
            System.out.println("Hello, World!");
        }

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

Functions with Parameters

Functions can accept parameters to perform specific tasks:

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

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

Functions with Return Values

Functions can return values using the return statement:

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

        public static void main(String[] args) {
            int result = add(5, 3);
            System.out.println("The sum is: " + result); // Output: The sum is: 8
        }
    }

Overloading Functions

Java supports function overloading, which allows you to define multiple functions with the same name but different parameters:

public class Main {
        public static void greet() {
            System.out.println("Hello!");
        }

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

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

Next Steps

Practice creating functions with different parameters and return types. Functions are essential for writing clean and reusable Java code. With these functions you can learn about object orientated programming!