Smarter Code: Methods and Reusability

By now, you've written code that takes input, makes decisions, and repeats actions. But if your code is starting to feel messy or repetitive, you’re not alone. That’s where methods come in — your next superpower.

Why Do We Need Methods?

Imagine having to copy-paste the same few lines of code every time you need to do something. Not only is that boring, but it also makes your program harder to fix or update. Methods let you:

What Is a Method?

A method is a block of code that performs a specific task. You define it once, and you can use (or "call") it as many times as you like. Java methods have four main parts:

Example:

method structure

This method takes a String and prints a greeting.

Calling a Method

Once a method is defined, you can call it from main or another method:

method call example

Return Types

Not all methods just do something — some return values.

return type example

Now you can do:

return type call example

If a method doesn’t return anything, use void as the return type. Example:

void method example

This method does something but doesn’t return a value. You can call it like this:

void method call example

Parameters vs Arguments

Example:

parameters and arguments example

Organizing Code with Methods

Instead of cramming everything inside main(), break your logic into methods:

organizing methods example

This way:

Common Mistakes

Practice Time!

Write methods for:

Adding two number
Converting Celsius to Fahrenheit
Checking if a number is even
Printing a star pattern
Returning the larger of two numbers

Then, call them from your main() method!

What’s Next

You’re now writing cleaner, smarter code. Next up, you’ll learn how Java uses objects and classes to model real-world things and build even more powerful programs. Get ready for Object-Oriented Programming (OOP)!