Piyush 231302160
Piyush 231302160
231302160
Title: Functions
in OOPs - Java)
JAVA •SYNTAX:
<access_modifier> <return_type>
METHOD
<method_name>( list_of_parameters) {
//body
}
S
Java Methods are blocks of
code that perform a specific
task. A method allows us to
reuse code, improving both
efficiency and organization.
All methods in Java must
belong to a class. Methods
are similar to functions and
expose the behavior of
objects.
KEY COMPONENTS OF A METHOD
DECLARATION
•Modifier: It specifies the method’s access level
(e.g., public, private, protected, or default).
•Return Type: The type of value returned, or
void if no value is returned.
•Method Name: It follows Java naming
conventions; it should start with a lowercase
verb and use camel case for multiple words.
•Parameters: A list of input values (optional).
Empty parentheses are used if no parameters
are needed.
•Exception List: The exceptions the method
might throw (optional).
•Method Body: It contains the logic to be
executed (optional in the case of abstract
methods).
Types of Methods in
1.Predefined Method
Java
Predefined methods are the method that is already defined in the Java
class libraries. It is also known as the standard library method or built-in
method.
Example:
Math.random // returns random value
Math.PI // returns pi value
2.User-defined Method
The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the
requirement.
Example:
sayHello(), sum(), add().
METHOD
CALLING:
Method calling allows to reuse code and organize our program effectively. The
method needs to be called for use its functionality. There can be three situations
when a method is called:
A method returns to the code that invoked it when:
•It completes all the statements in the method.
•It reaches a return statement.
•Throws an exception.
Parameter Passing
There are different ways in which parameter data can be passed into and out of methods and
functions.
Types of parameters:
• Formal Parameter: A variable and its type as they appear in the prototype of
the function or method.
Syntax:
function_name(datatype variable_name)
Syntax:
func_name(variable name(s));
Call By Value:
1. Call by Parameter
(Value)
• In call by value, a copy of the
Definition:
actual parameter is passed to
the function.
• Changes made inside the
function do not affect the
original value.
Call By
Reference
2. Call by Reference
Definition:
• In call by reference, the actual
memory address of the argument
is passed.
• Changes made inside the
function do affect the original
variable.
Recursive • Recursion is a process in which a function
calls itself directly or indirectly is called