OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 11 : Introducing Methods in Java
Unit - 2
Topic - 11 :Introducing Methods in Java
In Java, a method is a block of code that performs a specific task.
Methods make programs modular, reusable, and easy to maintain.
General Form of a Method
Where:
-
type → The data type of the value returned by the method.
-
Can be any valid type, including custom class types.
-
If no value is returned, use
void
.
-
-
name → The name of the method (must be a valid identifier).
-
parameter-list → A list of parameters (type and variable name), separated by commas.
-
If no parameters are needed, leave it empty.
-
-
return value; → Used to send a value back to the caller (for non-void methods).
Example 1: Method Without Return Value
Here, the method volume()
computes and displays the volume of a box directly.
Output:
💡 Note: This method prints the volume directly, which means it cannot be used for calculations elsewhere.
Example 2: Method with Return Value
This improved version of volume()
returns the computed value so it can be used anywhere.
Output:
Key Points
-
Void methods → Perform an action but do not return a value.
-
Return type methods → Return computed values for further use.
-
Modularity → Methods make code organized and reusable.
-
Parameters → Allow passing different values to a method, making it more flexible.
Comments
Post a Comment