Methods in Java(With Examples)

Have you ever thought about why Java programs execute things so effectively? Or, why are methods in Java called the backbone of Java programming? If you think Java methods are just reusable blocks of code, then you might not be using them to their fullest.

Java methods are not only a way to structure your code, but they also generally define the object behavior, data flow, and even optimization. Yet most programmers, unaware, misuse or underutilize them, leading to hard-to-maintain code. In this tutorial, we’ll discuss Java methods, their types, built-in methods, best practices to follow, and real-world examples.

Table of Contents:

What Are Java Methods?

A Java method is a group of code that is used for performing some particular task. These methods allow developers to structure programs efficiently, reuse code, and modulate logic in Java programs.

In Java programming, methods define how objects interact and carry out operations. Any Java program necessarily includes at least one method, and in OOP, methods define behavior in classes.

Syntax of a Java Method

A Java method has a structured syntax format:

access_modifier return_type method_name(parameters) {
    // Method body
    return value; // Optional
}

For example:

Java

Syntax of a Java Method output

How Methods Work in Java?

  1. Method Definition: In the method definition, the desired method is declared inside a class.
  2. Method Calling: The method is then called with the help of an object (for instance, methods) or directly (for static methods).
  3. Execution: After that, the method runs and performs its task
  4. Return Statement (if any): At last, the method may return a value.

Key Components of Java Methods

A Java method is a basic building block of the Java programming that generally encapsulates a block of code to perform a specific operation. To learn how Java methods work, it is very important to break them down into their most significant components. These components determine a method’s structure, behavior, and execution sequence.

By learning these things, a beginner can easily able to write efficient, readable, and reusable code and can take advantage of Java’s object-oriented programming (OOP) concepts.

1. Method Signature

A method signature in Java is the unique identifier of a method, and it consists of:

  • Method name: The name assigned to the method.
  • Parameter list: The types of parameters it takes and how many.

Note: The return type and access modifier are not part of the method signature.

Why is a Method Signature Important?

  • They help the compiler to differentiate between methods, especially in method overloading.
  • They also ensure the correct method gets executed when called.

Example of a Method Signature:

public int add(int a, int b)  // Method signature: add(int, int)

In the above example:

  • add is the method name.
  • (int a, int b) declares the parameters.

2. Method Name

Rules for Naming Methods in Java

  • The name of methods must start with a letter, _, or $ (but by convention, start with a letter).
  • It should not be a Java keyword.
  • It should be in camelCase notation.
  • It should be meaningful and descriptive in order to indicate its purpose.

Examples of Valid and Invalid Method Names

Valid Method Names Invalid Method Names
calculateSum() 1method() (Starts with a number)
getStudentDetails() class() (class is a keyword)
findMaxValue() find max() (Spaces are not allowed)

Example Usage:

public void printMessage() {

System.out.println("Hello, Java Methods!");

}

  • printMessage is a descriptive and meaningful method name.

3. Access Modifiers

Access modifiers control the visibility of Java methods. There are four main types:

Modifier Scope & Accessibility
public Accessible from anywhere in the program.
private Accessible only within the same class.
protected Accessible within the same package and subclasses.
(default) Accessible only within the same package (no modifier needed).

Example: Using Different Access Modifiers

public class Example {

public void publicMethod() { }  // Accessible anywhere

private void privateMethod() { }  // Accessible only within this class

protected void protectedMethod() { }  // Accessible within the package and subclasses

void defaultMethod() { }  // Accessible within the package

}

4. Return Type

  • The return type of a method specifies the type of value a method will return upon execution.
  • If a method is not returning anything, then its return type should be void.

Different Return Types in Java

Return Type Description Example
int Returns an integer value. public int getNumber() { return 5; }
String Returns a string. public String getName() { return “Alice”; }
double Returns a decimal value. public double getPrice() { return 99.99; }
boolean Returns true or false. public boolean isEven(int num) { return num % 2 == 0; }
void No return value. public void showMessage() { System.out.println(“Hello!”); }

Example Usage:

public int addNumbers(int a, int b) {

return a + b;  // Returns an integer value

}

6. Method Body

The method body generally contains the logic of the method. It consists of statements that are executed when the method is called.

Example:

public void displayMessage() {

System.out.println("Java Methods are powerful!");  // Method body

}

Defining a Method in Java

A method definition is a block of code that performs some specific task. All methods in Java follow a standard form.

Syntax of Method Definition:

access_modifier return_type method_name(parameter_list) {

// Method body

return value; // If the return type is not void

}

Explanation of Components:

  • Access Modifier: Specifies the visibility (public, private, protected, or default).
  • Return Type: Specifies the data type of the value the method will return (int, String, void, etc.).
  • Method Name: Follows Java naming conventions (should be descriptive and also start with lowercase).
  • Parameter List (Optional): Defines inputs the method accepts (in parentheses).
  • Method Body: Holds the method’s actual logic within {}.
  • Return Statement (Optional): If the return type is not void, it returns a value.

Example of a Method Definition

public class Example {

// Method to calculate the sum of two numbers

public int add(int a, int b) {

int sum = a + b; // Calculate sum

return sum;      // Return the result

}

}

Method Invocation (Calling a Method) in Java

A Java method is not executed until it is explicitly called (invoked) by another method. A method call generally allows you to execute the logic of a method, which simply helps you to achieve modularity and reusability of code.

There are typically two main ways you can call a method in Java:

  1. Calling an instance method (via an object of the class).
  2. Calling a static method (on the class name directly).

Let’s go through both ways of calling methods step by step.

1. Calling an Instance Method (Using Objects)

Instance methods are typically methods of an object and require an instance of the class to invoke. That is, we must instantiate the class to invoke the method.

Steps to Call an Instance Method:

  1. Create an instance of the class.
  2. Call the method using the object reference through the dot (.) operator.

Example: Calling an Instance Method

Java

Output:

Calling an Instance Method Output

Explanation:

  • The add(int a, int b) method is an instance method.
  • We create an object calc by instantiating a new Calculator().
  • The add method gets called with calc.add(5, 10), and the return value is stored in result.

Key Point: You can’t call an instance method without an object except within the instance context of the same class.

2. Calling a Static Method (Without an Object)

A static method in Java is a member of the class, not an instance. You can call it without an object by explicitly using the class name.

Steps to Call a Static Method:

  1. Use the dot (.) operator along with the class name.
  2. Or you can call it directly within the same class without any class name.

Example: Calling a Static Method

Java

Output:

Calling a Static Method Output

Explanation:

  • square(int num) is a static declaration, which simply means that it belongs to the class.
  • We are calling it using MathUtils.square(4) directly without creating any object.

Key Point: Static methods are usually used for utility methods, such as Math.sqrt() or Integer.parseInt().

3. Calling a Method from Another Method

You can also call a method directly from another method of the same class. This simply promotes code reusability and organization.

Example:

Java

Output:

Calling a Method from Another Method

Explanation:

  • sayHello() is called in main(), and it calls displayMessage().
  • This generally shows how one method can invoke another method.

4. Calling Methods with Parameters and Return Values

Java Methods can take parameters and can also return values when called.

Example: Calling a Method with Parameters and Return Value

Java

Output:

Calling Methods with Parameters and Return Values

Explanation:

  • Here multiply(int a, int b) method typically has two parameters.
  • We are calling it with 6 and 7 as arguments.
  • The method multiplies them and stores the product in the result.

5. Calling Methods Using this Keyword

The this keyword in Java is typically used to point to the current object and is often used to differentiate between parameters and instance variables.

Example:

Java

Output:

Calling Methods Using this Keyword

Explanation:

  • The this keyword generally ensures that we are utilizing the instance variable name instead of the parameter name.

6. Calling Methods Using super Keyword (For Overridden Methods)

If a method in a subclass is overridden, the super keyword is used to call the method of the parent class.

Example:

Java

Output:

Calling Methods Using super Keyword

Explanation: super.show() invokes the show() method in the superclass(parent class), which generally prints both messages.

Types of Methods in Java

Java provides multiple types of methods in order to organize and execute code properly. It is very important to understand these types of methods for building modular, reusable, and manageable Java programs.

1. Predefined Methods (Built-in Methods)

Predefined methods are Java’s Standard Library methods (also called the Java API). They are methods that are already written in classes in the Java Development Kit (JDK), so you don’t have to write them yourself. They are time-saving and error-reducing since they give you well-tested functionality for doing standard tasks.

Common Examples and Use Cases

  • Math Operations:
    • max(a, b): It returns the larger of two values.
    • sqrt(x): It returns the square root of a number.
  • String Manipulation:
    • length(): This method gives the length of a string.
    • substring(startIndex, endIndex): Returns a substring of the string.
  • Input/Output Operations:
    • out.println(): Prints to the console.
  • Data Conversion and Parsing:
    • parseInt(String s): It converts a string to an integer.

Example Code for Demonstrating Predefined Methods

Java

Output:

Demonstrating Predefined Methods

2. User-Defined Methods

User-defined methods in Java are the type of methods that are defined by programmers in order to perform specific tasks in their program. In contrast to predefined methods, which are part of Java’s standard library, user-defined methods generally allow you to encapsulate your own logic so that your code is more modular and easier to maintain.

Defining a User-Defined Method

A typical user-defined method in Java includes:

  • Access Modifiers: They typically control the visibility of the method (e.g., public, private).
  • Return Type: It indicates the data type of the value returned by the method. Use void if the method doesn’t return any value.
  • Method Name: The name of the method should be descriptive and follow camelCase naming conventions.
  • Parameters: They can be an empty list of inputs that the method accepts in order to perform its task.
  • Method Body: They are block of code that realizes the method’s behavior.

Example Code Demonstrating a User-Defined Method

Java

Output:

Code Demonstrating a User-Defined Method

3. Static Methods

Static methods in Java belong to the class itself, not to any instance (object) of the class. This simply allows static methods to be called directly on the class name without even creating an object. They are mostly useful for utility or helper functions that perform operations independent of any object state.

Defining a Static Method

The static method in Java is simply declared using the static keyword before the return type in the declaration. It just takes the same format as an instance method except that it is prefixed by static.

Example Code Demonstrating a Static Method

Java

Output:

Code Demonstrating a Static Method

4. Instance Methods

Instance methods in Java are generally the core part of Java object-oriented programming. Unlike static methods, instance methods are typically linked to an object, as whenever you create an instance of the class, the instance methods of the class can access and modify the object’s unique data (instance variables). Instance methods generally define an object’s behavior and are the foundation for modeling real-world objects.

Defining an Instance Method

An instance method in Java is declared without the static keyword. Its signature includes an access modifier, a return type, the method name, and a parameter list. It then declares a block of code that can use the instance data of the object.

Example Code Demonstrating an Instance Method

Java

Output:

Code Demonstrating an Instance Method output

5. Abstract Methods

Abstract methods in Java are among the basic principles of Java’s object-oriented paradigm. They generally allow you to declare a method without providing its full implementation. Abstract methods are used in abstract classes and interfaces for defining a common behavior that can be implemented by different subclasses as per their requirement.

Defining an Abstract Method

An abstract method is defined with the abstract keyword and has no body. The syntax for an abstract method is:

public abstract returnType methodName(parameters);

Example Code Demonstrating Abstract Methods

Java

Output:

Code Demonstrating Abstract Methods Output

6. Factory Methods

Factory methods in Java are a design pattern that generally provide a way to encapsulate the creation of objects. Instead of directly calling a constructor, a factory method will return an object instance. Not only is object creation simplified with this method, but it also makes it simple to decouple what class instance is being returned, supporting a range of design patterns like Singleton, Factory, or Abstract Factory to be used.

Defining a Factory Method

A factory method in Java is generally a static method that returns an instance of a class. Its signature includes:

    • An appropriate access modifier (usually public).
    • A return type, which may be a concrete class, an abstract class, or an interface.
    • A method name that describes what the method performs (e.g., createInstance, getInstance, or something more descriptive).

Example Code Demonstrating a Factory Method

Java

Output: Code Demonstrating a Factory Method

 

Method Scope in Java

Method Scope in Java refers to the visibility and accessibility of methods and variables in a Java program. It generally defines where a method or a variable can be accessed and how long it is kept in memory. Why is Scope Important?

    • It helps to organize variables and methods efficiently.
    • It also prevents accidental modification of variables outside of their intended range.
    • It simply minimizes memory utilization by allocating resources only when they are required.

Types of Scope in Java

1. Local Scope (Method-Level Scope)

A variable that is declared inside a method, constructor, or block is called a local variable. These variables are present only as long as the method is running and are not visible outside the method. Example of Local Scope:

Java

Output: Local Scope Explanation:

    • The variable number is declared inside the method display().
    • It can be used only inside that method.
    • If we try to access it from main(), we will get an error because local variables cannot be accessed outside the method.

2. Instance Scope (Object-Level Scope)

Instance variables are declared in a class but outside any method. Instance variables, in contrast to local variables, are tied to an object and exist as long as the object exists. Example of Instance Scope:

Java

Output: Example of Instance Scope Explanation:

    • name is an instance variable (defined inside the class but outside any method).
    • A copy of name is given to both objects (p1 and p2).
    • The name value changes depending on the object that is using it.

3. Class Scope (Static Scope)

A static variable (declared using the static keyword) is shared by all members of a class. Unlike instance variables, there is only one copy of a static variable for the entire class. Example of Class Scope:

Java

Output: Example of Class Scope Explanation:

    • count is a static variable and belongs to the class, not to objects.
    • Every time an object is created, the count is incremented.
    • Since count is shared by all objects, it suitably keeps a tally of the total objects created.

4. Block Scope (Loop or Conditional Scope)

Block scope is given to variables defined inside loops, if-statements, or any block inside {}. These variables don’t exist outside the block and can’t be accessed externally. Example of Block Scope:

Java

Output: Example of Block Scope Explanation:

    • x is declared in the if block.
    • It can only be used in that block.
    • If we try to use x outside the block, it throws an error.

Memory Allocation for Methods and Variables in Java

In Java, variables and methods of various types are stored in various memory locations:

Type Memory Location Lifecycle
Local Variables Stack Memory Created when the method starts, destroyed when the method ends
Instance Variables Heap Memory Exists as long as the object exists
Static Variables Method Area (Class Memory) Created when class is loaded, destroyed when the program ends
Method Calls Stack Memory Stored in Stack when invoked, removed after execution

Advanced Method Concepts in Java

Java provides several complex method-related features that enhance the flexibility, readability, and efficiency of programs. The following topics are explained here in detail:

1. Void Keyword

    • The void keyword in Java is used for declaring methods that don’t return any value.
    • When a method is void, it carries out some action but does not return any result.

Example of a Void Method:

Java

Output: Example of a Void Method Explanation:

    • The greet() method does not return anything, it just prints a message.

2. Using Command-Line Arguments in Methods

    • Command-line arguments allow the user to pass values to a Java application at runtime via the terminal.
    • These arguments are received in the form of an array of Strings (String[] args) by the main() method.

Example of Command-Line Arguments:

public class CommandLineExample {
    public static void main(String[] args) {
        System.out.println("Number of arguments: " + args.length);
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + (i + 1) + ": " + args[i]);
        }
    }
}

Execution (in the terminal):

java CommandLineExample Hello World 123

Explanation:

  • The command line arguments are passed as an array of String[].
  • Every argument is addressed by an index (args[i]).

3. this Keyword in Java Methods

  • this keyword refers to the current instance of a class.
  • It differentiates between local variables and instance variables when they have the same name.

Example of Using this:

Java

Output:

this Keyword in Java Methods

Explanation:

  • The this keyword is utilized to refer to the instance variable name to avoid confusion with the local variable name.

4. Java Varargs (Variable-Length Arguments)

  • Varargs (Variable-Length Arguments) allow a method to accept a variable number of arguments.
  • It is declared with three dots(…) as the method parameter.

Example of Varargs Method:

Java

Output:

Example of Varargs Method

Explanation:

  • The displayNumbers(int. numbers) method can accept any number of int arguments.
  • Internally, Varargs are handled as an array.

Method Overloading in Java

Method overloading is a Java feature whereby multiple methods within a class may have the same method name but with a different parameter list (method signature). Method overloading allows methods to perform similar actions with different types or numbers of parameters.

Key Characteristics of Method Overloading

  • Occurs in the same class.
  • Methods must vary in their parameter lists (number, type, or order of the parameters).
  • Return type may vary but has no impact on overloading.
  • Enhances readability and reusability by grouping related functionalities under a single method name.

Example of Method Overloading:

Java

Output:

Example of Method Overloading

Explanation:

  • The compiler determines the method to be called based on the arguments given.
  • Although all the methods share the same name (add()), they all have different parameter lists, so they are all different.
  • This improves code organization and avoids method name duplication for identical operations.

Method Overriding in Java

Method overriding in Java is a feature that enables a subclass to possess a specialized form of the method that is already available in its superclass. It is used to achieve runtime polymorphism.

Key Characteristics of Method Overriding

  • Takes place between a superclass and a subclass (inheritance required).
  • The subclass method needs to have the same name, return type, and parameters as in the parent class.
  • Access modifiers cannot be more restrictive than the overridden method (i.e., the public method cannot be overridden as private).
  • Used for altering the behavior of a method from the parent class.
  • Requires the @Override annotation (optional but recommended for clarity and to avoid mistakes).

Example of Method Overriding:

Java

Output:

Example of Method Overriding

Explanation:

  • The Dog class overrides the makeSound() method of the Animal class.
  • If we call makeSound() on a Dog object, it executes the overridden method in Dog, not the one in Animal.
  • Upcasting (Animal myDog = new Dog();) enables runtime polymorphism, i.e., the method called is determined by the actual object (Dog) and not by the reference type (Animal).

Java Recursion to Demonstrate Methods

Recursion is a process where a method invokes itself directly or indirectly to obtain the solution to a problem. Recursion is generally used in the following scenarios:

Key Characteristics of Recursion

  • Base Condition: Defines the recursion termination point (prevents infinite calls).
  • Recursive Case: The part of the method where the method calls itself.
  • Stack Memory Usage: Each recursive call is put on the method call stack until it completes.

Basic Example of Recursion in Java

Let’s take a simple example to understand recursion: calculating the factorial of a number.

Factorial Example Using Recursion

Java

Output:

Factorial Example Using Recursion

Explanation:

  1. The base case (n == 0) ensures that the recursion stops when n is 0.
  2. Otherwise, the method calls itself with n – 1, breaking down the problem.

Advantages of Using Methods in Java

1. Code Reusability

Java methods avoid duplicating code since they allow you to write a block of logic once and reuse it numerous times, and hence the program is efficient and simple to maintain.

2. Improved Code Readability

By breaking up big logic into small, independent methods, Java methods enable code to be more readable so that developers can understand and debug it better.

3. Maintainability and Modularity

Methods promote modular programming, where a large program is divided into small, self-contained units. This makes it much easier to debug, update, and maintain the code.

4. Reduces Code Complexity

Methods enable code organization by dividing tasks into logical sections, reducing overall complexity, and improving program design.

5. Makes Debugging and Testing Easier

Since methods are independent, you can test and debug individual methods separately, improving software reliability and making it easier to identify errors.

6. Efficient Memory Management

Java methods help optimize memory since they only consume memory when a method is invoked. Methods utilize a stack-based execution model, taking minimal excess memory.

7. Promotes Code Abstraction

By using methods, you can conceal implementation details and only reveal the required functionality, thus supporting data abstraction and neater code design.

8. Supports Method Overloading and Overriding

Methods enable method overloading (multiple methods with the same name but different parameters) and method overriding (modifying inherited methods), providing flexibility and code optimization.

Conclusion

This is the end of the tutorial on Java Methods. You have now understood that Java Methods are an important part of Java Programming for the reusability, maintainability, and efficiency of the code. From the basic Java method definitions to the advanced topics of method overloading, method overriding, and recursion, understanding these methods in Java helps you write structured and optimized code.

By learning the scope of the method in Java, memory allocation, and calling guarantee correct execution, while var, args, this keyword, and command-line arguments are some of the features that make Java methods versatile. Keep practicing to improve your skills in Java!

Java Methods - FAQs
1. What are methods in Java, and why are they important?

Java methods are simply blocks of code that perform some operations and improve code reusability, maintainability, and performance. They also help in splitting complex problems into manageable parts so that the code is modular and readable.

2. What is the difference between method overloading and method overriding in Java?
  • Method Overloading: It means that there is more than one method with the same name but different parameters in the same class.
  • Method Overriding: Here, the subclass provides a specialized meaning to a method that is already present in the parent class by having the same name and parameters.
3. What is the difference between static and instance methods in Java?

Static methods are typically class members and can be called without an object. They are defined using the static keyword, whereas Instance methods belong to individual objects and require an instance of the class to be invoked.

4. How does Java handle method parameters—pass by value or pass by reference?

Java uses pass-by-value for method parameters. For primitive types, the value is copied, so the changes inside the method are not visible in the original value. For objects, however, the reference is passed by value, and therefore, changes to the object’s state within the method affect the original object.

5. What is recursion in Java, and when should it be used?

Recursion is a technique in which a method calls itself to solve a problem. Recursion is very useful for overlapping subproblems kind of problems, such as factorial, Fibonacci series, and tree traversal. Excessive recursion leads to StackOverflowError, however, so it should be used with proper base conditions.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.