Industry Ready Java Spring Boot, React & Gen AI — Live Course
JavaMethods and constructors

Methods

What Are Methods?

A method is a block of code designed to perform a specific task.
Methods allow you to:

  • Organize logic into meaningful units
  • Avoid repeating code
  • Improve readability and maintainability
  • Represent the behaviour of an object in Object-Oriented Programming

Every Java program starts execution from the main() method, but you can create many other methods to structure your code better.

methods

Example – Class with Methods

class Computer {

    // Behaviour 1: does not return anything
    public void playMusic() {
        System.out.println("Playing music");
    }

    // Behaviour 2: returns a value
    public String getMeAPen(int cost) {
        if (cost >= 10)
            return "Pen";
        return "Nothing";
    }
}

This class defines two behaviours:

  1. playMusic() → prints a message
  2. getMeAPen(int cost) → returns a value based on the input

Main Class – Calling Methods

public class Demo {
    public static void main(String[] args) {
        Computer obj = new Computer();     // Create object

        obj.playMusic();                   // Call method 1

        String item = obj.getMeAPen(5);    // Call method 2
        System.out.println(item);
    }
}

Output

Playing music
Nothing

Understanding How Methods Work

A method in Java has this general structure:

returnType methodName(parameters) {
    // method body
}

Example Breakdown

public String getMeAPen(int cost)
PartMeaning
publicAccess modifier — method is visible outside the class
StringReturn type — this method returns a String
getMeAPenMethod name
(int cost)Parameter — input value required to execute method

Important Concepts

1. The void Keyword

When a method does not return anything, you use void:

public void playMusic() {
    System.out.println("Playing music");
}

This method performs an action but does not return a value.

2. Returning a Value

If a method returns a value, its return type must match what it returns:

public String getMeAPen(int cost) {
    if (cost >= 10)
        return "Pen";      // Must return a String
    return "Nothing";
}

If a return statement is expected, it must be present on every possible path.

3. Passing Arguments (Parameters)

Data is passed into a method using parameters:

obj.getMeAPen(15);

Here, 15 is copied into the parameter cost.

The number and type of arguments must match the method definition.

Summary

  • Methods represent the behaviours of an object.
  • void methods perform actions without returning a value.
  • Methods with return types must return the specified type.
  • Parameters allow data to be passed into methods.
  • The main() method acts as the program’s entry point, from where other methods are invoked.

Written By: Shiva Srivastava

How is this guide?

Last updated on