Methods in Java

  • Last Updated: June 25, 2025
  • By: javahandson
  • Series
img

Methods in Java

Explore basics about methods in Java — from syntax and types to overloading, overriding, static, final, abstract, and synchronized methods.

 

In Java, a method is a block of code that performs a specific task. Methods play a crucial role in writing modular, reusable, and maintainable code. Instead of writing the same code multiple times, we define a method once and invoke it whenever needed. This improves code efficiency and readability.

Why Use Methods in Java?

Methods are fundamental in Java for several reasons:

Code Reusability – Define once, use multiple times.
Modularity – Break down complex logic into smaller, manageable parts.
Maintainability – Easier to debug and update.
Readability – Organizes the program into logical sections.
Encapsulation – Hides implementation details from the user.

Method Declaration & Syntax

A method in Java has the following structure:

modifier returnType methodName(parameterList) {

    // Method body

    return value;   // (if applicable)
}

Example:

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

Components of a Method

A Java method consists of:

Access Modifier – Determines the visibility of a method (public, private, protected, or default).
Return Type – Specifies the data type of the value returned (void if no value is returned).
Method Name – Identifies the method uniquely.
Parameter List – Inputs passed to the method, enclosed in parentheses (optional if no parameters are required).
Method Body – The block of code that executes when the method is called.
Return Statement – Returns a value (if applicable). If the method is void, no return statement is needed.

Types of Methods in Java

In Java, methods can be classified into different types based on their functionality and usage. These include predefined methods, user-defined methods, static methods, instance methods, abstract methods, and synchronized methods.

1. Predefined Methods (Built-in Methods)

 

Java provides many built-in methods in libraries such as Math, String, Arrays, etc. These methods are already defined and can be directly used in our programs.

Example: Using Built-in Methods

package com.javahandson.methods

public class PredefinedMethodExample {
    public static void main(String[] args) {
        double squareRoot = Math.sqrt(25); // sqrt() is a predefined method
        System.out.println("Square root of 25: " + squareRoot);
        
        String str = "Hello, JavaHandsOn!";
        System.out.println("String Length: " + str.length()); // length() is a predefined method
    }
}
Output:
Square root of 25: 5.0  
String Length: 19 

2. User-Defined Methods

These are methods that developers define to perform specific tasks. They help in reusability and modularity.

Example: User-Defined Method

package com.javahandson.methods

public class UserDefinedMethod {

    // User-defined method to calculate the sum of two numbers
    public int addNumbers(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        UserDefinedMethod obj = new UserDefinedMethod();
        int sum = obj.addNumbers(10, 20);
        System.out.println("Sum: " + sum);
    }
}
Output: Sum: 30  

We need to create an object of the UserDefinedMethod class so that we can call the #addNumbers method, as #addNumbers is an instance method.

3. Static Methods

Static methods belong to the class rather than instances of the class. They can be called without creating an object.

Example: Static Method

package com.javahandson.methods

public class StaticMethodExample {
    // Static method
    public static void showMessage() {
        System.out.println("This is a static method.");
    }
    public static void main(String[] args) {
        showMessage(); // Calling static method directly without object creation
    }
}
Output: This is a static method.

4. Instance Methods (Non-Static Methods)

Instance methods belong to an object of the class and require an object to be called.

Example: Instance Method

package com.javahandson.methods

public class InstanceMethodExample {
    // Instance method
    public void showMessage() {
        System.out.println("This is an instance method.");
    }
    public static void main(String[] args) {
        InstanceMethodExample obj = new InstanceMethodExample();
        obj.showMessage(); // Calling instance method using object
    }
}
Output: This is an instance method.

5. Abstract Methods

An abstract method is a method that is declared without any implementation. The abstract method must be defined inside an abstract class and overridden by subclasses.

Example: Abstract Method

package com.javahandson.methods

abstract class Animal {
    // Abstract method (does not have a body)
    abstract void makeSound();
}
class Dog extends Animal {
    // Implementing the abstract method
    void makeSound() {
        System.out.println("Dog barks.");
    }
}
public class AbstractMethodExample {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound();
    }
}
Output: Dog barks. 

6. Synchronized Methods

A synchronized method is used in multithreading to prevent multiple threads from accessing it simultaneously. It ensures thread safety.

Example: Synchronized Method

package com.javahandson.methods

class SharedResource {
    synchronized void displayMessage(String message) {
        System.out.print("[ " + message);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(e);
        }
        System.out.println(" ]");
    }
}

package com.javahandson.methods

class MyThread extends Thread {
    SharedResource obj;
    String message;

    MyThread(SharedResource obj, String message) {
        this.obj = obj;
        this.message = message;
    }
    public void run() {
        obj.displayMessage(message);
    }
}

package com.javahandson.methods

public class SynchronizedMethodExample {
    public static void main(String[] args) {
        SharedResource obj = new SharedResource();
        MyThread t1 = new MyThread(obj, "Hello");
        MyThread t2 = new MyThread(obj, "JavaHandsOn");

        t1.start();
        t2.start();
    }
}
Output: 
[ Hello ]  
[ JavaHandsOn ] 

Method Parameters & Return Types

Methods in Java can take parameters (inputs) and return values (outputs). Understanding how these work is essential for writing reusable and efficient code.

1. Method Parameters in Java

 

A parameter is a value passed to a method when it is called. Parameters allow methods to work with different data instead of hardcoding values.

Methods with Parameters – A method can take one or more parameters as input.

Example: Method with Single Parameter

package com.javahandson.methods

public class SingleParameterExample {
    // Method with a single parameter
    public void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        SingleParameterExample obj = new SingleParameterExample();
        obj.greet("Suraj"); // Passing a parameter
    }
}
Output: Hello, Suraj!

Example: Method with Multiple Parameters

package com.javahandson.methods

public class MultipleParametersExample {
    // Method with two parameters
    public int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        MultipleParametersExample obj = new MultipleParametersExample();
        int sum = obj.add(10, 20);
        System.out.println("Sum: " + sum);
    }
}
Output: Sum: 30 

Methods Without Parameters – A method can also be defined without parameters when it does not require any input values.

Example: Method Without Parameters

package com.javahandson.methods

public class NoParameterExample {
    public void showMessage() {
        System.out.println("Hello, this is a method without parameters.");
    }

    public static void main(String[] args) {
        NoParameterExample obj = new NoParameterExample();
        obj.showMessage();
    }
}
Output: Hello, this is a method without parameters.

Variable Arguments (Varargs) – Java allows a method to accept variable-length arguments using the … syntax.

Example: Method Using Varargs

package com.javahandson.methods

public class VarargsExample {
    public void printNumbers(int... numbers) {
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        VarargsExample obj = new VarargsExample();
        obj.printNumbers(1, 2, 3, 4, 5);  // Passing multiple arguments
    }
}
Output: 1 2 3 4 5  

2. Method Return Types in Java

A return type specifies the type of value a method returns. Methods can return primitive values, objects, or nothing (void).

Methods with Return Values – A method can return a value using the return keyword. The return type must match the type of value returned.

Example: Method Returning an Integer

package com.javahandson.methods

public class ReturnExample {
    public int square(int num) {
        return num * num;
    }

    public static void main(String[] args) {
        ReturnExample obj = new ReturnExample();
        int result = obj.square(5);
        System.out.println("Square: " + result);
    }
}
Output: Square: 25

Methods Without Return Values (void Methods) – A method declared with void does not return anything.

Example: void Method

package com.javahandson.methods

public class VoidMethodExample {
    public void printMessage() {
        System.out.println("This is a void method.");
    }

    public static void main(String[] args) {
        VoidMethodExample obj = new VoidMethodExample();
        obj.printMessage();
    }
}
Output: This is a void method.

Returning Objects from Methods – Methods can return non-primitive types, such as objects.

Example: Returning a String

package com.javahandson.methods

public class StringReturnExample {
    public String getMessage() {
        return "Hello JavaHandsOn!";
    }

    public static void main(String[] args) {
        StringReturnExample obj = new StringReturnExample();
        String message = obj.getMessage();
        System.out.println(message);
    }
}
Output: Hello JavaHandsOn!

Example: Returning a Custom Object

package com.javahandson.methods

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

public class ObjectReturnExample {
    public Person createPerson(String name) {
        return new Person(name);
    }

    public static void main(String[] args) {
        ObjectReturnExample obj = new ObjectReturnExample();
        Person p = obj.createPerson("Suraj"); // Return a custom object
        System.out.println("Person's name: " + p.name);
    }
}
Output: Person's name: Suraj

Returning Arrays from Methods – A method can also return an array.

Example: Returning an Array

package com.javahandson.methods

public class ArrayReturnExample {
    public int[] getNumbers() {
        return new int[]{1, 2, 3, 4, 5};
    }

    public static void main(String[] args) {
        ArrayReturnExample obj = new ArrayReturnExample();
        int[] numbers = obj.getNumbers();
        
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
Output: 1 2 3 4 5

Method Overloading in Java

Method overloading is a feature in Java that allows multiple methods in the same class to have the same name but different parameters.

Key Points About Method Overloading:

1. Methods must have the same name but different parameter lists.
2. Method overloading is determined at compile-time (also called as compile-time polymorphism).
3. It does not depend on return type (return type alone cannot differentiate methods).
4. Overloaded methods can have different numbers of parameters or different parameter types.

Example: Overloading a method

package com.javahandson.methods

class OverloadingExample {
    // Overloaded method with different parameters
    void display(int a) {
        System.out.println("Integer: " + a);
    }

    void display(double a) {
        System.out.println("Double: " + a);
    }

    public static void main(String[] args) {
        OverloadingExample obj = new OverloadingExample();
        obj.display(5);    // Calls method with int parameter
        obj.display(5.5);  // Calls method with double parameter
    }
}
Output: 
Integer: 5  
Double: 5.5  

Method Overriding in Java

Method overriding in Java occurs when a subclass provides a specific implementation of a method that is already defined in its parent class. The overriding method in the subclass must have the same name, return type, and parameters as the method in the parent class.

Key Points About Method Overriding:

1. The method name, return type, and parameters must be identical.
2. The method in the child class must have the same or broader access modifier than the parent method.
3. The method in the child class cannot have a stricter access modifier than the parent method.
4. It is an example of runtime polymorphism (dynamic method dispatch).
5. The overridden method in the parent class must not be private, static, or final.
6. If the parent method is static, it does not get overridden; instead, the child method hides it.

Example: Overriding a method

package com.javahandson.methods

class Parent {
    void show() {
        System.out.println("Parent class method");
    }
}

class Child extends Parent {
    @Override
    void show() {
        System.out.println("Child class method");
    }
}

public class OverridingExample {
    public static void main(String[] args) {
        Parent obj = new Child(); // Upcasting
        obj.show(); // Calls the overridden method in Child class
    }
}
Output: Child class method  

Static vs Non-Static Methods

In Java, methods can be classified into static and non-static methods based on whether they belong to the class or an instance of the class. Understanding the difference between these two is crucial for effective programming.

Static Methods

A static method belongs to the class rather than an instance of the class. It is defined using the static keyword.

Key Characteristics of Static Methods:

1. Can be called without creating an object.
2. Can only access static variables and static methods directly.
3. Cannot use this or super keywords.
4. Cannot be overridden but can be hidden in subclasses.

Example: Static Method Usage

package com.javahandson.methods

class StaticExample {
    static int count = 0;

    // Static method
    static void displayCount() {
        System.out.println("Count: " + count);
    }

    public static void main(String[] args) {
        StaticExample.displayCount(); // Calling static method without object
    }
}
Output: Count: 0

Non-Static Methods

A non-static method belongs to an instance (object) of the class.

Key Characteristics of Non-Static Methods:

1. Can access both static and instance variables.
2. Requires an object to be called.
3. Can use this and super keywords.
4. Can be overridden in a subclass.

Example: Non-Static Method Usage

package com.javahandson.methods

class NonStaticExample {
    int count = 0;

    // Non-static method
    void increment() {
        count++;
        System.out.println("Count: " + count);
    }

    public static void main(String[] args) {
        NonStaticExample obj = new NonStaticExample();
        obj.increment(); // Calling non-static method
    }
}
Output: Count: 1

Final, abstract, and synchronized methods

Final method

A final method cannot be overridden by a subclass. It ensures that the method’s implementation remains unchanged across the inheritance hierarchy.

Key Characteristics:

1. Declared using the final keyword.
2. Cannot be overridden in child classes.
3. It can be inherited and called by child classes.
4. Increases security and prevents accidental modifications.

class Parent {
    final void show() {
        System.out.println("This is a final method.");
    }
}

class Child extends Parent {
    // ❌ Compilation Error: Cannot override final method
    // void show() { System.out.println("Trying to override"); }
}

public class FinalMethodExample {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.show(); // Calls the Parent class method
    }
}

Use Cases of Final Methods:

1. When you want to prevent modification of critical logic in subclasses.
2. Used in Java’s String class (e.g., final String toString()).
3. Common in utility classes and framework classes (e.g., java.lang.Math).

Abstract method

An abstract method is a method without a body; it must be implemented by a subclass. An abstract method is only allowed inside an abstract class.

Key Characteristics:

1. Declared using the abstract keyword.
2. No method body (only declaration).
3. Must be overridden in child classes.
4. The class containing an abstract method must be abstract.

abstract class Animal {
    abstract void makeSound(); // Abstract method (no body)
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark! Bark!");
    }
}

public class AbstractMethodExample {
    public static void main(String[] args) {
        Animal obj = new Dog();
        obj.makeSound(); // Calls the overridden method in Dog class
    }
}
Output: Bark! Bark!

Use Cases of Abstract Methods:

1. Encourages abstraction and enforces a common method signature.
2. Used in frameworks like Spring and Hibernate for defining interfaces.

Synchronized method

A synchronized method ensures that only one thread can execute it at a time, preventing race conditions in multithreaded applications.

Key Characteristics:

1. Declared using the synchronized keyword.
2. Ensures thread safety by allowing only one thread to access it at a time.
3. Can be applied to both static and instance methods.
4. Reduces concurrency issues, but can affect performance due to locking.

class SharedResource {
    synchronized void printNumbers() {
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
            try { Thread.sleep(500); } catch (InterruptedException e) {}
        }
    }
}

class Thread1 extends Thread {
    SharedResource obj;
    Thread1(SharedResource obj) { this.obj = obj; }
    public void run() { obj.printNumbers(); }
}

class Thread2 extends Thread {
    SharedResource obj;
    Thread2(SharedResource obj) { this.obj = obj; }
    public void run() { obj.printNumbers(); }
}

public class SyncMethodExample {
    public static void main(String[] args) {
        SharedResource obj = new SharedResource();
        Thread1 t1 = new Thread1(obj);
        Thread2 t2 = new Thread2(obj);
        
        t1.start();
        t2.start();
    }
}
Output: 1 2 3 4 5  1 2 3 4 5  

Use Cases of Synchronized Methods:

1. Used in multithreading to prevent race conditions.
2. Common in banking applications (e.g., balance updates).
3. Used in thread-safe Java classes (Vector, Hashtable).

Conclusion

Methods are the foundation of any Java application. From understanding their syntax and types to mastering advanced concepts like overloading, overriding, and synchronization, this guide has walked you through it all. By grasping these method-related concepts, you’ll write cleaner, more efficient, and object-oriented Java code that’s easier to maintain and scale. Keep practicing, and soon these fundamentals will become second nature!

So this is all about methods in Java. If you have any questions on this topic, please raise them in the comments section. If you liked this article, then please share this post with your friends and colleagues.

Leave a Comment