Java Methods

Java Methods (Functions)

A method in Java is a block of code that performs a specific task. Methods help reuse code, improve readability, and make programs modular.


1. Syntax of a Method

  • modifierpublic, private, static, etc.

  • returnType → data type returned (void if nothing is returned)

  • methodName → name of the method

  • parameters → optional input values


2. Example 1: Method without Parameters and Return Value


 

📌 Output:

Hello, welcome to Java Methods!

3. Example 2: Method with Parameters


 


4. Example 3: Method with Return Value


 

📌 Output:

Sum = 15

5. Example 4: Method Overloading

Java allows multiple methods with the same name but different parameters (overloading).


 


6. Example 5: Calling One Method from Another


 

📌 Output:

Hello!
Welcome to Java Methods.

🧠 Key Points

  • Methods improve code modularity and reusability.

  • A method can:

    • Take parameters (inputs)

    • Return a value

    • Be called from other methods

  • Use void if the method does not return anything.

  • Overloading allows methods with the same name but different parameters.

You may also like...