Functions in Java
In Java, functions (more correctly called methods) are blocks of code that perform a specific task. They help in code reusability, modularity, and readability.
✅ What is a Function/Method in Java?
A method in Java is a block of code that:
-
Has a name
-
Can take input (parameters)
-
May return a value
-
Is called (invoked) when needed
πΉ Syntax of a Method
πΉ Types of Methods in Java
-
Predefined methods – like
System.out.println()
,Math.sqrt()
-
User-defined methods – you define these based on your requirements
πΈ Example 1: Method without Parameters and without Return Value
πΈ Example 2: Method with Parameters
πΈ Example 3: Method with Return Value
πΉ Key Components of a Method
Component | Description |
---|---|
returnType | Type of value the method returns (e.g., int , void ) |
methodName | Name of the method (should be meaningful) |
parameters | Input values (optional) |
return | Used to return value from method (if not void) |
πΉ Method Overloading (Same name, different parameters)
π Best Practices
-
Method names should be verbs and start with lowercase.
-
Keep methods short and do one thing well.
-
Use static if the method doesn't need to access instance variables.
Comments
Post a Comment