Java Part 5: Methods In Java

Java Part 5: Methods in Java


Please Subscribe Youtube| Like Facebook | Follow Twitter

Methods in Java

In this article, we will provide a detailed overview of Methods in Java and provide examples of how they are used in Java programming.

In Java, methods are essential building blocks of a program, allowing developers to write reusable code and break down complex logic into smaller, more manageable pieces. Thus in this article we’ll explore the concepts of methods in Java, and how they’re used in programming. We’ll also provide plenty of examples with complete code and output to help you understand the concepts better.

Functions vs. Methods in Java

In Java, functions and methods are essentially the same thing: a block of code that can be called from other parts of the program. However, the term “method” is often used to refer specifically to functions that are associated with a class or object, while the term “function” is sometimes used more generally to refer to any block of code that performs a specific task.

So while the syntax and usage of functions and methods are the same in Java, some programmers may use the terms interchangeably or prefer one term over the other based on their background or personal preference.

Method Syntax:

[access_modifier] [static] [final] [return_type] method_name([parameter_list]) {
    // code block
    return [value];
}

[access_modifier]: specifies the visibility of the method to other classes. Examples of access modifiers in Java include public, private, protected, and the default modifier.
[static]: indicates that the method belongs to the class itself, rather than to an instance of the class. Static methods can be called without creating an object of the class.
[final]: indicates that the method cannot be overridden by subclasses.
[return_type]: specifies the type of data that the method returns. If the method doesn’t return anything, use the void keyword.


method_name: the name of the method. This should be a descriptive name that indicates what the method does.
[parameter_list]: a list of parameters that the method takes in. Each parameter should include its data type and a name.
// code block: the body of the method, where the actual logic of the method is written.
return [value]: returns the output of the method. If the method doesn’t return anything, this line can be omitted.

Types of Methods in Java

Java supports two types of methods:

  1. Built-in Methods
  2. User-Defined Methods

Built-in Methods

Built-in methods are already defined in Java, and can be used directly in your code. It comes with a number of built-in Methods that are readily available for use in any Java program. These Methods include things like System.out.println(), Math.random(), String.length(), Array.sort() and Date.getTime() among many others.

User-Defined Methods

User-defined methods are created by the developer and can be used in the same way as built-in methods. In Java, you can define your own methods to perform specific tasks. These are called user-defined Methods or methods. You can define a method in Java using the public static keywords followed by the return type of the method, the name of the method, and the parameters it accepts.

Example of a Method in Java

public class MyClass {
    public int multiply(int a, int b) {
        return a * b;
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        int result = obj.multiply(2, 3);
        System.out.println("The result is: " + result);
    }
}

Output

The result is: 5

In this example, we have defined a class called MyClass that contains a method called multiply. This method takes two integer parameters and returns their product. We create an instance of the MyClass class using the new keyword, and then we call the multiply method on that instance using the syntax obj.multiply(2, 3) and store the result in a variable called result.

Example Method in Java with no return type and no parameters

public class MyClass {
    public void sayHello() {
        System.out.println("Hello, world!");
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.sayHello();
    }
}

Output

Hello, world!

Passing Parameters to a Method in java

You can pass parameters to a Method in java using two methods:

  1. Pass-by-Value
  2. Pass-by-Reference

Pass-by-Value

In Java, the default method of passing parameters to a method is by value. This means that when you pass a primitive data type (such as int, float, boolean, etc.) or a reference to an object to a method, a copy of that value is passed to the method.

Here is an example of a Java method that takes an integer parameter and increments its value by one

public static int addOne(int num) {
    num++;
    return num;
}

When calling this method, the value of num variable is copied and passed to the method, and any changes made to the value inside the method do not affect the original value outside the method.

int num = 5;
System.out.println(addOne(num)); // Output: 6
System.out.println(num); // Output: 5

Output

6
5

In the above example, we have defined a method addOne() that takes a parameter num. The method adds 1 to the parameter and returns it. We have also defined a variable num and assigned the value 5 to it. We then call the method addOne() and pass num as an argument. The method returns 6, but the value of num remains 5.

Pass-by-Reference

In Java, you can also pass parameters to a method by reference, using the & operator. When a parameter is passed by reference, a reference to the variable is passed to the method, rather than a copy of its value. This allows the method to modify the original value of the variable.

However, it’s important to note that Java does not have a true pass-by-reference mechanism. Instead, pass-by-reference in Java is implemented by passing the reference to the object that holds the value of the variable.

Here’s an example method that takes an integer parameter by reference:

public static void incrementByOne(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        arr[i]++;
    }
}

This method takes an array of integers as a parameter, and increments each element of the array by one. When calling this method, we pass an array of integers to the method.

int[] numbers = {1, 2, 3, 4, 5};
incrementByOne(numbers); // numbers is passed by reference to the incrementByOne() method
for (int num : numbers) {
    System.out.print(num + " "); // Output: 2 3 4 5 6
}

Output

2 3 4 5 6

In this example, the incrementByOne method takes an array of integers as a parameter by reference. When the method modifies the elements of the array, it is actually modifying the original array outside the method. This is because the array is passed by reference to the method, rather than by value.

Note that in Java, you cannot pass primitive data types (such as int, float, boolean, etc.) by reference. Instead, you can pass an object that holds the value of the variable by reference, or use wrapper classes (such as Integer, Float, Boolean, etc.) that can be passed by reference.

Conclusion

In conclusion, methods are essential building blocks in Java and other object-oriented programming languages. They allow us to write modular, reusable code that can be easily maintained and scaled. By breaking down complex tasks into smaller, more manageable methods, we can create more organized and efficient code. Understanding the syntax and best practices for creating methods is a fundamental skill for any Java programmer. With practice and experience, you can become proficient in designing and implementing effective methods that make your programs more robust and flexible.

Java Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *