Lesson 26 of 140

Checking lesson access...

Video and written lesson · 23 min

Introduction to Methods

Learn why methods exist, declare and call a simple `void` method, and follow how control moves into a method and back.

PreviewCaptionsSoon

You are viewing a free preview lesson.

Lesson Overview

As a program grows, keeping all logic inside the main() method becomes difficult. Writing the same code repeatedly also creates duplication. For example:

java
System.out.println("====================");
System.out.println("Tarkev");
System.out.println("====================");

If the same header is needed in different parts of a program, these statements may have to be written repeatedly. Methods help solve this problem. A method is:

A named block of code that performs a specific task.

With methods, we write repeated logic once, divide a large program into smaller tasks, and give each task a name that says what it does. In this lesson, we write simple methods that take no input and return nothing; parameters and return values follow in the next lesson.

Learning Objectives

After completing this lesson, you will be able to:

  • Explain what a method is
  • Declare a simple method
  • Call a method
  • Distinguish between declaration and invocation
  • Understand the basic meaning of void
  • Trace method execution flow
  • Reuse a method multiple times
  • Choose meaningful method names
  • Extract meaningful behavior from a large block of code

What Is a Method?

A method is a named block of code that performs a specific task. In this example, greet is the method name, and the method body inside the curly braces contains the work performed by the method:

java
static void greet() {
    System.out.println("Welcome to Tarkev!");
}

Method Call

Declaring a method does not execute it. To run the method's behavior, you must call it with greet();. Complete example:

java
public class Main {

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

    static void greet() {
        System.out.println("Welcome to Tarkev!");
    }
}

Output:

text
Welcome to Tarkev!

Declaring a Method Does Not Run It

A method declaration (the static void greet() { ... } block) defines what the method does. A method call (greet();) tells Java to execute it. These are two different things, and only the call runs the code:

java
public class Main {

    public static void main(String[] args) {
        System.out.println("Program started");
    }

    static void greet() {
        System.out.println("Hello!");
    }
}

Output:

text
Program started

Hello! is not printed. Why? Because greet(); was never called.

Method Structure

In this lesson, we will use this simple method pattern:

java
static void methodName() {
    // Statements
}

For example:

java
static void showMenu() {
    System.out.println("1. Courses");
    System.out.println("2. Exit");
}

static

Our main() method is public static void main(String[] args). In this lesson, we will also write helper methods as static, as in static void greet(). This allows us to call a method in the same class directly from main() with greet();.

We will understand what static means and how it relates to objects in more detail when we learn about classes and objects. For now, remember it as part of our method declaration pattern.

void

void means that the method does not return a result value to the caller (return values will be covered in the next lesson). This method performs an action (it prints a message), but it does not return a value:

java
static void printWelcomeMessage() {
    System.out.println("Welcome!");
}

Parentheses

A method declaration has parentheses after the method name, as in greet(). In this lesson, the parentheses are empty because the method does not receive any input. In the next lesson, we will see how calls such as greet("Sakib"); work.

Curly Braces

The method body is placed inside curly braces. Both statements here are part of the greet() method:

java
static void greet() {
    System.out.println("Hello");
    System.out.println("Welcome");
}

Naming Methods

A method name should describe its behavior. A meaningful name helps the reader understand what the method is going to do.

Methods usually represent actions, so a verb or verb phrase is a good default, written in lowerCamelCase:

text
Good:   showMenu()  printHeader()  displayCourseList()  calculateTotal()
Vague:  doIt()  thing()  abc()  x()
Wrong case: ShowMenu()  show_menu()  SHOWMENU()

doIt() compiles, but the reader has to open the method to find out what it does. ShowMenu() and show_menu() also compile; they just break the convention every Java programmer expects.

Calling a Method Multiple Times

One major benefit of methods is reuse. Here, the method is declared once but called three times:

java
public class Main {

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

    static void greet() {
        System.out.println("Hello!");
    }
}

Output:

text
Hello!
Hello!
Hello!

Methods Reduce Duplication

Without a method, the header is duplicated:

java
System.out.println("====================");
System.out.println("Tarkev");
System.out.println("====================");

System.out.println("1. Java");
System.out.println("2. Backend");

System.out.println("====================");
System.out.println("Tarkev");
System.out.println("====================");

Refactored Version

In the refactored version, the header logic exists in one place:

java
public class Main {

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

        System.out.println("1. Java");
        System.out.println("2. Backend");

        printHeader();
    }

    static void printHeader() {
        System.out.println("====================");
        System.out.println("Tarkev");
        System.out.println("====================");
    }
}

Methods Make Intent Clearer

Compare these examples. Without a method:

java
System.out.println("1. Java");
System.out.println("2. Backend");
System.out.println("3. Exit");

With a method:

java
showMenu();

By reading showMenu(), you can immediately understand what the program is doing. If you need the implementation details, you can look at the method body.

main() Is Also a Method

We have been using public static void main(String[] args) from the beginning. This is also a method. When a standard Java application starts, the JVM begins execution from main(). High-level breakdown (we will study some of these pieces in more detail later):

text
public        → access modifier
static        → static method
void          → no returned value
main          → method name
String[] args → parameter

Method Execution Flow

When Java sees greet();, execution moves to the body of the greet() method. When the method finishes, execution continues in the calling method from the statement after the method call.

java
public class Main {

    public static void main(String[] args) {
        System.out.println("A");
        greet();
        System.out.println("C");
    }

    static void greet() {
        System.out.println("B");
    }
}

Output:

text
A
B
C

Execution flow:

Drawing diagram…

One Method Can Call Another Method

java
public class Main {

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

    static void startApplication() {
        showLogo();
        showMenu();
    }

    static void showLogo() {
        System.out.println("Tarkev");
    }

    static void showMenu() {
        System.out.println("1. Courses");
        System.out.println("2. Exit");
    }
}

Execution:

Drawing diagram…

A Method Can Be Called Even If Its Declaration Appears Later in the Source File

Look again at the program in Method Call above: main() calls greet(), and the greet() declaration comes after main() in the file. That is valid. The compiler reads the whole class, so the order of method declarations inside a class does not matter.

Dividing a Program into Small Tasks

Suppose a program needs to:

text
Show welcome message
Show course list
Show enrollment confirmation

We can write:

java
public class Main {

    public static void main(String[] args) {
        showWelcomeMessage();
        showCourses();
        showEnrollmentConfirmation();
    }

    static void showWelcomeMessage() {
        System.out.println("Welcome to Tarkev!");
    }

    static void showCourses() {
        System.out.println("Available courses:");
        System.out.println("1. Java and OOP Foundation");
        System.out.println("2. Backend Development");
    }

    static void showEnrollmentConfirmation() {
        System.out.println("Enrollment completed.");
    }
}

Now main() shows the high-level program flow:

Drawing diagram…

One Method, One Clear Purpose

A method should ideally represent one coherent task. This one is reasonable, because all of its statements represent one concept, showing the course details:

java
static void showCourseDetails() {
    System.out.println("Course: Java");
    System.out.println("Level: Beginner");
    System.out.println("Language: Bangla");
}

Not Every Line Needs a Method

Over-complicated:

java
static void printA() {
    System.out.println("A");
}

static void printB() {
    System.out.println("B");
}

static void printC() {
    System.out.println("C");
}

Simply creating methods does not automatically make code better. A method is useful when it:

  • Represents a meaningful task
  • Encapsulates repeated behavior
  • Gives a clear name to a complex section
  • Divides a large method into understandable parts

Method Extraction

Moving a meaningful block of existing code into a new method is commonly called Extract Method. We already did it once: in the Refactored Version above, the three header lines moved out of main() into printHeader(), and main() now says what happens instead of how.

When Is Method Extraction Useful?

Useful signals include:

  • The same logic is repeated
  • Several statements together form a clear task
  • A code block can be given a meaningful name
  • A method performs many unrelated tasks
  • The main program flow is getting lost among implementation details

A Local Variable Is Not Available Outside Its Method

java
static void showCourse() {
    String courseName = "Java and OOP Foundation";
    System.out.println(courseName);
}

The variable courseName is accessible only within the local scope of the method; we will study variable scope in more detail later. This is invalid:

java
public static void main(String[] args) {
    showCourse();
    System.out.println(courseName);
}

Where Methods Are Declared

A method declaration appears inside the class body:

java
public class Main {

    static void greet() {
        System.out.println("Hello");
    }
}

A method cannot be declared inside another method. This is invalid, because greet() sits inside main():

java
public static void main(String[] args) {

    static void greet() {
        System.out.println("Hello");
    }
}

Methods sit side by side in the class body, as in every complete program in this lesson.

Important Terms

Method

A named block of code that performs a specific task.

Method Declaration

Defines a method's structure and behavior.

Method Call

Executes a declared method.

void

Indicates that the method does not return a result value.

Method Body

The statements inside the method's curly braces.

Local Variable

A variable declared inside a method.

Method Extraction

Moving a meaningful block of code into a separate method.

Predict the Result

Question 1

What does this program print?

java
public class Main {

    public static void main(String[] args) {
        System.out.println("Start");
        greet();
        printLine();
        System.out.println("End");
    }

    static void greet() {
        printLine();
        System.out.println("Hello");
    }

    static void printLine() {
        System.out.println("---");
    }
}

Answer

text
Start
---
Hello
---
End

greet() calls printLine() before it prints Hello, so the first line of dashes comes from inside greet(). When greet() finishes, main() continues with its own printLine() call.

Question 2

What does this program print?

java
public class Main {

    static void showFooter() {
        System.out.println("Footer");
    }

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

    static void showHeader() {
        System.out.println("Header");
    }
}

Answer

text
Header

Execution always starts in main(), wherever it sits in the class. showHeader() is declared after main() and still runs; showFooter() is declared first but never called, so it never runs.

Question 3

Does this program compile?

<!-- error -->
java
public class Main {

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

    static void greet() {
        System.out.println("Hello");
    }
}

Answer

No. Without parentheses, greet is not a method call, and javac reports error: not a statement. The call must be written greet();.

Question 4

What does this program print?

java
public class Main {

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

    static void lesson() {
        System.out.println("Watch");
        quiz();
    }

    static void quiz() {
        System.out.println("Answer");
    }
}

Answer

text
Watch
Answer
Answer
Watch
Answer

Each lesson() call prints Watch and then calls quiz(). main() also calls quiz() directly between the two lesson() calls, so Answer appears three times.

Common Mistakes

Forgetting () in a Method Call

greet; is not a call, and javac rejects it with error: not a statement (Predict the Result, Question 3). Write greet();.

Misspelling the Method Name

If the method is declared as static void showMenu(), the call showMenus(); fails with error: cannot find symbol. The name in the call must match the declaration exactly, including upper and lower case.

Omitting the Return Type

Wrong:

java
static greet() {
    System.out.println("Hello");
}

javac reports error: invalid method declaration; return type required. A method that returns nothing still needs void: static void greet().

Declaring a Method Inside Another Method

A method declaration belongs in the class body, next to main(), never inside it (see Where Methods Are Declared). Practice Exercise 4 asks you to fix exactly this.

Practice Exercise 1: Greeting Method

Solutions: lesson 2.10.

Write a method static void greet() and call it three times from main(). The method prints:

text
Welcome to Java!

Practice Exercise 2: Extract Duplicate Code

Extract this repeated block into a method named printHeader():

java
System.out.println("----------------");
System.out.println("Java");
System.out.println("----------------");

Practice Exercise 3: Predict the Output

java
public class Main {

    public static void main(String[] args) {
        System.out.println("1");
        first();
        System.out.println("4");
    }

    static void first() {
        System.out.println("2");
        second();
    }

    static void second() {
        System.out.println("3");
    }
}

What will the output be?

Practice Exercise 4: Fix the Program

This program does not compile. Identify the problem and write the correct structure:

<!-- error -->
java
public class Main {

    public static void main(String[] args) {

        static void showMessage() {
            System.out.println("Hello");
        }

        showMessage();
    }
}

Practice Exercise 5: Break into Methods

Divide this program into three methods, showHeader(), showCourses() and showFooter():

java
public class Main {

    public static void main(String[] args) {
        System.out.println("Tarkev");
        System.out.println("----------------");

        System.out.println("1. Java");
        System.out.println("2. Backend");
        System.out.println("3. System Design");

        System.out.println("----------------");
        System.out.println("Learn. Live. Grow.");
    }
}

Knowledge Check

Question 1

What is a method?

Question 2

What is the difference between a method declaration and a method call?

Question 3

What does void mean?

Question 4

Does declaring a method automatically execute it?

Question 5

Can a method be called multiple times?

Question 6

Can one method call another method?

Question 7

Where does execution continue after a called method finishes?

Question 8

Why are meaningful method names useful?

Question 9

Where is a normal Java method declared?

Question 10

Should every statement be placed in a separate method?

Question 11

When is method extraction useful?

Question 12

Is main() a method?

Knowledge Check Answers

Answer 1

A named block of code that performs a specific task or behavior.

Answer 2

A declaration defines what the method does. A call executes the method's code.

Answer 3

The method does not return a result value to the caller.

Answer 4

No. The method must be called.

Answer 5

Yes.

Answer 6

Yes.

Answer 7

Execution continues from the statement after the method call in the calling method.

Answer 8

They communicate what behavior the method performs without requiring the reader to open the implementation.

Answer 9

Inside a class and outside other methods.

Answer 10

No. A method should represent a meaningful responsibility or reusable behavior.

Answer 11

When logic is repeated, a block has a clear purpose, or large code needs to be divided into meaningful parts.

Answer 12

Yes. public static void main(String[] args) is a Java method.

Lesson Summary

In this lesson, we learned:

  • A method is a named block of code for one task; main() is a method too
  • A declaration defines the method, and only a call (greet();, with parentheses) runs it
  • void means the method returns no value, and for now we write helper methods as static
  • After a called method finishes, execution continues with the statement after the call, and methods can call other methods
  • A method declared once can be called many times, which removes duplication
  • Good method names are verb phrases in lowerCamelCase that state intent; not every line deserves its own method
  • Methods are declared side by side inside the class, never inside another method, and their local variables stay inside them

Think first

Coming soon

Checkpoint questions that ask you to commit to an answer before the lesson shows it.