In programming, as your applications grow larger and more complex, you'll find yourself writing code that performs similar tasks multiple times. Copying and pasting code leads to messy, hard-to-maintain programs. This is where methods (also known as functions or subroutines in other programming languages) come in.

A method is a block of code that performs a specific task. Think of it as a mini-program within your main program. Once defined, a method can be called (or invoked) multiple times from different parts of your code, making your programs:

  • Modular: Break down complex problems into smaller, manageable pieces.

  • Reusable: Write a piece of code once and use it many times.

  • Readable: Organize your code logically, making it easier to understand.

  • Maintainable: Changes or bug fixes only need to be applied in one place (the method definition).

In Java, all methods are part of a class. Let's dive into how to define and use them.

Defining a Method: The Blueprint

Every method has a blueprint, or signature, that tells the Java compiler about its characteristics.

Basic Syntax:

access_modifier static_keyword? return_type methodName(parameter1, parameter2, ...) {
    // Body of the method - code to be executed
    // (Optional) return value;
}

Let's break down each part of this signature:

  • access_modifier: Controls the visibility of the method. Common modifiers include:

    • public: Accessible from anywhere.

    • private: Accessible only within the class it's defined in.

    • protected: Accessible within the same package and by subclasses.

    • (No modifier / default): Accessible only within the same package.

    • For now, we'll primarily use public.

  • static_keyword?: The static keyword is optional. A static method belongs to the class itself, rather than to any specific object of that class. You can call a static method directly using the class name (e.g., ClassName.methodName()). Non-static methods (instance methods) require an object to be created before they can be called. For introductory purposes, many of our examples will use static methods.

  • return_type: Specifies the type of data the method will send back after it finishes executing. If the method doesn't return any value, you use the keyword void. Examples: int, double, String, boolean, or a custom class type.

  • methodName: A unique identifier for the method. It should follow Java's naming conventions (camelCase, starting with a lowercase letter, descriptive).

  • parameters (optional): A comma-separated list of input values that the method accepts. Each parameter has a data type and a name (e.g., int number, String message). These parameters act as local variables within the method.

  • {} (Method Body): The curly braces enclose the actual code that the method will execute when called.

Example: A Simple Method Definition

// MyFirstMethod.java

public class MyFirstMethod {


// This is a static method named 'greet'

// It has a 'void' return type, meaning it doesn't return any value.

// It takes no parameters.

public static void greet() {

System.out.println("Hello from the greet method!");

}


public static void main(String[] args) {

// We will call the greet method here later

// For now, it just defines the method

}

}

Calling a Method: Putting it into Action

Defining a method just creates its blueprint. To actually execute the code inside a method, you need to call (or invoke) it.

To call a static method within the same class, you simply use its name followed by parentheses ():

methodName(); // For methods with no parameters
methodName(argument1, argument2); // For methods with parameters

Example: Calling a Simple Method

// CallingMethodExample.java

public class CallingMethodExample {


// A simple static method

public static void displayMessage() {

System.out.println("This message is from the displayMessage method.");

}


public static void main(String[] args) {

System.out.println("Starting main method...");


// Calling the displayMessage method

displayMessage(); // Invokes the code inside displayMessage()


System.out.println("Main method finished.");

}

}

Parameters and Arguments

Methods can accept input values, which are called parameters in the method definition and arguments when the method is called.

  • Parameters: Variables declared in the method signature that act as placeholders for the values the method expects to receive.

  • Arguments: The actual values passed to the method when it is called.

Java uses pass-by-value, meaning a copy of the argument's value is passed to the method. Changes to the parameter inside the method do not affect the original argument's value (for primitive types).

Return Values and the void Keyword

Methods can produce a result and send it back to the code that called them. This result is called the return value.

  • return_type: If a method is designed to return a value, its signature must specify the data type of that value (e.g., int, String, double).

  • return keyword: Inside the method body, the return keyword is used to send the value back. The return statement also immediately exits the method.

If a method does not return any value, its return type must be void. void methods perform actions but don't produce a result that can be used by the calling code. They do not use the return keyword unless it's to exit the method early without returning a value (e.g., return;).

Example: Methods with Parameters and Return Values

// MethodWithParamsAndReturn.java

public class MethodWithParamsAndReturn {


// This method takes two integer parameters and returns their sum.

public static int addNumbers(int num1, int num2) {

int sum = num1 + num2;

return sum; // Returns the calculated sum (an int)

}


// This method takes a String parameter and prints a personalized greeting.

// It has a 'void' return type because it doesn't return any value.

public static void printGreeting(String name) {

System.out.println("Hello, " + name + "! Welcome to Java methods.");

}


public static void main(String[] args) {

// Calling a void method with a String argument

printGreeting("Alice");

printGreeting("Bob");


// Calling a method that returns an int

int result1 = addNumbers(10, 20); // 10 and 20 are arguments

System.out.println("Sum of 10 and 20: " + result1);


// You can also use the returned value directly

System.out.println("Sum of 5 and 7: " + addNumbers(5, 7)); // 5 and 7 are arguments


int a = 15;

int b = 25;

int result2 = addNumbers(a, b); // Using variables as arguments

System.out.println("Sum of " + a + " and " + b + ": " + result2);

}

}

Method Overloading: Same Name, Different Job

Method overloading allows a class to have multiple methods with the same name, as long as their parameter lists are different. The difference can be in:

  • The number of parameters.

  • The data types of the parameters.

  • The order of the data types of the parameters.

The return type alone is not enough to overload a method. When an overloaded method is called, Java determines which version to execute based on the number and type of arguments passed.

Example: Method Overloading

// MethodOverloading.java

public class MethodOverloading {


// Method 1: Adds two integers

public static int add(int a, int b) {

System.out.println("Adding two integers:");

return a + b;

}


// Method 2: Adds three integers (different number of parameters)

public static int add(int a, int b, int c) {

System.out.println("Adding three integers:");

return a + b + c;

}


// Method 3: Adds two doubles (different data types of parameters)

public static double add(double a, double b) {

System.out.println("Adding two doubles:");

return a + b;

}


public static void main(String[] args) {

// Calls Method 1 (int, int)

int sum1 = add(5, 10);

System.out.println("Sum: " + sum1 + "\n");


// Calls Method 2 (int, int, int)

int sum2 = add(1, 2, 3);

System.out.println("Sum: " + sum2 + "\n");


// Calls Method 3 (double, double)

double sum3 = add(5.5, 10.2);

System.out.println("Sum: " + sum3 + "\n");

}

}

The main Method: Your Program's Entry Point

You've already been using a special method in all your Java programs: the public static void main(String[] args) method.

  • public: It must be public so the Java Virtual Machine (JVM) can access it.

  • static: It must be static so the JVM can call it without creating an object of the class.

  • void: It doesn't return any value.

  • main: This is the standard name recognized by the JVM as the entry point.

  • String[] args: This parameter allows the program to accept command-line arguments as an array of strings.

The JVM always starts execution from the main method. It's the starting point from which all other methods in your program are typically called, directly or indirectly.

Conclusion

Methods are the building blocks of well-structured Java programs. By mastering their definition, calling conventions, parameters, return values, and overloading, you can write code that is not only functional but also organized, reusable, and easy to maintain. This modular approach is key to developing robust and scalable applications.

Key Takeaways

  • Methods (or functions) are self-contained blocks of code designed to perform specific tasks

    • Modularity: Breaking down complex problems into smaller, manageable parts.

    • Reusability: Writing code once and calling it multiple times from different places.

    • Readability: Making your programs easier to understand and navigate.

    • void methods: Perform actions but do not produce a result that can be used by the calling code. They do not use the return keyword to send a value.

    • Methods with a return_type: Compute a value and send it back to the caller using the return keyword. The return statement also immediately exits the method.

    • Parameters are placeholders for values defined in the method signature.

    • Arguments are the actual values passed to the method when it is called.

    • Java uses pass-by-value, meaning a copy of the argument's value is passed to the method. Changes to the parameter inside the method generally don't affect the original argument.

Quiz