Table of Contents

Methods

Functions in Java, also known as methods, are essential for writing organized, reusable, and manageable code.

A function in Java is a block of code designed to perform a specific task. It's defined within a class and can take inputs, process them, and return an output. Functions help in breaking down complex problems into simpler, reusable code pieces.

Creating Our First Function

To understand functions better, let's create a simple Java class that defines and calls a method.

public class FirstMethod {

    // Defining the main method - the entry point of a Java program
    public static void main(String[] args) {
        // Creating an instance of the class to call the non-static method
        FirstMethod fm = new FirstMethod();
        fm.sayHello();
    }

    // Defining a simple method to print a message
    public void sayHello() {
        System.out.println("Hello, how are you?");
    }
}

In this example, we've defined a sayHello method that prints "Hello, how are you?" to the console. This method is called from the main method, demonstrating how methods can be executed (or called) in Java.

Key Components of a Java Method

  1. Access Modifier: Controls the visibility of the method. public means the method can be accessed from anywhere.
  2. Return Type: Specifies the type of value the method returns. void indicates the method does not return anything.
  3. Method Name: The identifier used to call the method. It follows the camelCase naming convention.
  4. Parameters: The inputs to the method, enclosed in parentheses. Parameters are optional; a method can have zero or more parameters.
  5. Method Body: Enclosed in curly braces {}, it contains the code that defines the task performed by the method.

Why Use Methods?

Methods allow for code reuse, making your programs more modular and easier to maintain. Instead of writing the same code repeatedly, you can define it once in a method and call it wherever needed.

Calling a Method in Java

To use a method, you must call (or invoke) it. This can be done from within the same class or from another class, depending on the method's access level. If the method is not static, you'll need to create an instance of the class to call it, as shown in the example above.

The main Method in Java

The main method serves as the entry point for Java applications. It follows a specific structure: