0% found this document useful (0 votes)
18 views7 pages

SPM Unit5

This document provides an overview of functions and methods in Java, explaining their definitions, types, and usage. It covers predefined and user-defined methods, function declaration, definition, parameter passing, and returning values. Additionally, it discusses the advantages of using methods, memory allocation for method calls, and the concept of recursive functions.

Uploaded by

Vinit Pansuriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

SPM Unit5

This document provides an overview of functions and methods in Java, explaining their definitions, types, and usage. It covers predefined and user-defined methods, function declaration, definition, parameter passing, and returning values. Additionally, it discusses the advantages of using methods, memory allocation for method calls, and the concept of recursive functions.

Uploaded by

Vinit Pansuriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT 5 INTRODUCING FUNCTIONS

→ A Java Method is a collection of statements that performs some specific task and return the
result to the caller.
→ A function is a block of code that can be reused throughout a program. It can take input
parameters and return a value.
→ Methods are used to perform certain actions, and they are also known as Functions.
→ A Java method can perform some specific task without returning anything.
→ In Java, every method must be part of some class.
→ A method is a block of code which only executes (runs) when it is called.
→ You can pass data, known as parameters, into a method.
→ Functions are a powerful tool for organizing and reusing code in Java. By using functions, you can
make your code more readable, maintainable, and reusable.

Types of Methods in Java


There are two types of methods in Java:
1. Predefined Method
These are built-in methods in Java that are available to use.
2. User-defined Method
We can create our own method based on our requirements.

5.1 Inbuilt functions


5.2 User defined functions
5.2.1 Function declaration, definition and function calling
5.2.2 Passing parameter to functions
5.2.3 Returning values from functions

5.1 INBUILT FUNCTIONS

→ In Java, any method that is already defined in the Java class libraries (JCL) is known as predefined
methods.
→ It is also known as the standard library method or inbuilt method.
→ The predefined methods are ready-to-use methods, we can directly use these methods just by
calling them in the program at any point.
→ There are several built-in methods in java that are easily and directly accessible.
→ These methods are from java standard libraries which can be Java Class Libraries (JCL) inside the
java archive file with JVM and JRE.
→ There are numerous predefined methods, such as length(), sqrt(), max(), and print(), and each of
them is defined inside their respective classes.
Prepared by : Prof. Lavleena Stephens
How to use Predefined Methods in Java

→ When we invoke a Java predefined method, a block of code(already defined in the library)
associated with that method runs behind the scene and produces the output accordingly.
→ In Java, every predefined method belongs to some specific class. For example, the length() method
belongs to the Java String class, the print() method belongs to the PrintStream class, and so on.

5.2 USER DEFINED FUNCTIONS

→ Java programming allows us to create our own methods where we can specify our own logic
depending upon the specific task. Such types of methods are referred to as user-defined methods.
→ These methods can be modified by the user or programmer according to their requirement.
→ Moreover, there are specific rules that need to be followed while creating a user-defined method.
→ It is possible to modify and tweak these methods according to the situation.

5.2.1 FUNCTION DECLARATION, DEFINITION AND FUNCTION CALLING

FUNCTION DECLARATION
→ A function declaration tells the compiler about the function's name, return type, and parameters
(if any).
→ In general, function declarations have 6 main components:
• Access Modifier
• Return Type
• Method Name
• Parameter list
• Exception list
• Method body
1. Modifier: It defines the access type (scope) of the function i.e. from where it can be accessed in
your application. It is Optional in syntax. In Java, there 4 types of access specifiers:
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its subclasses
private: It is accessible only within the class in which it is defined.
default: It is declared without using any modifier. It is accessible within the same class and
package within which its class is defined.
2. Return type: The data type of the value returned by the function or void if does not return a
value. It is Mandatory in syntax.
3. Function Name: It specifies the name of the function. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their data
type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect thrown by the function. It is Optional in syntax.
6. Function body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.
Prepared by : Prof. Lavleena Stephens
→ General syntax of a function declaration :
modifier return_type function_name ( parameter-list )

Rules to name a Function:


• While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
• If the method name has more than two words, the first name must be a verb followed by an
adjective or noun.
• In the multi-word method name, the first letter of each word must be in uppercase except the
first word. For example, findSum, computeMax, setX, and getX.

FUNCTION DEFINITION
→ A function definition provides the implementation of the function's code.
→ A function must be defined within a class.
→ General syntax of a function definition :
modifier return_type function_name ( parameter-list ) {
// function_body (logic)
return value;
}
→ Example :
public int max (int x, int y)
{
if (x > y)
return x;
else
return y;
}

2 Ways To Create Functions in Java


1. Instance Method (Non static method):
→ Access the instance data using the object name.
→ Declared inside a class.
→ Syntax:
void method_name(){
body //instance area }
2. Static Method:
→ Access the static data using class name.
→ Declared inside class with static keyword.
→ Syntax:
static void method_name(){
body //static area }

FUNCTION CALLING
→ The method needs to be called for use its functionality.
→ To call a function, simply write its name followed by parentheses and any required parameters,
with a semicolon at the end.

Prepared by : Prof. Lavleena Stephens


5.2.2 PASSING PARAMETER TO FUNCTIONS

→ Generally, the programming languages use pass by value and pass by reference for passing
parameters to a method.
→ However, Java does not support both approaches rather it uses pass by value to pass both primitive
and reference type values. Thus, Java is strictly pass by value.
→ Let us assume that a function B() is called from another function A(). In this case A is called
the “caller function” and B is called the “called function or callee function”.
→ Also, the arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.
→ The parameters that appear in the function definition are called formal parameters. And, the
parameters that appear in the function call statement are called actual parameters.
→ For example, if we have a variable ‘x’ with a value of 10, and we pass ‘x’ as a parameter to a
method, then the method receives a copy of original value 10 as its parameter.
→ Since reference variables are stored in stack, therefore, for reference types such as arrays, objects
and strings the value of the parameter is the reference or address of the given variable. For
example, if we have an array ‘arr’ with elements {1, 2, 3} and we pass ‘arr’ as a parameter to a
method, then the method receives the copy of reference or address of ‘arr’ as its parameter.

METHODS OF PARAMETER PASSING

Pass by Value
→ In this way of passing parameters, a copy of parameter value is passed to the given method. That
method can modify the copy, but it cannot affect the original value of the parameter.
→ This means that any changes that the function makes to the parameter will not be reflected in the
original parameter.

Pass by Reference

→ In this way of passing parameters, a reference or an address of the parameter is passed to the given
method. That method can modify the original value of the parameter by using the reference.
→ This means that any changes that the function makes to the parameter will be reflected in the
original parameter.
→ In Java, all primitive types are passed by value and all reference types (objects, arrays) are passed
by reference.

Parameters vs Arguments

Parameters − are the named variable passed during the method definition and serve as a placeholder for
arguments. They import the arguments into the specified method. They allow a method to be generalized.
Here, generalized means we can reuse a single method with various data according to the needs.

Arguments − are the actual values that are passed during the time of method call. They must match the type
of parameter passed in the method definition.

Prepared by : Prof. Lavleena Stephens


5.2.3 RETURNING VALUES FROM FUNCTIONS

→ We can let a method return a value, using the return statement.


→ Return type can be :
1. void
2. non-void
→ The word void means “empty” and because it has been used Java is not expecting anything to
return from the method.
→ To change the return type from a void to non-void, the word void should be replaced with int,
double, or char, etc.
→ When Java hits the return keyword it exits out of the method and returns back to main() void.

EXAMPLES :

Prepared by : Prof. Lavleena Stephens


IMPORTANT POINTS

• Every Java method must be within a class.


• Static methods belong to a class while non-static methods belong to objects.
• All parameters to functions are ‘passed by value’, primitives content is copied, while objects are not
copied and are ‘passed by reference’.

Advantages of Methods :
• Code Reusability: Methods allow you to write code once and use it many times, making your
code more modular and easier to maintain.
• Abstraction: Methods allow you to abstract away complex logic and provide a simple
interface for others to use. This makes your code more readable and easier to understand.
• Improved readability: By breaking up your code into smaller, well-named methods, you can
make your code more readable and easier to understand.
• Encapsulation: Methods allow you to encapsulate complex logic and data, making it easier to
manage and maintain.
• Separation of concerns: By using methods, you can separate different parts of your code and
assign different responsibilities to different methods, improving the structure and
organization of your code.
• Improved modularity: Methods allow you to break up your code into smaller, more
manageable units, improving the modularity of your code.
• Improved testability: By breaking up your code into smaller, more manageable units, you can
make it easier to test and debug your code.
• Improved performance: By organizing your code into well-structured methods, you can
improve performance by reducing the amount of code that needs to be executed and by
making it easier to cache and optimize your code.

Note: Methods are time savers and help us to reuse the code without retyping the code.

EXTRA POINTS
Memory Allocation for Method Calls
• A stack is used to implement the method calls. A stack frame is created within the stack area
whenever we call or invoke a method.

• After that, the local variables, the arguments passed to the method and value which is returned by
this method, all are stored in this stack frame. This allocated stack frame gets deleted when the
called method gets executed.

Recursive Function
In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion.
A physical world example would be to place two parallel mirrors facing each other. Any object in between
them would be reflected recursively.

Prepared by : Prof. Lavleena Stephens


Example :
class Factorial {
static int factorial( int n ) { // recursive function
if (n != 0)
return n * factorial(n-1); // recursive call
else
return 1;
}
public static void main(String[] args) {
int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}

Function Declaration vs Function Definition


Features Declaration Definition
Definition Declarations are used to give The definition identifies the code or data
program names, including functions, connected with the function, class, variable,
variables, namespaces, and classes. etc.
Variable or The variable or function may be The variable or function can be defined only
Function declared multiple times. once.
Memory It doesn't allocate memory to the It allocates memory to an entity.
Allocation entities.
Scope The scope of a variable, function, The scope in the definition refers to the time.
object, class or enumeration in a
declaration describes its visibility.
Repetition Once an entity has been defined, the Even if you define an entity, redeclaration is
definition procedure cannot be always feasible at any given time.
repeated indefinitely.

Prepared by : Prof. Lavleena Stephens

You might also like