Methods and Functions in Java: Reusing Code with Ease
When programming, you often need to reuse code or organize your program into smaller, manageable pieces. That’s exactly what methods (also called functions) are for!
In Java, a method is a block of code that performs a specific task, which you can call whenever needed.
What Is a Method?
A method:
-
Groups related statements together
-
Has a name, parameters (optional), and a return type (or void if no value is returned)
-
Can be called (invoked) from other parts of the program
⚙️ Defining a Method
Here’s the basic syntax:
Example: A simple method that adds two numbers
-
publicis an access modifier (means method can be accessed from other classes) -
intis the return type (the method returns an integer) -
addis the method name -
(int a, int b)are parameters (inputs) -
return sum;returns the result
Calling a Method
To use the method, call it with appropriate arguments:
️ Methods with No Return Value (void)
Sometimes you just want a method to perform an action without returning data.
Call it like this:
Method Overloading
Java allows methods with the same name but different parameter lists — called method overloading.
The compiler decides which method to call based on the argument types.
Access Modifiers (Quick Intro)
-
public: accessible from anywhere -
private: accessible only within the class -
protected: accessible within the package or subclasses
Example: Putting It All Together
Summary
-
Methods organize reusable code blocks
-
Define with return type, name, and parameters
-
Call methods to execute their code
-
Use
voidif no return value -
Method overloading allows multiple versions of a method
