Day 4: Methods in Java

Day 4: Methods in Java

Jun 24, 2023ยท

4 min read

Play this article

Java methods are blocks of code that perform a specific action. They are used to organize your code into reusable blocks and make it more readable and maintainable. In this tutorial, we'll cover everything you need to know about methods in Java, including:

  1. Defining a method

  2. Calling a method

  3. Method parameters

  4. Return values

  5. Method overloading

  6. Recursion

  7. Scope of variables

Defining a Method

You define a method in Java using the keyword def followed by the method name and parentheses (). Inside the parentheses, you can pass parameters which are variables that provide input to the method. The method body is enclosed in curly brackets {} with the statements that define what the method does.

For example:

public void sayHello() {
    System.out.println("Hello!");
}

This is a basic method that prints "Hello!". It has no parameters and does not return a value. The void keyword indicates the method does not return a value.

Calling a Method

To call or execute a method, simply write the name of the method followed by parentheses with any required parameters. For example:

sayHello(); // Calls the sayHello method

When a method is called, the code inside its body is executed. Calling a method multiple times will execute its body again on each invocation.

Method Parameters

Parameters are variables that act as inputs to a method. They are defined inside the parentheses of a method. For example:

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

This method has a String parameter named name. When we call the method, we pass an argument (an actual value) for the parameter:

sayHello("John"); // Prints "Hello John!"
sayHello("Mary"); // Prints "Hello Mary!"

We can have multiple parameters separated by commas. Parameters have the following attributes:

  • Type - The parameter type like String, int, boolean, etc. This determines what kind of values can be passed for that parameter.

  • Name - The name used to reference the parameter in the method body. Best practice is to use meaningful names.

  • Default value - Parameters can have default values specified using =. For example, int age = 30. If no argument is passed for that parameter, it will take the default value.

Return Values

When a method finishes its execution, it can return a value. To return a value from a method, you use the return keyword followed by the value you want to return. For example:

public int multiply(int x, int y) {
    return x * y;
}

This method takes two numbers x and y and returns their product. You call the method like this:

int result = multiply(2, 5); // Returns 10

A method can only have one return statement. Once a return statement is executed, the method ends its execution. A method that returns a value must have its return type declared in the method definition. The return type is written before the method name, for example, void, int, boolean, String, etc.

Method Overloading

Method overloading means having two or more methods with the same name but different parameters. The compiler distinguishes between the methods based on the parameters. Some rules for method overloading:

  • The methods must have different parameters (different numbers of parameters or different data types of parameters)

  • The methods can have the same return type or different return types

  • The access modifiers can be the same or different

  • The overload method cannot be ambiguous i.e. the compiler must be able to uniquely resolve which overloaded method to call based on the arguments.

Here's an example of method overloading:

public void print(int x) {
    System.out.println(x);
}

public void print(String s) {
    System.out.println(s);
}

public void print(int x, String s) {
    System.out.println(x + " " + s);
}

We have 3 overloaded print methods. We can call them like this:

print(5); // Prints 5 (Calls print(int))
print("Hello"); // Prints Hello (Calls print(String))
print(2, "World"); // Prints 2 World (Calls print(int, String))

The compiler determines which print method to call based on the parameters passed. Method overloading allows you to have multiple methods with the same name, making the API simpler and easy to use.

Scope of Variables

The scope of a variable refers to the region in a program where that variable is accessible. Java has block scope and method scope:

  • Block scope: Variables defined within a block {...} can only be accessed within that block. For example:
{
    int x = 5;
// x is accessible here
}
// x is not accessible here
  • Method scope: Variables defined within a method are accessible anywhere within that method. For example:
public void method() {
    int x = 5;

    {
    // x is accessible here
    }
    // x is also accessible here
}
  • Parameters also have method scope. They are only accessible within the method that defines them.

In summary, methods allow you to organize your Java code into reusable sections. They make your code more readable, writeable, and maintainable using parameters, return values, and overloading.

Did you find this article valuable?

Support Laxman Rai by becoming a sponsor. Any amount is appreciated!

ย