Java Methods - Syntax, Types and Complete Examples

⏱️ 10 min read • Beginner Level • Lesson 33

Lesson 33 of 124 of Java Tutorial

A method in Java is a block of code that performs a specific task. Methods help you write reusable, organized, and easy-to-maintain programs.

Before learning methods, you should understand Java Program Structure, Java Variables, and Java Data Types. After this lesson, continue with Java Method Parameters.


What is a Method in Java?

A method is a group of statements written together to perform a particular operation. Instead of writing the same code again and again, you can define a method once and call it whenever required.

Simple Meaning: A method is like a small machine. You give it input, it performs some work, and it may return output.

Why Use Methods in Java?

  • Methods make code reusable.
  • Methods reduce duplicate code.
  • Methods make programs easier to read and maintain.
  • Methods divide a large program into smaller parts.
  • Methods help in testing and debugging code easily.

Real-World Example of Methods

Methods are used everywhere in real applications. For example, an online shopping website may use separate methods for:

  • Calculating the total bill
  • Applying discounts
  • Processing payments
  • Sending confirmation emails

Instead of writing all logic inside the main() method, developers divide the program into smaller reusable methods.

Example: A shopping application may contain methods such as calculateTotal(), applyDiscount(), makePayment(), and sendEmail().

Syntax of Method in Java

The general syntax of a Java method is:

MethodSyntax.java
Copy Download
accessModifier returnType methodName(parameters) {
    // method body
}

Parts of a Java Method

Part Meaning
Access Modifier Defines where the method can be accessed from, such as public, private, or protected. If no access modifier is written, Java uses default access, which allows access only within the same package.
Return Type Defines what type of value the method returns. Use void if it returns nothing.
Method Name Name used to call the method.
Parameters Input values passed to the method.
Method Body Statements written inside method braces.
Important: If no access modifier is specified before a method, Java applies default access. Default access is also called package-private access, which means the method can be accessed only within the same package.

Default Access Method Example

If a method does not use public, private, or protected, it has default access. This means it can be accessed only by classes in the same package.

DefaultAccessMethodExample.java
class DefaultAccessMethodExample {

    void showMessage() {
        System.out.println("This method has default access.");
    }

    public static void main(String[] args) {
        DefaultAccessMethodExample obj = new DefaultAccessMethodExample();
        obj.showMessage();
    }
}

Output:

This method has default access.
Note: The method showMessage() has no access modifier, so it gets default access and can be used only inside the same package.

How to Call a Method in Java

A method runs only when it is called. Static methods can be called directly from another static method in the same class, while instance methods need an object.

CallMethodExample.java
Copy Try Download
public class CallMethodExample {
    static void greet() {
        System.out.println("Hello Java");
    }

    public static void main(String[] args) {
        greet();
    }
}

Output:

Hello Java
Method Execution Flow:

Method Call ➜ Control Transfers to Method ➜ Statements Execute ➜ Return to Caller

Predefined Methods in Java

Predefined methods are already available in Java libraries. You can use them without writing their body. Examples include System.out.println(), Math.sqrt(), and String.length().

PredefinedMethodExample.java
Copy Try Download
public class PredefinedMethodExample {
    public static void main(String[] args) {
        System.out.println("Java Methods");
        System.out.println(Math.sqrt(25));
        System.out.println("ProwessApps".length());
    }
}

Output:

Java Methods
5.0
11

User-Defined Methods in Java

User-defined methods are methods created by the programmer to perform specific tasks.

UserDefinedMethodExample.java
Copy Try Download
public class UserDefinedMethodExample {
    static void showMessage() {
        System.out.println("This is a user-defined method.");
    }

    public static void main(String[] args) {
        showMessage();
    }
}

Output:

This is a user-defined method.

void Method in Java

A void method performs a task but does not return any value.

VoidMethodExample.java
Copy Try Download
public class VoidMethodExample {
    static void printWelcome() {
        System.out.println("Welcome to Java methods.");
    }

    public static void main(String[] args) {
        printWelcome();
    }
}

Output:

Welcome to Java methods.

Return Type Method in Java

A return type method performs a task and sends a value back to the caller using the return statement.

ReturnMethodExample.java
Copy Try Download
public class ReturnMethodExample {
    static int square() {
        return 5 * 5;
    }

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

Output:

Square: 25
Note: If a method has a return type other than void, it must return a value of that type.

Parameterized Method in Java

A parameterized method accepts one or more input values through parameters.

ParameterizedMethodExample.java
Copy Try Download
public class ParameterizedMethodExample {
    static void showStudent(String name, int age) {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        showStudent("Ayan", 20);
    }
}

Output:

Name: Ayan
Age: 20

No-Argument Method in Java

A no-argument method does not accept any parameters.

NoArgumentMethodExample.java
Copy Try Download
public class NoArgumentMethodExample {
    static void displayDateMessage() {
        System.out.println("Today is a good day to learn Java.");
    }

    public static void main(String[] args) {
        displayDateMessage();
    }
}

Output:

Today is a good day to learn Java.

Static Method in Java

A static method belongs to the class. It can be called without creating an object.

StaticMethodExample.java
Copy Try Download
public class StaticMethodExample {
    static void showMessage() {
        System.out.println("Static method called");
    }

    public static void main(String[] args) {
        StaticMethodExample.showMessage();
    }
}

Output:

Static method called

Instance Method in Java

An instance method belongs to an object. You must create an object to call an instance method.

InstanceMethodExample.java
Copy Try Download
public class InstanceMethodExample {
    void showMessage() {
        System.out.println("Instance method called");
    }

    public static void main(String[] args) {
        InstanceMethodExample obj = new InstanceMethodExample();
        obj.showMessage();
    }
}

Output:

Instance method called

Recursive Method in Java

A recursive method is a method that calls itself. Recursion is useful for problems that can be divided into smaller similar problems.

RecursiveMethodExample.java
Copy Try Download
public class RecursiveMethodExample {
    static int factorial(int number) {
        if (number == 1) {
            return 1;
        }
        return number * factorial(number - 1);
    }

    public static void main(String[] args) {
        System.out.println("Factorial: " + factorial(5));
    }
}

Output:

Factorial: 120
Important: A recursive method must have a stopping condition. Otherwise, it may cause a stack overflow error.

Getter and Setter Methods in Java

Getter and setter methods are commonly used to read and update private variables. Getter methods are also called accessor methods, and setter methods are also called mutator methods.

GetterSetterExample.java
Copy Try Download
class Student {
    private String name;

    public void setName(String studentName) {
        name = studentName;
    }

    public String getName() {
        return name;
    }
}

public class GetterSetterExample {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("Ayan");
        System.out.println(student.getName());
    }
}

Output:

Ayan

Complete Example of Java Methods

This example uses static method, instance method, void method, return method, and parameterized method together.

JavaMethodsExample.java
Copy Try Download
public class JavaMethodsExample {

    static void welcomeMessage() {
        System.out.println("Welcome to Java Methods");
    }

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

    void displayResult(int result) {
        System.out.println("Result: " + result);
    }

    public static void main(String[] args) {
        welcomeMessage();

        int sum = addNumbers(10, 20);

        JavaMethodsExample obj = new JavaMethodsExample();
        obj.displayResult(sum);
    }
}

Output:

Welcome to Java Methods
Result: 30

Explanation

  1. welcomeMessage() is a static void method.
  2. addNumbers() is a static parameterized method that returns an integer.
  3. displayResult() is an instance void method.
  4. An object is created to call the instance method.
  5. The program demonstrates different method types together.

Types of Methods in Java - Quick Revision

Method Type Meaning
Predefined Method Already available in Java libraries.
User-defined Method Created by the programmer.
void Method Does not return a value.
Return Type Method Returns a value.
Parameterized Method Receives input values.
No-Argument Method Does not receive parameters.
Static Method Belongs to the class.
Instance Method Belongs to an object.
Recursive Method Calls itself.
Getter/Setter Method Used to read and update private variables.

Common Mistakes with Java Methods

  • Forgetting to call the method after defining it.
  • Using a return type but not returning a value.
  • Trying to call an instance method directly from a static method without creating an object.
  • Passing wrong number or wrong type of arguments.
  • Writing method names that are not meaningful.
  • Creating recursive methods without a stopping condition.
Summary:
  • A method is a reusable block of code that performs a specific task.
  • Methods improve readability, reusability, and maintainability.
  • Java supports predefined and user-defined methods.
  • A void method does not return a value.
  • A return type method returns a value using return.
  • Static methods belong to the class, while instance methods belong to objects.
  • Parameterized methods receive input values.
  • Recursive methods call themselves and need a stopping condition.

Frequently Asked Questions

A method in Java is a block of code that performs a specific task. It helps make code reusable, organized, and easier to maintain.

Methods are used in Java to reuse code, reduce duplication, divide large programs into smaller parts, and improve readability and maintenance.

The basic syntax of a Java method is accessModifier returnType methodName(parameters) { method body }.

If no access modifier is specified before a method, Java applies default access, also called package-private access. This means the method can be accessed only within the same package.

A void method performs a task but does not return any value. It uses the void return type.

A return type method performs a task and returns a value using the return statement. The returned value must match the method return type.

A parameterized method is a method that receives input values through parameters. These values are used inside the method body.

A no-argument method is a method that does not accept any parameters. It can be called without passing values.

A static method belongs to the class and can be called without creating an object of the class.

An instance method belongs to an object. To call an instance method, you need to create an object of the class.

A recursive method is a method that calls itself. It must have a stopping condition to avoid infinite recursion.

Predefined methods are methods already provided by Java libraries, such as System.out.println(), Math.sqrt(), and String.length().

User-defined methods are methods created by programmers to perform specific tasks in a program.

Getter and setter methods are used to read and update private variables. Getter methods return values, while setter methods update values.

A Java method directly returns only one value. To return multiple values, you can use an object, array, collection, or custom class.

No, an instance method cannot be called directly from a static method. You must create an object to call an instance method.

Next step: Learn Java Method Parameters

🚀 Continue to Java Method Parameters →

🧠 Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: Methods | Language: Java

Q1. How can a static method be called using class name?
Q2. Why are methods used in Java?
Q3. What is a method in Java?
Q4. What happens if a method is defined but never called?
Q5. What is a recursive method?
Q6. What is necessary in a recursive method?
Q7. What does a setter method usually do?
Q8. What happens if no access modifier is specified for a method in Java?
Q9. What is a no-argument method?
Q10. What will be the output of this code?
public class Test {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(10, 20));
    }
}
Q11. What is a static method in Java?
Q12. What is a parameterized method?
Q13. What does a getter method usually do?
Q14. What is a user-defined method?
Q15. What will be the output of this code?
public class Test {
    static void greet() {
        System.out.println("Hello Java");
    }

    public static void main(String[] args) {
        greet();
    }
}
Q16. Which keyword is used when a method does not return any value?
Q17. Which part of a method tells what value the method sends back?
Q18. Which of the following is a valid method declaration?
Q19. What is another name for default access in Java?
Q20. Which of the following is an example of a predefined method?
Q21. What will be the output of this code?
public class Test {
    static void show(String name) {
        System.out.println(name);
    }

    public static void main(String[] args) {
        show("Ayan");
    }
}
Q22. What is a predefined method in Java?
Q23. What is required to call an instance method from main method?
Q24. Which method has default access?
Q25. A method with default access can be accessed from where?
Q26. Which statement is true about a method with return type int?
Q27. What is an instance method in Java?
Q28. Which method name follows Java naming convention?

🎉 Great job! Continue learning Java step by step.