Methods, Arrays, and Program Structure

Introduction to Methods

ReadingPreview

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:

System.out.println("====================");
System.out.println("LiveKlass");
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.

Using methods, we can:

  • Reuse repeated logic
  • Divide a large program into smaller tasks
  • Clearly express the intent of code
  • Reduce duplication
  • Make a program easier to read and maintain

In this lesson, we will learn:

  • What a method is
  • Method declaration
  • Method call
  • void methods
  • Basic use of static
  • Method execution flow
  • Method naming
  • Method reuse
  • Dividing a program into methods
  • Common method-related mistakes

We will learn about parameters and return values 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.

Example:

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

Here:

greet

is the method name.

The method body:

{
    System.out.println(
            "Welcome to LiveKlass!"
    );
}

contains the work performed by the method.

Method Call

Declaring a method does not execute it.

To run the method's behavior, you must call it:

greet();

Complete example:

public class Main {

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

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

Output:

Welcome to LiveKlass!

Method Declaration and Method Call

These are two different concepts.

Declaration

Defines what the method does:

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

Call

Tells Java to execute the method:

greet();

Declaring a Method Does Not Run It

public class Main {

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

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

Output:

Program started

Hello! is not printed.

Why?

Because:

greet();

was never called.

Method Structure

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

static void methodName() {
    // Statements
}

Example:

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:

static void greet() {
}

This allows us to call a method in the same class directly from main():

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.

Example:

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

This method performs an action:

Print a message

but it does not return a value.

Return values will be covered in the next lesson.

Method Name

A method name should describe its behavior.

Good:

showMenu()
printHeader()
showCourses()
displayResult()

Weak:

doIt()
thing()
abc()
x()

A meaningful name helps the reader understand what the method is going to do.

Method Naming Convention

Java method names generally use lowerCamelCase.

Good:

showMenu()
printWelcomeMessage()
displayCourseList()

Avoid:

ShowMenu()
show_menu()
SHOWMENU()

Verb-Based Names

Methods usually represent actions.

Therefore, a verb or verb phrase is a good default.

Examples:

printHeader()
showCourses()
displayResult()
calculateTotal()
validateInput()

In this lesson, we are focusing on action-based methods without parameters or return values.

Parentheses

A method declaration has parentheses after the method name:

greet()

In this lesson, the parentheses are empty:

greet()

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:

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

Both statements are part of the greet() method.

Calling a Method Multiple Times

One major benefit of methods is reuse.

public class Main {

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

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

Output:

Hello!
Hello!
Hello!

The method is declared once but called three times.

Methods Reduce Duplication

Without a method:

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

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

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

The header is duplicated.

Refactored Version

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(
                "LiveKlass"
        );

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

Now the header logic exists in one place.

Methods Make Intent Clearer

Compare these examples.

Without a method:

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

With a method:

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 this code from the beginning:

public static void main(String[] args)

This is also a method.

When a standard Java application starts, the JVM begins execution from:

main()

High-level breakdown:

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

We will study some of these pieces in more detail later.

Method Execution Flow

Example:

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:

A
B
C

Execution flow:

main starts
↓
Print A
↓
Call greet()
↓
Print B
↓
greet() finishes
↓
Continue in main
↓
Print C

What Happens When a Method Is Called?

When Java sees:

greet();

execution moves to the body of the greet() method.

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

When the method finishes, execution continues in the calling method from the statement after the method call.

One Method Can Call Another Method

public class Main {

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

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

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

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

Execution:

main()
↓
startApplication()
↓
showLogo()
↓
showMenu()

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

This code is valid:

public class Main {

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

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

Even though the greet() declaration appears after main(), Java can resolve the method.

Dividing a Program into Small Tasks

Suppose a program needs to:

Show welcome message
Show course list
Show enrollment confirmation

We can write:

public class Main {

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

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

    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:

Welcome
→ Courses
→ Confirmation

One Method, One Clear Purpose

A method should ideally represent one coherent task.

Reasonable:

static void showCourseDetails() {
    System.out.println(
            "Course: Java"
    );

    System.out.println(
            "Level: Beginner"
    );

    System.out.println(
            "Language: Bangla"
    );
}

All of these statements represent one concept:

Show course details

Not Every Line Needs a Method

Over-complicated:

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.

Before:

public class Main {

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

        System.out.println("Java Course");
    }
}

After:

public class Main {

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

        System.out.println(
                "Java Course"
        );
    }

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

Now the intent of main() is clearer.

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

Example:

static void showCourse() {
    String courseName =
            "Java and OOP Foundation";

    System.out.println(
            courseName
    );
}

This variable:

courseName

is accessible only within the local scope of the method.

Invalid:

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

    System.out.println(
            courseName
    );
}

We will study variable scope in more detail later.

Methods Are Declared Inside a Class

Correct:

public class Main {

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

The method declaration appears inside the class body.

A Method Cannot Be Declared Inside Another Method

Invalid:

public static void main(String[] args) {

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

Correct:

public class Main {

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

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

Common Mistakes

Forgetting () in a Method Call

Wrong:

greet;

Correct:

greet();

Declaring a Method but Never Calling It

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

This does not execute by itself.

Call it:

greet();

Wrong Method Name

Declared:

static void showMenu() {
}

Wrong:

showMenus();

The method name must match exactly.

Declaring a Method Inside Another Method

Wrong:

public static void main(String[] args) {

    static void showMessage() {
    }
}

Keep method declarations at the class level.

Omitting the Return Type

Wrong:

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

Correct:

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

Using a Local Variable Outside Its Method

static void createMessage() {
    String message = "Hello";
}

Invalid:

System.out.println(message);

if that code appears in another method.

Complete Example

public class Main {

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

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

        System.out.println(
                "LiveKlass"
        );

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

    static void showCourses() {
        System.out.println(
                "Available Courses"
        );

        System.out.println(
                "1. Java and OOP Foundation"
        );

        System.out.println(
                "2. Backend Development"
        );
    }

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

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

main() now clearly shows the program structure:

showHeader()
showCourses()
showFooter()

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.

Practice Exercise 1: Greeting Method

Write a method:

static void greet()

that prints:

Welcome to Java!

Then call it three times from main().

Practice Exercise 2: Extract Duplicate Code

Extract this repeated block into a method:

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

Method name:

printHeader()

Practice Exercise 3: Predict the Output

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

Identify the problem:

public class Main {

    public static void main(String[] args) {

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

        showMessage();
    }
}

Write the correct structure.

Practice Exercise 5: Break into Methods

Divide this program into three methods:

showHeader()
showCourses()
showFooter()

Original:

public class Main {

    public static void main(String[] args) {
        System.out.println("LiveKlass");
        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 behavior
  • Methods help organize code
  • Methods can reuse repeated logic
  • Method declaration and method call are different
  • A declared method does not execute automatically
  • Parentheses are required when calling a method
  • void means the method does not return a result value
  • At this stage, we write helper methods as static
  • A method can be called multiple times
  • One method can call another method
  • When a called method finishes, execution returns to the caller
  • Meaningful method names communicate program intent
  • Methods help divide large programs into smaller tasks
  • Not every statement needs to become a method
  • Method declarations appear inside a class
  • A normal method cannot be declared inside another method
  • A local variable is not accessible outside its method scope
  • main() is itself a method