Methods in Java: Syntax, Types and Examples

A method in Java is a named block of code defined inside a class that performs a specific task and executes only when called. It has an access modifier, a return type, a name, and optional parameters. Methods let you write logic once and reuse it anywhere, keeping Java programs organised and easy to maintain.

Key Takeaways

  • A method in Java must be declared inside a class, unlike a standalone function in C or Python.
  • Every method has a return type, a name, and an optional list of parameters, collectively called its method signature.
  • Java has two broad categories: predefined methods (built into the Java API) and user-defined methods (written by you).
  • You call a method using its name followed by parentheses, passing any required arguments.
  • Strong method design is a foundational skill for ethical hacking, secure coding, and backend development alike.

What a Method Is

In Java, a method in Java is a self-contained unit of code defined inside a class. When your program needs to do something, say calculate a student’s percentage or validate a login credential, you write that logic inside a method and call it wherever you need it. This is the write-once, use-anywhere principle that makes Java so maintainable at scale.

Think of a method like a vending machine. You press a button (the method call), the machine runs its internal process, and it gives you back a result (the return value). You do not care how the machine works inside; you just use it. That abstraction is exactly what methods in Java provide.

Methods vs Functions in Java

This trips up a lot of beginners. In languages like C or Python, a function can exist on its own, outside any class. In Java, that is not allowed. Every block of reusable code must live inside a class, which means Java technically has methods, not standalone functions. The terms methods and functions in Java are often used interchangeably in casual conversation, but the distinction matters in interviews and in practice.

According to the Oracle Java documentation, a method is a member of a class or object, and its behaviour is tied to that class. That object-oriented constraint is what separates Java from procedural languages. If you are coming from C, our guide on how to write, compile and run a C program shows exactly how that structural difference plays out in practice.

Why Methods in Java Matter in Real Projects

The Stack Overflow Developer Survey 2024 ranked Java among the top five most-used programming languages globally, with roughly 30% of professional developers working with it regularly. At that scale, unorganised code without well-structured methods in Java becomes unmaintainable within weeks. According to the TIOBE Index (June 2025), Java is the second most popular programming language in the world, which means Java method concepts appear in thousands of technical interviews every month across India’s IT sector. A 2023 Naukri.com report found over 1.2 lakh active Java developer job listings in India at any given time, making method design one of the most tested skills in campus placements at TCS, Wipro and Accenture. Senior developers at product companies like Flipkart or Razorpay will reject a pull request if a single method is doing more than one job. That is the real-world standard you are aiming for.

Method Syntax in Java

The java method syntax follows a fixed pattern. Getting this right is non-negotiable because the Java compiler is strict: one missing keyword and your program will not compile. Here is the complete structure of a method declaration in Java, broken down piece by piece.

The Full Syntax

The syntax for a method in Java looks like this:

accessModifier returnType methodName(parameterType parameterName) {
    // method body
    return value;
}

A concrete java method example using that structure:

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

Anatomy of a Method Declaration in Java

Every part of the method declaration in Java has a job. The table below breaks down each component so you can read or write any method signature confidently.

Component Example What It Does
Access Modifier public, private, protected Controls which classes can call this method
Return Type int, String, void Declares what kind of value the method sends back; void means nothing is returned
Method Name addNumbers The identifier you use to call the method; use camelCase by Java convention
Parameters int a, int b Input values the method needs to do its work; optional
Method Body { return a + b; } The actual logic executed when the method runs
Return Statement return a + b; Sends the result back to the caller; required unless return type is void

How to Declare a Method in Java: Practical Tips

When you write methods in Java, name them with a verb that describes what they do: calculateTax(), validateEmail(), fetchUserData(). A common beginner mistake is naming methods like variables, for example result() or data(), which tells the next developer nothing about what the method does.

Another mistake: writing methods that are 80 lines long. If your method body scrolls off the screen, it is almost certainly doing too many things. Break it into smaller, focused methods. This is not just good style; it directly affects how easy it is to handle Java exceptions and common runtime errors, because smaller methods isolate where a bug can actually occur.

Types of Methods in Java

Java methods fall into two main categories, and understanding both is essential for any interview or real project.

Predefined Methods

Predefined methods are part of the Java standard library, the vast collection of classes and methods Oracle ships with every Java installation. You do not write them; you just call them. Examples include Math.sqrt(), System.out.println(), and String.length(). These methods have already been written, tested and optimised by the Java team, so use them whenever they fit your need rather than reinventing them.

User-Defined Methods in Java

User-defined methods in Java are the ones you write yourself. This is where most of your actual programming work happens. Within user-defined methods, there are two important sub-types you will encounter constantly:

  • Static methods: Belong to the class itself, not to any particular object. You call them using the class name: ClassName.methodName(). The main method is always static.
  • Instance methods: Belong to an object of the class. You must create an object first, then call the method on it: myObject.methodName(). These can access instance variables directly.

Static vs Instance Methods in Java: Quick Comparison

Feature Static Method Instance Method
Belongs to The class An object (instance)
How to call ClassName.method() object.method()
Can access instance variables? No Yes
Common use case Utility functions, main method Business logic tied to object state
Example Math.abs(-5) student.getMarks()

If you are planning a career in full stack developer vs software developer roles, knowing when to use static versus instance methods is one of those things that separates junior from mid-level developers in code reviews.

Calling Methods in Java

Defining a method does nothing on its own. You have to call it, and that is where the function call in Java comes in. The way you call a method depends on whether it is static or an instance method.

Calling a Static Method

public class Calculator {
    public static int addNumbers(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = Calculator.addNumbers(10, 20);
        System.out.println(result); // Output: 30
    }
}

Because addNumbers is static, you call it using the class name. Inside the same class, you can also call it without the class name prefix: just addNumbers(10, 20). Both work.

Calling an Instance Method

public class Student {
    String name;

    public void displayName() {
        System.out.println("Student: " + name);
    }

    public static void main(String[] args) {
        Student s = new Student();
        s.name = "Priya";
        s.displayName(); // Output: Student: Priya
    }
}

Here, displayName() is an instance method. You create a Student object first, then call the method on that object. This is the pattern you will use most often in real applications, where each object holds its own data.

Passing Arguments and Receiving Return Values

When you call a method, the values you pass in are called arguments. Inside the method, they are received as parameters. Java is pass-by-value, meaning the method gets a copy of the data, not the original variable. This is a classic interview question, and getting it wrong is one of the most common mistakes candidates make at campus placements for companies like TCS, Wipro and Accenture.

If you are building the kind of broad programming foundation that opens doors to roles in cybersecurity or AI, it is worth exploring the software development tools to learn first alongside Java fundamentals. Knowing your tools as well as your language is what makes you productive from day one.

Students pursuing a BSc Computer Science subjects and scope or looking at jobs and salary after MCA will cover Java methods in Java extensively in their core programming modules. Getting comfortable with method calls early means the rest of object-oriented programming clicks much faster.

What to do this week:

  1. Write five user-defined methods of your own: at least two static, two instance, and one that takes parameters and returns a value. Run them in a single main method.
  2. Read through the Java Math class documentation on Oracle’s site and call at least three predefined methods you have not used before.
  3. If you are serious about building a career in tech, explore 3.0 University online certification courses in Cybersecurity, Ethical Hacking, AI, and Blockchain. Java programming is the foundation for secure coding, penetration testing scripts and smart contract development. The CEH v13 AI online course is a strong next step once your fundamentals are solid.

Frequently Asked Questions

What is a method in Java?

A method in Java is a named block of code defined inside a class that performs a specific task and runs only when called. It has a return type, a name, and optional parameters. Methods in Java allow you to reuse logic without rewriting it, which keeps your programs organised and easier to maintain.

What is the syntax of a method in Java?

The method syntax in Java is: accessModifier returnType methodName(parameterType parameterName) { // body }. For example, public int addNumbers(int a, int b) { return a + b; }. The access modifier controls visibility, the return type states what value comes back, and the parameters are the inputs the method needs.

What are the types of methods in Java?

Java has two main types: predefined methods (built into the Java API, like Math.sqrt() or String.length()) and user-defined methods (written by the programmer). User-defined methods in Java are further divided into static methods, which belong to the class, and instance methods, which belong to an object of the class.

What is the difference between methods and functions in Java?

In Java, all reusable code blocks are called methods because they must be defined inside a class. A standalone function that exists outside any class is not possible in Java, unlike in C or Python. The terms are often used interchangeably in conversation, but technically Java has methods, not functions.

How do I call a method in Java?

To call a static method, use ClassName.methodName(arguments). To call an instance method, first create an object of the class using new, then call object.methodName(arguments). If you are calling a method from within the same class, you can use just the method name and arguments directly.

What is method overloading in Java?

Method overloading in Java means defining multiple methods with the same name but different parameter lists within the same class. Java decides which version to call based on the number and type of arguments you pass. For example, you can have add(int a, int b) and add(double a, double b) as two separate overloaded methods in Java.

What is a void method in Java?

A void method in Java is a method whose return type is declared as void, meaning it performs an action but does not send any value back to the caller. System.out.println() is the most common example. You use void methods in Java when the goal is to do something, like print output or update a variable, rather than calculate and return a result.

Can a Java method return multiple values?

A method in Java can only return one value directly. To return multiple values, you can return an array, a List, or a custom object that holds all the values you need. This is a common pattern in real Java projects where a method needs to send back, for example, both a status code and a message to the caller.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles