0% found this document useful (0 votes)
4 views

Module1-CC103

This document covers user-defined functions in Java, emphasizing their importance for code abstraction, modularity, and reusability. It explains the definition, declaration, and overloading of functions, along with best practices for their implementation. Additionally, it includes learning activities and programming exercises to reinforce the concepts presented.

Uploaded by

arjaysoberano36
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module1-CC103

This document covers user-defined functions in Java, emphasizing their importance for code abstraction, modularity, and reusability. It explains the definition, declaration, and overloading of functions, along with best practices for their implementation. Additionally, it includes learning activities and programming exercises to reinforce the concepts presented.

Uploaded by

arjaysoberano36
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Module 1 – User-defined Functions

User-defined Functions

1.0 Learning Objectives

 Explain the importance of code abstraction in programming.


 Design the function with proper data sources and return values.
 Analyze the data movements and computations in a program through code
tracing and assess whether those make sense.
 Apply correct coding style on the formulated solutions.

1.1 Introduction

Overview of User-defined Functions in Java


In Java, functions (also known as methods) are blocks of code that perform specific
tasks. While Java provides many built-in methods, user-defined functions allow
developers to create reusable blocks of logic tailored to specific needs, improving code
modularity, readability, and maintainability.
A user-defined function is a method explicitly written by the programmer to carry
out a particular operation. These functions can accept input values (parameters), perform
operations, and return results. By breaking complex problems into smaller, manageable
parts, user-defined functions promote the principles of modularity and code reusability,
key aspects of efficient programming.

1.2 Code abstraction using functions


1.2.1 What is Code Abstraction?
Abstraction in programming is the process of hiding complex implementation details and
exposing only the necessary functionalities to the user. It allows programmers to focus on
what a method does rather than how it does it. In Java, functions (or methods) provide a
primary way to achieve abstraction by breaking down complex operations into smaller,
more manageable pieces of code.
1.2.2 Importance of Code Abstraction
 Simplifies Code Management: Abstracting repetitive tasks into functions prevents
code duplication.
 Enhances Readability: Well-named functions make code easier to understand.
 Improves Maintainability: Changes to logic are easier to implement in a single
function than in multiple places.
 Promotes Reusability: Once defined, functions can be reused across the program.

1.2.3 Defining Functions for Abstraction


 In Java, functions (methods) are defined inside a class. They follow a specific
syntax that allows encapsulating logic.
Syntax:
accessModifier returnType functionName(parameterList) {
// method body
}
Example of a Simple Function:
public int sum(int a, int b) { return a + b; }
This sum function abstracts the addition of two numbers. Any part of the program needing
to add two integers can call sum without repeating the logic.

1.2.4 Example: Using Code Abstraction in a Java Program

Problem Without Abstraction:

public class NoAbstractionExample {


public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Sum: " + (a + b)); // Directly performing
addition
int c = 15, d = 20;
System.out.println("Sum: " + (c + d)); // Repeated addition
logic
}
}

Improved Solution with Abstraction:


public class AbstractionExample {
// Abstracting addition into a reusable function
public int add(int x, int y) {
return x + y;
}

public static void main(String[] args) {


AbstractionExample example = new AbstractionExample();
System.out.println("Sum: " + example.add(5, 10));
// Output: Sum: 15
System.out.println("Sum: " + example.add(15, 20));
// Output: Sum: 35
}
}

1
In the improved example, the add method abstracts the logic of addition, making the
code more readable and reusable.

1.2.5 Real-World Use Cases of Abstraction with Functions

1. Input Validation:
Abstracting input validation logic into a reusable function.

public boolean isValidNumber(int number) {


return number > 0;
}

2. Business Logic Encapsulation:


Encapsulating specific business rules for better maintainability.

public double calculateDiscount(double price, double rate)


{
return price * (1 - rate);
}

3. Mathematical Computations:
Common operations like computing averages or maximum values.

public double average(int[] numbers) {


int sum = 0;
for (int num : numbers) {
sum += num;
}
return (double) sum / numbers.length;
}
1.2.6 Best Practices for Using Abstraction with Functions

1. Use Descriptive Names


The function name should clearly describe its purpose (e.g., calculateSalary
instead of doWork).
2. Follow the Single Responsibility Principle
Each function should do one thing. Avoid combining unrelated tasks in a single
method.
3. Keep Functions Small
Large functions are harder to understand and maintain. Break them into smaller,
specialized functions when possible.
4. Avoid Overusing Global Variables
Functions should rely on their parameters and return values rather than
modifying global variables.

1.3 Function Declaration and Definition


1.3.1 Function Declaration
A function declaration provides the method signature without its implementation. It
informs the compiler or interpreter about the name, return type, and parameters of a
method but does not include the method body.

public int calculateSum(int a, int b);

2
In this example:

 The method calculateSum is declared with a return type of int.


 It takes two integer parameters a and b.
 No body ({}) is provided, so it does not specify what the method does.

In Java, function declarations are commonly used in interface definitions and abstract
classes, where only the method signature is provided, and subclasses or implementing
classes provide the implementation.

Parts of a Java Function/Method Declaration

1. Access Modifier: Specifies the visibility of the method.


Common access modifiers:
o public: Accessible from any other class.
o private: Accessible only within the class where it is declared.
o protected: Accessible within the same package or subclasses.
2. Return Type: Specifies the type of value the method returns.
o If a method does not return any value, the return type is void.
3. Method Name: Identifies the method. Method names follow the camelCase
naming convention.
4. Parameters: Optional. A method can accept parameters, which are values
passed to it. Parameters are specified within parentheses.
5. Method Body: The code that defines the task the method performs, enclosed in
curly braces {}.

1.3.2 Function Definition


A function definition includes both the method signature and its implementation
(method body). It specifies what the function does when it is called.

Example of a Function Definition in Java


public int calculateSum(int a, int b) {
return a + b; // Implementation
}

In this example:

 The method calculateSum has a complete definition.


 The method body { return a + b; } defines the logic for summing two
integers and returning the result.

Examples of Method Definitions

1. Method Without Parameters and No Return Value

public void displayMessage() {


System.out.println("Hello, welcome to Java programming!");
}

2. Method with Parameters and No Return Value

3
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
3. Method with Parameters and a Return Value
public int addNumbers(int num1, int num2) {
return num1 + num2;
}

1.4 Function Overloading


Function overloading (also known as method overloading) is a feature in Java that allows a class
to have multiple methods with the same name but different parameter lists (either by number,
type, or both). It enables methods to perform similar but slightly different tasks based on the
arguments passed.

1.4.1 Key Characteristics of Method Overloading

1. Same Method Name: All overloaded methods share the same name.
2. Different Parameter Lists: Methods must differ in one or more of the following
ways:
o Number of parameters.
o Type of parameters.
o Order of parameters.
3. Return Type: The return type does not differentiate overloaded methods.
Changing only the return type without changing the parameter list will result in a
compilation error.

1.4.2 Example of Method Overloading


public class MathOperations {

// Method with one integer parameter


public int square(int number) {
return number * number;
}

// Overloaded method with one double parameter


public double square(double number) {
return number * number;
}

// Overloaded method with two integer parameters


public int multiply(int a, int b) {
return a * b;
}

// Overloaded method with two double parameters


public double multiply(double a, double b) {
return a * b;
}
}

4
In this example:

 The square method is overloaded to handle both int and double types.
 The multiply method is overloaded to handle both int and double
parameters.

1.4.3 Calling Overloaded Methods


public class TestOverloading {
public static void main(String[] args) {
MathOperations operations = new MathOperations();

System.out.println("Square of 5: " +
operations.square(5)); // Calls square(int)
System.out.println("Square of 5.5: " +
operations.square(5.5)); // Calls square(double)
System.out.println("Product of 3 and 4: " +
operations.multiply(3, 4)); // Calls multiply(int, int)
System.out.println("Product of 3.5 and 4.5: " +
operations.multiply(3.5, 4.5)); // Calls multiply(double,
double)
}
}

1.4.4 Rules for Method Overloading

1. Different Parameter Type: The following example illustrates different parameter


types.

public void display(String text) {


System.out.println(text);
}

public void display(int number) {


System.out.println(number);
}

2. Different Number of Parameters:

public void printInfo(String name) {


System.out.println("Name: " + name);
}

public void printInfo(String name, int age) {


System.out.println("Name: " + name + ", Age: " + age);
}

3. Different Order of Parameters:

public void display(String name, int age) {


System.out.println(name + " is " + age + " years
old.");
}

public void display(int age, String name) {


System.out.println(name + " is " + age + " years
old.");
}

5
1.5 Learning Activities
1.5.1 Multiple Choice:
Directions: Read Each Question Carefully. Ensure you understand the question before
selecting an answer.

1. Which of the following best describes code abstraction in Java?


A. Hiding data from unauthorized users
B. Dividing a large program into smaller, manageable parts using functions or methods
C. Using classes and objects to encapsulate data
D. Using conditional statements to control program flow

2. Why is code abstraction important in Java programming?


A. It makes the code shorter and harder to understand
B. It improves code readability, maintainability, and reusability
C. It allows direct access to private data
D. It prevents object creation in memory

3. Which of the following is a valid example of a method declaration for


abstracting a sum operation?
A. public void sum(int a, int b)
B. int sum(int a, int b) { return a + b; }
C. void sum(a, b)
D. static sum(int a, int b)

4. Which keyword is used to define a method in Java?


A. return
B. void
C. function
D. method

5. What is the correct way to declare a function that takes two integers and
returns their product in Java?
A. int multiply(int a, int b);
B. public int multiply(int a, int b) { return a * b; }
C. void multiply(int a, int b)
D. function multiply(int a, int b) { return a * b; }

6. Which part of a function declaration specifies the return type?


A. The parameter list
B. The method body
C. The name of the function
D. The data type before the function name

7. What is function overloading in Java?


A. Using multiple functions with the same name but different return types
B. Using multiple functions with the same name but different parameter lists
C. Using multiple functions with the same name and the same parameter lists
D. Using nested functions inside another function

8. Which of the following is a valid overloaded method?


A. public void display(int a) and public void display(int b)
B. public int sum(int a, int b) and public int sum(int c, int d)

6
C. public double calculate(int a) and public double calculate(int a, int b)
D. public void print(int a) and public void print(int a)

9. In which scenario does function overloading occur?


A. When multiple functions have the same name and same parameter types but
different bodies
B. When multiple functions have the same name but different numbers or types of
parameters
C. When a function is defined inside another function
D. When a method is declared without a body

10. Which of the following methods demonstrates correct overloading in Java?


A. void print(int a) and void print(String a)
B. int display() and void display()
C. void compute(double x) and void compute(double x)
D. public calculate() and public calculate()

1.5.2 Programming Exercises:

1. Problem: Create a program that calculates the area and perimeter of a rectangle using
separate functions for each operation. Use the algorithm provided below in writing your
program.

Algorithm:

1. Start.
2. Input the length and width of the rectangle.
3. Call the calculateArea(length, width) function.
4. Call the calculatePerimeter(length, width) function.
5. Display the area and perimeter.
6. End.

2. Problem: Write a program that demonstrates function overloading by adding two


integers, two doubles, and three integers. Use the algorithm provided below in writing
your program.

Algorithm:

1. Start.
2. Define multiple sum functions with different parameters.
3. Call sum(int a, int b) and store the result.
4. Call sum(double a, double b) and store the result.
5. Call sum(int a, int b, int c) and store the result.
6. Display the results.
7. End.

3. Problem: Write a program that converts temperature between Celsius and Fahrenheit
using two functions: one for converting from Celsius to Fahrenheit, and the other for
converting from Fahrenheit to Celsius.

Requirements:

 Define a function celsiusToFahrenheit(double celsius) to convert


Celsius to Fahrenheit.

7
 Define a function fahrenheitToCelsius(double fahrenheit) to convert
Fahrenheit to Celsius.
 Take input from the user for the temperature value and unit (Celsius or Fahrenheit).
 Display the converted temperature.

Example Input/Output:

Enter the temperature value: 100


Enter the unit (C for Celsius or F for Fahrenheit): C
Converted temperature: 212.0 Fahrenheit

4. Problem: Write a program that calculates the area of different shapes using function
overloading. Implement functions for:

 circleArea(double radius) for calculating the area of a circle.


 rectangleArea(double length, double width) for calculating the area
of a rectangle.
 triangleArea(double base, double height) for calculating the area of a
triangle.

Requirements:

 Overload the area function with different parameters for different shapes.
 The program should allow the user to choose the shape and input the necessary
values.

Example Input/Output:

Choose a shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 1
Enter the radius of the circle: 5

1.6 References
Ebook - Farrel, J, Java Programming, Course Technology, Cengage Learning
• https://www.javatpoint.com/java-function
• https://www.geeksforgeeks.org/function-overloading-in-programming/
• https://www.dremendo.com/java-programming-tutorial/java-function-overloading

You might also like