How To Do

[Explained] How to Call a Method in Java

A way in Java is nothing however a reusable piece of code that may be executed on demand.

Methods are sometimes known as features, and you’ll discover that each phrases are used interchangeably.

Importance of Using Methods or Functions

Software builders remedy a downside by breaking it down into smaller issues and fixing them in order to remedy the issue as a entire. This concept led to what’s often known as modular structure. In this method, builders break down code into items that may be moved round and executed to remedy a larger downside.

Methods are advantageous as a result of they’re usable at completely different situations in the whole software. Let’s say you need to create a utility technique to take away all pointless whitespaces from a sentence. Will it make sense to write the logic each time you want it someplace in your software?

Or does it make sense to create a technique one time after which use the identical technique with completely different inputs at a number of locations in your software? The latter is clearly higher and extra environment friendly.

Not solely that, with the assistance of entry modifiers in Java, you’ll be able to even management which strategies are literally shareable throughout the appliance and which ones are usually not. It additionally helps make your code look extra readable, organized, and structured.

Types of Methods in Java

There are two varieties of strategies in Java: user-defined & pre-defined strategies. User-defined strategies, because the title suggests, are outlined explicitly by the programmer. An instance of a user-defined technique may be:

public int sum(int a, int b) {
    return a + b;
}

On the opposite hand, pre-defined strategies or built-in strategies are already current as a a part of the Java programming language. An instance of a built-in technique may be:

String textual content = "Hello World";
textual content.toLowerCase();

Here, toLowerCase is a built-in Java technique that may be known as from anyplace in your code.

Structure of a Method in Java

Let’s have a have a look at the perfect construction of a technique in Java:

[access_modifier] [return_type] method_name(...parameters) {
    // technique physique
}

These parts of a technique have to be specified in order. For instance, the tactic can’t be outlined earlier than the return kind and likewise. Let’s know the features of every of those parts constituting a technique and the way they work collectively.

#1. Access Modifier

In Java, entry modifiers are key phrases that outline the visibility of a technique, class, interface, variable, and many others. Technically, there are 5 entry modifiers in Java:

  • public: accessible to all lessons
  • personal: solely accessible to the category to which it belongs
  • default: the default entry modifier is comparable to the protected modifier in which the tactic is accessible solely inside the identical bundle
  • protected: accessible inside subclasses or a specific bundle
public int sum(a int, b int) {
    return a + b;
}

Here, the calc technique has the entry modifier as public, and thus it is going to be accessible from in every single place.

#2. Return Type

The return kind of a perform defines the information kind of the information that the perform goes to return. If you don’t need to return something from a perform, specify the void return kind in that case. The return key phrase can’t be used when a void kind is specified. Specifying the return kind is a should in order to outline a perform.

public void log(String textual content) {
    System.out.println(textual content);
}

The above technique isn’t returning something; it’s simply printing textual content to the console. And thus, the void return kind.

#3. Method Name

It identifies a technique in a class and is used to invoke the tactic from an object.

class Print {
    void log(String textual content) {
        System.out.println(textual content);
    }
}

Print p = new Print();
p.log("hello world"); // outputs "hello world"

#4. Parameters

You can move arguments to strategies in accordance to the parameters outlined in it. For instance, if there are two parameters outlined for a technique, then you’ll be able to solely move two arguments with corresponding information sorts. And you have to move the arguments in the order they’re outlined.

class Calc {
    int sum(a int, b int) {
        return a + b;
     }
}

Calc cal = new Calc();
cal.sum(3, 7); // will return 10

#5. Body

The technique physique contains the programming logic used to return a specific end result. It performs the perform which the tactic is meant to do. It is enclosed in curly braces and is usually referred to as a block of code.

class Calc {
    int sum(a int, b int) {
        return a + b;
     }
}

Here, the return assertion contained in the curly braces is the physique of the tactic sum.

Calling Methods in Java

Invoking strategies in Java is kind of easy. You can name a technique by its title from an occasion of the category it lives in.

Static strategies may be invoked with out an object occasion of the category in which it’s current. Non-static strategies have to be strictly invoked from an occasion of a class, in different phrases, from an object.

For static strategies, the invocation seems like this:

class Math {
    public static int sum(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void foremost(String[] args) {
        int add = Math.sum(5, 2);
        System.out.println(add);
    }
}

In the above code, the sum technique contained in the Math class is a static technique. And that’s the rationale why you don’t want to create an object (occasion) of Math class, you solely want to invoke the tactic from the category itself.

On the flip aspect, for non-static strategies, the invocation seems like this:

class Math {
    public int sum(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void foremost(String[] args) {
        int add = new Math().sum(5, 2);
        System.out.println(add);
    }
}

Here, you might be creating a new object from the Math class after which invoking the tactic sum. The cause behind that is that non-static strategies are usually not instantiated till the category is instantiated.

That’s how one can name a technique in Java.

Final Words

Not simply in Java however in any programming language, strategies are a smart way to set up your code and reuse them in a number of locations. Methods are the constructing blocks of modular and component-based structure.

If you might be into Java, be taught extra about exception dealing with in Java.

Vikash Gorayan

Vikash Gorayan is a technology enthusiast with a passion for gadgets and product management. He is constantly seeking new opportunities to learn and grow in his field.

Related Articles

Leave a Reply

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

Back to top button