Page 352 - Computer_Science_F5
P. 352
Functions, objects and classes in (iii) Modular design: Functions promote
Java OOP a modular approach, where your
program is built from independent,
Functions reusable components.
(a) Meaning of a function Chapter Five: Object oriented programming with Java
FOR ONLINE READING ONLY
Think of functions as small, specialised (c) Declaration of functions in Java
tools within your program. Each function In Java, methods (also called functions)
handles a particular job, such as computing are like tools within a toolbox (class).
an area, verifying a user’s age, or showing To create a method, you first decide
a message. These functions can be used who can use it (public or private), what
repeatedly in writing code so as to enhance kind of information it might give back
cleanliness and organisation. (return type), and give it a clear name.
You can also give it instructions to work
(b) Importance of using functions with (parameters). Finally, you tell the
There are various benefits of using method what to do (method body),
functions in Java. These benefits includes: and optionally what answer to provide
(i) Code reusability: Instead of (return statement).
writing the same code multiple
times, you can create a function Functions in java can be defined in
and call it whenever you need that several ways:
functionality. This saves time and (i) Public static` keyword: This keyword
effort. combination makes a function to
(ii) Improved readability: By breaking be accessible from other parts of a
down complex tasks into smaller program. This is like opening the
functions, your code becomes door so that a function to be used
easier to understand for both you anywhere in a code, as shown in
and others. Program Example 5.13.
Program Example 5.13:
Java program to demonstrate method call(public static function)
public class MathCalculations {
// This function is declared as public static, making it accessible from other parts of
//the program
public static int add(int num1, int num2) {
return num1 + num2;
}
343
Student’s Book Form Five
Computer Science Form 5.indd 343 23/07/2024 12:34

