Methods, Arrays, and Program Structure
Introduction to Methods
You are viewing a free preview lesson.
Lesson Overview
Java program বড় হতে শুরু করলে একই logic বারবার লিখলে code দ্রুত difficult হয়ে যায়।
Example:
System.out.println("Welcome to LiveKlass!");
System.out.println("Learn Java");
System.out.println("Build real projects");
এখন যদি একই message program-এর বিভিন্ন জায়গায় print করতে হয়, তাহলে একই code বারবার লিখতে হতে পারে।
Methods এই problem solve করে।
A method is a named block of code that performs a specific task।
Methods help us:
- Reuse logic
- Organize programs
- Give meaningful names to behavior
- Reduce duplication
- Break large problems into smaller parts
- Make code easier to test and understand
এই lesson-এ আমরা শিখব:
- What a method is
- Why methods exist
- How to declare a method
- How to call a method
voidmethods- Method execution flow
- Method naming
- Breaking a problem into methods
- Common beginner mistakes
Parameters এবং return values আমরা next lesson-এ বিস্তারিত শিখব।
What Is a Method?
A method is a named block of Java code that performs some work।
Example:
static void greet() {
System.out.println("Welcome to LiveKlass!");
}
Here:
greet
is the method name।
The method contains:
System.out.println("Welcome to LiveKlass!");
When we want this behavior to run, we call the method:
greet();
A 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!
Two Important Parts
A method has two separate concepts:
Method declaration
Method call
Method Declaration
This defines what the method does।
static void greet() {
System.out.println("Welcome!");
}
Method Call
This tells Java to execute the method।
greet();
Declaring a method does not automatically execute it।
Declaration Without Call
public class Main {
public static void main(String[] args) {
System.out.println("Program started");
}
static void greet() {
System.out.println("Hello!");
}
}
Output:
Program started
Why didn't Hello! appear?
Because:
greet();
was never called।
Calling the Method
public class Main {
public static void main(String[] args) {
System.out.println("Program started");
greet();
}
static void greet() {
System.out.println("Hello!");
}
}
Output:
Program started
Hello!
Basic Method Structure
A simple method can look like:
static void methodName() {
// statements
}
Let's break it down।
static
For now, we will often write methods as:
static
because main() is also static, and a static method can directly call another static method in the same class।
We will understand static properly when we study classes and objects।
For now, treat:
static
as part of the method declaration pattern we are using।
void
void
means:
This method does not return a value.
Example:
static void printWelcomeMessage() {
System.out.println("Welcome!");
}
This method performs an action but does not send a result back to its caller।
Return values will be covered in the next lesson।
Method Name
Example:
printWelcomeMessage
Method names should explain the behavior।
Good:
printWelcomeMessage()
showMenu()
calculateTotal()
saveCourse()
validateEmail()
Weak:
doIt()
runThing()
process()
abc()
x()
Good names reduce the need for comments।
Parentheses
Every Java method declaration includes parentheses:
greet()
For now, the parentheses are empty because the method receives no input।
Later:
greet("Sakib")
will pass input into a method।
Curly Braces
The method body exists inside:
{
}
Example:
static void greet() {
System.out.println("Hello!");
System.out.println("Welcome!");
}
Both statements belong to the method।
Calling a Method Multiple Times
One of the simplest benefits 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!
We defined the behavior once and reused it three times।
Why Methods Matter
Imagine this program:
public class Main {
public static void main(String[] args) {
System.out.println("====================");
System.out.println("LiveKlass");
System.out.println("====================");
System.out.println("1. Java");
System.out.println("2. Backend Development");
System.out.println("====================");
System.out.println("LiveKlass");
System.out.println("====================");
}
}
The header is duplicated।
We can extract it into a method।
Refactored Version
public class Main {
public static void main(String[] args) {
printHeader();
System.out.println("1. Java");
System.out.println("2. Backend Development");
printHeader();
}
static void printHeader() {
System.out.println("====================");
System.out.println("LiveKlass");
System.out.println("====================");
}
}
Now:
Header behavior exists in one place.
If the header changes, we update one method।
Methods Help Us Name Intent
Compare:
System.out.println("====================");
System.out.println("LiveKlass");
System.out.println("====================");
with:
printHeader();
The method call tells us immediately:
What is happening?
without needing to inspect every statement।
Methods as Small Tasks
A program can be viewed as a collection of smaller tasks।
Suppose we want a simple enrollment program।
At a high level:
Show welcome message
Show course list
Show enrollment confirmation
We can represent those behaviors as methods:
showWelcomeMessage();
showCourses();
showEnrollmentConfirmation();
Example
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.");
}
}
The main() method now reads like a small sequence of business steps।
Main as Program Entry Point
You've already used:
public static void main(String[] args)
This is itself a method।
The JVM starts a standard Java application by calling this method।
So methods are not a new concept completely।
You have already been working inside one।
main() Is a Method
Break it down:
public static void main(String[] args)
At a high level:
public → access modifier
static → belongs to the class
void → returns no value
main → method name
String[] args → input parameter
We will understand each of these pieces more deeply throughout the course।
Method Execution Flow
Consider:
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()
↓
enter greet
↓
print B
↓
greet finishes
↓
return to main
↓
print C
Method Calls Temporarily Transfer Control
When Java reaches:
greet();
execution temporarily moves into:
static void greet() {
...
}
After the method finishes, execution continues from the line after the method call।
Another Example
public class Main {
public static void main(String[] args) {
first();
System.out.println("Finished");
}
static void first() {
System.out.println("First");
second();
System.out.println("Back in first");
}
static void second() {
System.out.println("Second");
}
}
Output:
First
Second
Back in first
Finished
Trace the Execution
main()
↓
first()
↓
print First
↓
second()
↓
print Second
↓
second() finishes
↓
back to first()
↓
print Back in first
↓
first() finishes
↓
back to main()
↓
print Finished
Understanding this flow becomes very important later when we study:
Exceptions
Recursion
Object method calls
Stack traces
A Method Can Call Another Method
Methods are not limited to being called from main()।
Example:
static void startApplication() {
showLogo();
showMenu();
}
Where:
static void showLogo() {
System.out.println("LiveKlass");
}
static void showMenu() {
System.out.println("1. Courses");
System.out.println("2. Exit");
}
Then:
public static void main(String[] args) {
startApplication();
}
Method Order in the Source File
Java does not require you to declare a method before calling it in the same class।
This works:
public class Main {
public static void main(String[] args) {
greet();
}
static void greet() {
System.out.println("Hello!");
}
}
And Java can resolve the method even though greet() appears below main() in the source file।
Methods Reduce Duplication
Without method:
System.out.println("************************");
System.out.println("JAVA COURSE");
System.out.println("************************");
System.out.println();
System.out.println("************************");
System.out.println("JAVA COURSE");
System.out.println("************************");
With method:
printCourseBanner();
System.out.println();
printCourseBanner();
Declaration:
static void printCourseBanner() {
System.out.println("************************");
System.out.println("JAVA COURSE");
System.out.println("************************");
}
Duplication Is More Than Extra Typing
Duplicated logic creates maintenance risk।
Suppose the title changes from:
JAVA COURSE
to:
JAVA AND OOP FOUNDATION
With duplicated code, you may need to update many places।
If you miss one:
Program becomes inconsistent.
With one method:
static void printCourseBanner() {
System.out.println("JAVA AND OOP FOUNDATION");
}
there is one source of truth for that behavior।
Don't Extract Every Single Line
Methods are useful, but this does not mean every statement requires its own method।
Over-engineered:
static void printA() {
System.out.println("A");
}
static void printB() {
System.out.println("B");
}
static void printC() {
System.out.println("C");
}
if these methods have no meaningful purpose।
Methods should usually represent:
A meaningful task
A reusable behavior
A concept that deserves a name
A complex step worth hiding behind a name
Good Method Boundaries
Suppose:
static void showCourseDetails() {
System.out.println("Course: Java");
System.out.println("Level: Beginner");
System.out.println("Language: Bengali");
}
This is reasonable because the statements together form one concept:
Show course details
Weak Method Boundary
static void printCourseWord() {
System.out.print("Course");
}
If there is no meaningful reuse or semantic reason, extracting such tiny fragments may only make the program harder to navigate।
Method Naming Convention
Java method names usually use:
lowerCamelCase
Examples:
greet()
printHeader()
showCourseList()
calculatePrice()
registerLearner()
Avoid:
PrintHeader()
print_header()
PRINTHEADER()
unless some special API convention requires otherwise।
Use Verb-Based Names
Methods normally perform behavior, so method names are usually verbs or verb phrases।
Good:
printReceipt()
calculateTotal()
findCourse()
validateInput()
sendMessage()
Less clear:
receipt()
total()
course()
input()
message()
There are exceptions, but verb-based naming is a good beginner default।
Boolean-Like Methods
Later, methods that answer yes/no questions often use names such as:
isPublished()
hasLessons()
canEnroll()
containsCourse()
Example:
if (course.isPublished()) {
...
}
This reads naturally।
One Method, One Clear Purpose
Consider:
static void runApplication() {
System.out.println("Welcome");
// calculate prices
// validate email
// create course
// show report
// save files
// send messages
}
This method probably owns too many responsibilities।
Better decomposition might become:
showWelcomeMessage();
createCourse();
registerLearner();
showSummary();
Later, as our applications grow, those behaviors may belong to different classes as well।
Methods and Abstraction
A method can hide lower-level details।
Example:
showMenu();
Caller does not need to know that the method internally prints six lines।
This is a basic form of abstraction:
Expose what the operation means
Hide unnecessary implementation details
Example: Without Abstraction
System.out.println("1. View courses");
System.out.println("2. Enroll");
System.out.println("3. Exit");
With Abstraction
showMenu();
Implementation:
static void showMenu() {
System.out.println("1. View courses");
System.out.println("2. Enroll");
System.out.println("3. Exit");
}
The caller deals with the concept:
show menu
rather than individual print statements।
Method Calls Inside Loops
Methods can be called from control structures।
Example:
for (int i = 0; i < 3; i++) {
printSeparator();
}
Method:
static void printSeparator() {
System.out.println("--------------------");
}
Output:
--------------------
--------------------
--------------------
Method Calls Inside Conditions
if (loggedIn) {
showDashboard();
} else {
showLoginMessage();
}
Methods help make condition branches communicate intent।
Methods and Repeated Workflow
Suppose a program needs to display a separator several times।
Bad:
System.out.println("--------------------");
// logic
System.out.println("--------------------");
// logic
System.out.println("--------------------");
Better:
printSeparator();
// logic
printSeparator();
// logic
printSeparator();
Multiple Methods in One Class
A Java class can contain many methods।
Example:
public class Main {
public static void main(String[] args) {
showWelcome();
showCourses();
showFooter();
}
static void showWelcome() {
System.out.println("Welcome!");
}
static void showCourses() {
System.out.println("Java");
System.out.println("Backend Development");
}
static void showFooter() {
System.out.println("Learn. Live. Grow.");
}
}
Method Scope Preview
Variables created inside a method normally belong to that method's local scope।
Example:
static void showCourse() {
String courseName =
"Java and OOP Foundation";
System.out.println(
courseName
);
}
This will not compile:
public static void main(String[] args) {
showCourse();
System.out.println(
courseName
);
}
because:
courseName
exists only inside:
showCourse()
We will explore scope properly in a later lesson।
Local Variables Are Created During the Method Call
Example:
static void showMessage() {
String message =
"Hello";
System.out.println(
message
);
}
When the method executes, its local variables are used for that invocation।
When the invocation finishes, those local variables are no longer accessible through that method scope।
A Method May Have No Statements
Technically:
static void doNothing() {
}
is valid Java।
Calling:
doNothing();
simply performs no visible work।
This can occasionally be useful during development, but usually a method should exist because it represents some behavior।
Method Calls Require Parentheses
Correct:
greet();
Incorrect:
greet;
A method invocation includes:
method name + parentheses
Don't Confuse Method Declaration and Call
Declaration:
static void greet() {
System.out.println("Hello!");
}
Call:
greet();
A common beginner mistake is trying to write a declaration where a call is expected।
Incorrect:
public static void main(String[] args) {
static void greet() {
System.out.println("Hello");
}
}
Java does not allow defining a normal method inside another method।
Methods Belong to Classes
A method declaration must be inside a class।
Correct:
public class Main {
static void greet() {
System.out.println("Hello");
}
}
Not:
static void greet() {
System.out.println("Hello");
}
public class Main {
}
for a normal top-level Java source structure।
Methods Cannot Normally Be Nested
This is invalid Java:
static void first() {
static void second() {
System.out.println("Hello");
}
}
Declare them separately in the class:
static void first() {
second();
}
static void second() {
System.out.println("Hello");
}
Method Call Stack — Basic Intuition
When one method calls another, Java needs to remember where execution should return।
Conceptually:
main()
calls start()
calls showMenu()
You can imagine a stack of active method calls:
showMenu
start
main
When showMenu() completes, Java returns to start()।
Then when start() completes, Java returns to main()।
We will revisit this concept when learning:
Recursion
Exceptions
Stack traces
Example Execution Stack
public class Main {
public static void main(String[] args) {
start();
}
static void start() {
showMenu();
}
static void showMenu() {
System.out.println("Menu");
}
}
Conceptually during showMenu():
Top
↓
showMenu()
start()
main()
Then methods finish in reverse order।
Why Method Size Matters
A method does not become good merely because it is short।
But extremely long methods often mix multiple responsibilities।
Example:
static void run() {
// 200 lines
}
may be harder to understand than:
static void run() {
showWelcome();
readInput();
processSelection();
showResult();
}
The goal is not:
Make methods as short as possible.
The goal is:
Make each method easy to understand as one coherent operation.
Method Extraction
Turning a piece of logic into a new method is commonly called:
Extract Method
Before:
public static void main(String[] args) {
System.out.println("================");
System.out.println("LiveKlass");
System.out.println("================");
System.out.println("Java Course");
}
After:
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("================");
}
This is one of the most common refactoring techniques in software development।
When Should You Extract a Method?
Useful signals:
The same logic appears multiple times
A group of statements has one clear purpose
A block is difficult to understand
A section deserves a meaningful name
A method is becoming responsible for too much
When Not to Extract
Avoid extraction when it creates meaningless indirection।
Example:
static void printOne() {
System.out.println(1);
}
called once from:
printOne();
may be less clear than simply writing:
System.out.println(1);
unless printOne() represents an actual domain concept।
Example: Course Application
Let's improve a simple program।
First Version
public class Main {
public static void main(String[] args) {
System.out.println("======================");
System.out.println("LiveKlass");
System.out.println("======================");
System.out.println("Available Courses");
System.out.println(
"1. Java and OOP Foundation"
);
System.out.println(
"2. Backend Development"
);
System.out.println("======================");
System.out.println("Thank you");
System.out.println("======================");
}
}
It works, but structure is weak।
Refactored Version
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("Thank you");
System.out.println("======================");
}
}
Now main() expresses the program at a higher level:
Show header
Show courses
Show footer
Methods and Future Changes
Imagine later we add:
Spring Boot
Database
Web API
The implementation may become much more complex।
But the idea remains the same:
Give meaningful operations clear names
and keep responsibilities manageable.
Methods are one of the first tools for doing this।
Common Beginner Mistake 1: Forgetting ()
Incorrect:
greet;
Correct:
greet();
Common Beginner Mistake 2: Forgetting to Call the Method
You write:
static void greet() {
System.out.println("Hello");
}
but nothing appears।
Reason:
The method was declared but never called.
Common Beginner Mistake 3: Calling the Wrong Method Name
Declared:
static void showMenu() {
}
Called:
showMenus();
Compilation fails because:
showMenus
does not exist।
Common Beginner Mistake 4: Defining Method Inside main()
Invalid:
public static void main(String[] args) {
static void greet() {
}
}
Methods belong directly inside the class, not inside another method।
Common Beginner Mistake 5: Missing Return Type
Incorrect:
static greet() {
System.out.println("Hello");
}
A Java method must declare a return type।
For a method returning nothing:
static void greet() {
}
Common Beginner Mistake 6: Using a Variable Outside Its Method
static void createMessage() {
String message =
"Hello";
}
public static void main(String[] args) {
System.out.println(
message
);
}
This fails because message is local to:
createMessage()
Practice 1: Create a Greeting Method
Create:
static void greet()
that prints:
Welcome to Java!
Then call it from main() three times।
Solution
public class Main {
public static void main(String[] args) {
greet();
greet();
greet();
}
static void greet() {
System.out.println(
"Welcome to Java!"
);
}
}
Practice 2: Extract Duplicate Logic
Refactor:
public class Main {
public static void main(String[] args) {
System.out.println("----------------");
System.out.println("Java");
System.out.println("----------------");
System.out.println("Learning...");
System.out.println("----------------");
System.out.println("Java");
System.out.println("----------------");
}
}
Extract the repeated section।
Solution
public class Main {
public static void main(String[] args) {
printHeader();
System.out.println(
"Learning..."
);
printHeader();
}
static void printHeader() {
System.out.println("----------------");
System.out.println("Java");
System.out.println("----------------");
}
}
Practice 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 is the output?
Answer
1
2
3
4
Practice 4: Fix the Program
What is wrong here?
public class Main {
public static void main(String[] args) {
static void showMessage() {
System.out.println("Hello");
}
showMessage();
}
}
Answer
The method declaration is inside main()।
Correct:
public class Main {
public static void main(String[] args) {
showMessage();
}
static void showMessage() {
System.out.println("Hello");
}
}
Practice 5: Break a Program into Methods
Take this program:
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.");
}
}
Refactor it into:
showHeader()
showCourses()
showFooter()
Possible Solution
public class Main {
public static void main(String[] args) {
showHeader();
showCourses();
showFooter();
}
static void showHeader() {
System.out.println("LiveKlass");
System.out.println("----------------");
}
static void showCourses() {
System.out.println("1. Java");
System.out.println("2. Backend");
System.out.println("3. System Design");
}
static void showFooter() {
System.out.println("----------------");
System.out.println("Learn. Live. Grow.");
}
}
True or False
- Declaring a method automatically executes it.
- A method can be called more than once.
voidmeans the method returns no value.- A normal Java method can be declared inside
main(). - A method can call another method.
- Methods can reduce duplicated logic.
- Every single Java statement should have its own method.
- Method names should communicate intent.
main()is itself a method.- Execution returns to the caller after a method finishes.
Answers
1. False
2. True
3. True
4. False
5. True
6. True
7. False
8. True
9. True
10. True
Knowledge Check
Question 1
What is a method?
Question 2
What is the difference between method declaration and method call?
Question 3
What does void mean?
Question 4
Why do methods help reduce duplication?
Question 5
Can one method call another method?
Question 6
What happens after a called method finishes?
Question 7
Where are normal methods declared in Java?
Question 8
Why are meaningful method names important?
Question 9
Should every small statement automatically become a method?
Question 10
Why might we extract part of a long method into another method?
Knowledge Check Answers
Answer 1
A method is a named block of code that performs a specific task or behavior।
Answer 2
Declaration defines what the method does; calling the method causes that code to execute।
Answer 3
void means the method does not return a result value to its caller।
Answer 4
Repeated logic can be defined once in a method and reused from multiple places।
Answer 5
Yes. Methods can call other methods।
Answer 6
Execution continues from the point immediately after the method call in the caller।
Answer 7
Normal methods are declared inside a class and outside other methods।
Answer 8
A meaningful name tells readers what behavior is being performed without requiring them to inspect implementation details first।
Answer 9
No. Methods should represent useful responsibilities or abstractions rather than creating unnecessary indirection।
Answer 10
To improve readability, isolate a meaningful task, reduce duplication, or keep responsibilities manageable।
Lesson Summary
এই lesson-এ আমরা methods-এর foundation শিখেছি।
A method is:
A named block of behavior.
আমরা শিখেছি:
- Methods program organization improve করে
- Methods duplicated logic reduce করে
- Method declaration এবং method call আলাদা concepts
- Declaring a method automatically execute করে না
- A method can be called repeatedly
voidmeans no return value- Methods can call other methods
- Execution returns to the caller after a method finishes
- Java methods normally belong inside classes
- Methods cannot normally be nested inside other methods
- Local variables belong to method scope
- Meaningful method names communicate intent
- Extracting methods can simplify large blocks of code
- Too many meaningless tiny methods can also hurt readability
main()itself is a Java method- Method calls create the foundation for understanding call stacks, recursion, exceptions, and object behavior later
The central idea is:
A program should not be one giant sequence of statements.
Break meaningful behavior into named methods.
Next Lesson
পরবর্তী lesson:
Parameters, Arguments, and Return Values
আমরা শিখব:
- Passing data into methods
- Parameters vs arguments
- Multiple parameters
- Returning values
return- Return types
- Using returned values
- Early return
- Designing useful method signatures