Introduction to Java Methods
Methods in Java are reusable blocks of code designed to perform specific tasks. They enhance code reusability, maintainability, and readability. Java provides predefined (built-in) and user-defined methods.
1. Declaring a Method in Java
A method consists of:
- Access Modifier (
public,private, etc.) - Return Type (
void,int,String, etc.) - Method Name (should be meaningful)
- Parameters (optional)
- Method Body (code inside the method)
Syntax:
Example:
2. Types of Methods in Java
2.1 Predefined (Built-in) Methods
Java provides predefined methods like Math.sqrt(), length() for strings, and System.out.println().
Example:
2.2 User-Defined Methods
You can create custom methods based on your needs.
Example:
3. Method Parameters and Return Types
3.1 Method with Parameters
Passing arguments to a method allows it to work dynamically.
Example:
3.2 Method Returning a Value
A method can return data using the return keyword.
Example:
4. Method Overloading
Java allows multiple methods with the same name but different parameters. This is called method overloading.
Example:
5. The main() Method in Java
Every Java program must have a main() method, which acts as the entry point.
Syntax:
Example:
Conclusion
Methods help in writing clean, reusable, and efficient Java programs. In the next post, we will discuss Recursion in Java – How It Works with Examples.
Comments
Post a Comment