Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: August 17, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

A method in Java is nothing but a reusable piece of code that can be executed on demand.

Methods are often called functions, and you will notice that both words are used interchangeably.

Importance of Using Methods or Functions

Software developers solve a problem by breaking it down into smaller problems and solving them in order to solve the problem as a whole. This idea led to what’s known as modular architecture. In this approach, developers break down code into pieces that can be moved around and executed to solve a bigger problem.

Methods are advantageous because they are usable at different instances in the entire application. Let’s say you want to create a utility method to remove all unnecessary whitespaces from a sentence. Will it make sense to write the logic every time you need it somewhere in your application?

Or does it make sense to create a method one time and then use the same method with different inputs at multiple places in your application? The latter is obviously better and more efficient.

Not only that, with the help of access modifiers in Java, you can even control which methods are actually shareable across the application and which of them are not. It also helps make your code look more readable, organized, and structured.

Types of Methods in Java

There are two types of methods in Java: user-defined & pre-defined methods. User-defined methods, as the name suggests, are defined explicitly by the programmer. An example of a user-defined method can be:

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

On the other hand, pre-defined methods or built-in methods are already existing as a part of the Java programming language. An example of a built-in method can be:

String text = "Hello World";
text.toLowerCase();

Here, toLowerCase is a built-in Java method that can be called from anywhere in your code.

Structure of a Method in Java

Let’s have a look at the ideal structure of a method in Java:

[access_modifier] [return_type] method_name(...parameters) {
    // method body
}

These components of a method have to be specified in order. For example, the method cannot be defined before the return type and likewise. Let’s know the functions of each of these components constituting a method and how they work together.

#1. Access Modifier

In Java, access modifiers are keywords that define the visibility of a method, class, interface, variable, etc. Technically, there are five access modifiers in Java:

  • public: accessible to all classes
  • private: only accessible to the class to which it belongs
  • default: the default access modifier is similar to the protected modifier in which the method is accessible only inside the same package
  • protected: accessible within subclasses or a particular package
public int sum(a int, b int) {
    return a + b;
}

Here, the calc method has the access modifier as public, and thus it will be accessible from everywhere.

#2. Return Type

The return type of a function defines the data type of the data that the function is going to return. If you don’t want to return anything from a function, specify the void return type in that case. The return keyword can’t be used when a void type is specified. Specifying the return type is a must in order to define a function.

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

The above method isn’t returning anything; it’s just printing text to the console. And thus, the void return type.

#3. Method Name

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

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

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

#4. Parameters

You can pass arguments to methods according to the parameters defined in it. For example, if there are two parameters defined for a method, then you can only pass two arguments with corresponding data types. And you must pass the arguments in the order they are defined.

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 method body includes the programming logic used to return a particular result. It performs the function which the method is supposed to do. It is enclosed in curly braces and is often referred to as a block of code.

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

Here, the return statement inside the curly braces is the body of the method sum.

Calling Methods in Java

Invoking methods in Java is quite simple. You can call a method by its name from an instance of the class it lives in.

Static methods can be invoked without an object instance of the class in which it is present. Non-static methods have to be strictly invoked from an instance of a class, in other words, from an object.

For static methods, the invocation looks like this:

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

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

In the above code, the sum method inside the Math class is a static method. And that’s the reason why you don’t need to create an object (instance) of Math class, you only need to invoke the method from the class itself.

On the flip side, for non-static methods, the invocation looks like this:

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

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

Here, you are creating a new object from the Math class and then invoking the method sum. The reason behind this is that non-static methods are not instantiated until the class is instantiated.

That’s how you can call a method in Java.

Final Words

Not just in Java but in any programming language, methods are a great way to organize your code and reuse them in multiple places. Methods are the building blocks of modular and component-based architecture.

If you are into Java, learn more about exception handling in Java.

  • Murtuza Surti
    Author
    Software Engineer & Content Creator
  • Rashmi Sharma
    Editor

    Rashmi has over 7 years of expertise in content management, SEO, and data research, making her a highly experienced professional. She has a solid academic background and has done her bachelor’s and master’s degree in computer applications…. read more

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder