0% found this document useful (0 votes)
15 views106 pages

CCPRGG2L Course Manual-1

The document is a course manual for CCPRGG2L - Intermediate Programming, which builds on foundational programming principles and focuses on Java programming to solve complex problems. It covers topics such as Java syntax, control flow, data types, and real-world applications of Java, along with practical exercises for students. The course aims to enhance students' programming skills, analytical abilities, and problem-solving expertise.
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)
15 views106 pages

CCPRGG2L Course Manual-1

The document is a course manual for CCPRGG2L - Intermediate Programming, which builds on foundational programming principles and focuses on Java programming to solve complex problems. It covers topics such as Java syntax, control flow, data types, and real-world applications of Java, along with practical exercises for students. The course aims to enhance students' programming skills, analytical abilities, and problem-solving expertise.
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/ 106

VER 1.

Course

MANUAL
CCPRGG2L – INTERMEDIATE PROGRAMMING
This course advances the foundational principles covered in CCPRGG1L - Fundamentals of Programming, concentrating on
the application of general-purpose programming to solve complex computational problems. It emphasizes equipping
students with the competencies to design, implement, test, and debug programs that address diverse computing
challenges through fundamental programming constructs. Through this course, students will develop strong programming
practices, analytical skills, and problem-solving expertise, adopting the critical thinking needed for success in the
programming field.

Julie Anne A. Crystal


Jesfer M. dela Cruz
Elsie V. Isip
Marizkays P. Jamison
Cyruz RJ W. Robles
Jensen A. Santillan
Leonila B. Valdez
CCPRGG2L – Intermediate Programming
Table of Contents

01 Topic 1
Introduction to Java
Setting Up Java Development Environment
Java Syntax and Structure

02 Topic 2
Basic I/O Operations
Basic Programming

03 Topic 3
Control Flow Statements
Conditional Statements
Decision Making Statements

04 Topic 4
Arrays

05 Topic 5
Introduction to Class and Methods
Exception handling and Debugging

06 Topic 6
File Handling and I/O Operations
Intermediate Programming

Module 1

Learning Outcomes:

• Explain the purpose, origin, and evolution of the


Java programming language.
• Identify the unique features and benefits of Java as
a programming language.
• Define Java, its primary features, and its historical
significance in the programming world.
• Trace the key milestones in Java’s development
and discuss how it has evolved over time.
• Identify real-world applications of Java,
emphasizing its versatility across industries.
Intermediate Programming

INTRODUCTION TO JAVA

Java is a high-level, class-based, object-oriented programming


language that is designed to have as few implementation
dependencies as possible.

It is a general-purpose programming language that follows the


principle of "write once, run anywhere" (WORA).

This means that compiled Java code can run on all platforms that
support Java without the need for recompilation.

Java was developed by James Gosling, Mike Sheridan, and Patrick


Naughton at Sun Microsystems (which has since been acquired by
Oracle Corporation) in 1991.

The language was initially called "Oak" after an oak tree that stood
outside Gosling's office.

It was later renamed "Java" after the Indonesian coffee.


Intermediate Programming

MILESTONE OF JAVA

1991: The project was initiated by James Gosling and the Green Team at Sun
Microsystems. It was originally designed for interactive television, but it was
too advanced for the digital cable television industry at the time.
1995: Java was officially launched. The first public implementation was Java
1.0, which was released with the slogan "Write Once, Run Anywhere"
(WORA). This version provided a stable environment for developers to write
code that could be executed on any machine that had the Java Runtime
Environment (JRE).
1997: The Java Development Kit (JDK) 1.1 was released, which included
significant updates like the JDBC API, the JavaBeans component model, and
inner classes.
1999: Sun Microsystems released Java 2 (also known as J2SE 1.2), marking the
beginning of the three-edition platform: J2SE (Java 2 Standard Edition), J2EE
(Java 2 Enterprise Edition), and J2ME (Java 2 Micro Edition). This version
introduced the Swing graphical API and the Collections framework.
2004: Java 5.0 (formerly known as J2SE 1.5) was released, introducing major
updates like generics, metadata, enumerated types, and the enhanced for
loop.
2006: Sun Microsystems released Java under the GNU General Public License
(GPL), making it free and open-source software. This led to the development
of the OpenJDK, an open-source implementation of the Java platform.
2009: Oracle Corporation acquired Sun Microsystems, and with it, Java.
Oracle continues to develop and support Java.
2014: Java 8 was released, which included features like lambda expressions,
the Stream API, and the new date and time API.
2017: Oracle announced that Java would switch to a new release cadence,
with new versions being released every six months. This led to the rapid
introduction of features in subsequent versions.
Intermediate Programming

MILESTONE OF JAVA

Present: Java continues to evolve, with the latest versions introducing new
features and enhancements. The language is still widely used in various
domains, including web development, mobile applications, and large-scale
enterprise systems.

It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection

.
Intermediate Programming

REAL WORLD APPLICATION OF JAVA

Java is used in various domains due to its versatility and platform


independence.

Here are some examples of real-world applications:

Web Applications: Java is extensively used for building server-side


applications. Frameworks like Spring, Hibernate, and Struts are
commonly used in web development.

Enterprise Applications: Java is widely used in large-scale enterprise


systems due to its robustness, scalability, and security features. Java
EE (now Jakarta EE) is specifically designed for building distributed,
multi-tiered, transactional applications.

Mobile Applications: Most Android applications are either written


in Java or use Java as one of the core languages.

Big Data Technologies: Java is used in big data technologies like


Apache Hadoop, Apache Spark, and others.

Scientific Applications: Java is used in various scientific applications


for data processing, mathematical calculations, and simulations.
Gaming: Java is used in developing 2D and 3D games, as well as
mobile games.

Cloud Computing: Java is used in cloud computing platforms like


AWS, Google Cloud, and Azure for developing scalable and
distributed systems.
Intermediate Programming

INSTALL AND SET UP

To start programming in Java, you need to set up your development


environment. This involves installing the Java Development Kit (JDK) and
setting up an Integrated Development Environment (IDE) for writing and
running Java code.
1. Downloading and Installing JDK
1. Visit the Oracle JDK Download Page: Go to the official Oracle website or
OpenJDK to download the latest version of the JDK.
2. Choose the Appropriate Version: Select the appropriate JDK version based
on your operating system (Windows, macOS, or Linux).
3. Install the JDK:
1. For Windows:
1. Download the installer (.exe file).
2. Run the installer and follow the instructions.
3. The installer will automatically set up the JDK and configure
the necessary environment variables.
2. For macOS:
1. Download the .dmg file.
2. Open the .dmg file and drag the JDK package to the
Applications folder.

3. For Linux:You can install OpenJDK using the package manager.


For example, on Ubuntu, you can use the following command:
sudo apt update
sudo apt install openjdk-17-jdk
Intermediate Programming

SETTING UP PATH ENVIRONMENT


To run Java programs from the command prompt, you need to set up the
PATH environment variable.
1. Locate the JDK Installation Directory: The default installation directory is
usually C:\Program Files\Java\jdk-<version>.
2. Set the PATH Variable:
1. Open the Start menu and search for "Environment Variables."
2. Click on "Edit the system environment variables."
3. In the System Properties window, click on "Environment Variables."
4. Under "System Variables," find and select the Path variable, then
click "Edit."
5. Click "New" and add the path to the bin directory inside the JDK
installation folder (e.g., C:\Program Files\Java\jdk-<version>\bin).
6. Click "OK" to save the changes.
3. Verify the PATH Configuration: Open a new command prompt window
and type javac -version. If the PATH is configured correctly, it will display the
Java compiler version.

INSTALLING IDE
While you can write Java code in a simple text editor, using an Integrated
Development Environment (IDE) greatly enhances productivity.
Popular Java IDEs include:

• Eclipse: A widely used, open-source IDE with powerful features for Java
development.
• IntelliJ IDEA: A popular IDE from JetBrains, known for its advanced code
editing and refactoring features.
• NetBeans: Another open-source IDE that is easy to use and comes with
built-in support for Java SE, Java EE, and more.
Intermediate Programming

INSTALLATION STEPS
Installation Steps:

1. Download the IDE: Visit the official website of the IDE and download the
installer for your operating system.
2. Install the IDE: Run the installer and follow the instructions to complete
the installation.
3. Set Up the IDE:
1. Configure the IDE to use the installed JDK.
2. Create a new Java project to get started with Java programming.
Intermediate Programming

WRITING & RUNNING A SIMPLE


JAVA PROGRAM

Open your IDE and create a new Java project.

Create a New Java Class:


• Name the class HelloWorld.
• Write the following code in the HelloWorld.java file:

CODE:

OUTPUT:
Intermediate Programming

JAVA SYNTAX AND STRUCTURE

Basic Structure of a Java Program

• Main method: Every Java application must have a main() method


that acts as the entry point.
• public static void main(String[] args)
• This method is executed when the Java application starts

public: The method is accessible from outside the class.


static: Allows the method to run without creating an instance of the
class.
void: The method does not return any value.
String[] args: Command-line arguments passed to the program.
ASSESSMENT TASK

ACTIVITY FOR PRACTICE


Writing and Running Your First Java Program
Objective:
• To understand how to write, compile, and run a basic Java program using an IDE or an online compiler.
Materials Required:
• A computer with Java Development Kit (JDK) installed.
• Java Integrated Development Environment (IDE) or an online Java compiler (e.g., JDoodle, Programiz).
Step 1: Write the following code in the HelloWorld.java file:

Step 2: Writing the Java Program


• Open the IDE or the online compiler. Create a new Java file:
1. In an IDE:
2. Create a new project.
3. Right-click on the source folder and create a new Java Class file.
4. Name it HelloWorld.
• In an online compiler:
• Create a new Java project and name the file HelloWorld.java.
Step 3: Saving the Program
• In IDE: Save your file by selecting File > Save or pressing Ctrl + S.
• In Online Compiler: The file usually saves automatically, but ensure you save the file if the option is available.
Step 4: Compiling and Running the Program
• In IDE:
• Click on the "Run" button (usually a green triangle icon).
• The IDE will automatically compile the program and run it.
• In Online Compiler:
• Click on the "Run" button in the interface.
• The code will be compiled and executed.

Step 5: Viewing Output


• Once the program runs, you should see the following output in the console:
ASSESSMENT TASK

ACTIVITY FOR PRACTICE

Java Syntax and Structure

Expected Output:
Intermediate Programming

Module 2

Learning Outcomes:

• Demonstrate the use of basic input and output


operations in Java to interact with users.
• Define and differentiate between Java data types,
including primitive and reference types.
• Declare, initialize, and manipulate variables using
appropriate data types.
• Utilize arithmetic, relational, logical, and
assignment operators to perform calculations and
make decisions within a Java program.
Intermediate Programming

JAVA VARIABLES & DATA TYPES

Introduction to Variables

In Java, variables act as containers to store data that can be referenced and
manipulated in a program. Each variable has a specific type, determining the
kind of data it can hold.

Syntax:
To declare a variable, specify the data type, followed by the variable name.

Initialization:
Variables can be initialized when they are declared or later in the code
Intermediate Programming

JAVA VARIABLES & DATA TYPES

Java Data Types


Java is a statically-typed language, meaning each variable must have a type
defined at compile time.

Java has two primary data types:


Primitive Data Types and Reference Data Types.

• Primitive Data Types:

• byte: 1 byte, used for small numbers (range: -128 to 127).


• short: 2 bytes, suitable for slightly larger numbers (range: -32,768
to 32,767).
• int: 4 bytes, most commonly used integer type (range: -2^31 to
2^31-1).
• long: 8 bytes, for larger integer values (use L suffix for literals, e.g.,
long bigNumber = 123456789L;).
• float: 4 bytes, single-precision floating point (use F suffix, e.g., float
pi = 3.14F;).
• double: 8 bytes, double-precision floating point, default for decimal
values.
• char: 2 bytes, stores a single Unicode character.
• boolean: 1 bit, holds true or false.

• Reference Data Types:

• These include classes, interfaces, and arrays, such as String, arrays


(int[]), and custom classes.
• Unlike primitives, they store references to objects rather than the
object itself.
Intermediate Programming

VARIABLE SCOPE & LIFETIME

Scope: The section of the code where a variable can be accessed.

• Local Variables: Declared within a method and accessible only within that
method.
• Instance Variables (Fields): Declared within a class but outside any method.
They belong to the instance of the class.
• Class Variables (Static Fields): Declared with the static keyword and shared
across all instances of the class.

Lifetime: The period during which a variable occupies memory. Local


variables are deleted after method execution, while instance and class
variables persist as long as the object or class exists.
Intermediate Programming

JAVA OPERATORS

Operators allow us to perform operations on variables and values. Java


provides a variety of operators, grouped into categories.

Arithmetic Operators
Used for mathematical calculations, including:
• Addition (+), Subtraction (-), Multiplication (*), Division (/),
Modulus (%).

EXAMPLE:

Assignment Operators

Used to assign values to variables. The = operator is the basic assignment


operator.

Compound Assignment Operators: These combine an operation with


assignment, e.g., +=, -=, *=, /=.
Intermediate Programming

JAVA OPERATORS

Comparison Operators

Used to compare values, returning a boolean result (true or false).


• Equal to (==), Not equal to (!=), Greater than (>), Less than (<),
Greater than or equal to (>=), Less than or equal to (<=).

EXAMPLE:

Logical Operators

Used to combine multiple conditions, returning a boolean result.


• AND (&&): Returns true if both conditions are true.
• OR (||): Returns true if at least one condition is true.
• NOT (!): Inverts the boolean value.
Intermediate Programming

JAVA OPERATORS

Increment and Decrement Operators

Increment (++) and Decrement (--) are used to increase or decrease a


variable by 1.
• Prefix (e.g., ++x): Increments the value before use in an expression.
• Postfix (e.g., x++): Increments the value after use in an expression.
EXAMPLE:

Logical Operators

Used to combine multiple conditions, returning a boolean result.


• AND (&&): Returns true if both conditions are true.
• OR (||): Returns true if at least one condition is true.
• NOT (!): Inverts the boolean value.
Intermediate Programming

BASIC INPUT AND


OUTPUT OPERATION

OUTPUT OPERATIONS

EXAMPLE:
CODE:

OUTPUT:
Intermediate Programming

BASIC INPUT AND


OUTPUT OPERATION

OUTPUT OPERATIONS:
EXAMPLE CODE:

OUTPUT:
Intermediate Programming

BASIC INPUT AND


OUTPUT OPERATION

INOUT OPERATIONS:
Using the Scanner Class
To read input, you first need to import the Scanner class from the java.util package.

Step-by-Step Guide to Using Scanner:


1. Import the Scanner class:
2. Create a Scanner object to read input:
EXAMPLE CODE:

Use various methods to read input (depending on the type of input required).
Intermediate Programming

BASIC INPUT AND


OUTPUT OPERATION

EXAMPLE CODE:
Intermediate Programming

BASIC INPUT AND


OUTPUT OPERATION

EXAMPLE CODE:
ASSESSMENT TASK

ACTIVITY FOR PRACTICE

Declare and Initialize Variables: Try using different data


types (int, double, char, boolean).

Arithmetic Calculations: Perform calculations using


arithmetic operators.

Conditional Expressions: Use comparison and logical


operators to print a message based on certain conditions.

Increment/Decrement Exercise: Experiment with prefix


and postfix increment operators to observe differences in
behavior
ASSESSMENT TASK

ACTIVITY FOR PRACTICE


Variables, Data Types and Operations

This sample introduces students to:


• Basic data types and variable usage.
• Arithmetic operations.
• String concatenation.

Variables and Data Types:

• int (integer): Stores whole numbers (e.g., age = 20).


• double: Stores decimal numbers (e.g., height = 5.9).
• char: Stores single characters (e.g., grade = 'A').
• boolean: Stores true/false values (e.g., isStudent = true).
• String: Stores sequences of characters (e.g., name = "Alice").

Operations:
• Arithmetic operations (addition, subtraction, multiplication, and division) are performed on integers.
• String concatenation (+ operator) combines two strings.
ASSESSMENT TASK

ACTIVITY FOR PRACTICE


Expected Output:

Basic Input and Output Operations

• Basic input and output operations using the Scanner class for input and
System.out.println for output:
ASSESSMENT TASK

LABORATORY ACTIVITY 1
Instructions:

• Open a Java Integrated Development Environment (IDE).


• Create a new Java project and name it "BasicJava".
• Create a new Java class and name it "BasicJavaActivity".
• Copy the following code into the "BasicJavaActivity" class:

What to Do:

• Run the program by clicking the "Run" button or pressing Shift+F6.


• Enter your name, age, and height when prompted.
• Observe the output displayed on the console.
• Modify the program to perform additional calculations using operators (e.g., addition,
subtraction, multiplication, division).
• Experiment with different data types (e.g., char, boolean, float).
• Use System.out.printf() to format output with precision and padding.
ASSESSMENT TASK

LABORATORY ACTIVITY
Questions to Answer:

• What is the purpose of the Scanner class in Java?


• How do you declare a variable in Java?
• What is the difference between System.out.print() and
System.out.println()?
• How do you perform calculations using operators in Java?

Assessment:

• Run the program and verify that it works correctly.


• Answer the questions above.
• Modify the program to perform additional calculations
using operators.
• Submit your modified program and answers to the
questions for review.
ASSESSMENT TASK

LABORATORY ACTIVITY 2
Activity Title: "Grocery Store Calculator"

Objective:
• Use basic input and output in Java.
• Declare and initialize variables.
• Perform basic arithmetic operations with operators.

Instructions:

Scenario:
You are creating a simple program that acts as a grocery store calculator. The user will input the
prices of three items, and the program will calculate the total cost and apply a discount.

Steps:
• Input:
The program will prompt the user to input the prices of three grocery items using Scanner.
• Variables:
Declare variables to store the prices of the three items. Also, create a variable to hold the
total cost and the discounted price.
• Operators:
Use the addition operator to compute the total cost of all three items.
If the total cost is greater than 500, apply a 10% discount to the total.
• Output:
Display the original total cost before the discount.
If the discount applies, display the final price after applying the 10% discount.

EXAMPLE PROGRAM FLOW:


ASSESSMENT TASK

LABORATORY ACTIVITY 2

Requirements:

• Create a program using Java's Scanner class to handle user input.


• Declare variables for each of the three item prices.
• Use arithmetic operators to compute the total cost and check if the total is above the discount
threshold (500).
• Output the original total, and if applicable, the discounted total.

Deliverables:

• Submit a working Java program that compiles and runs without errors. Take screenshot of all the codes
and output.
• Add functionality where the user can also input the quantity of each item, and the total cost will
account for quantities as well.

STARTER CODE:
Intermediate Programming

Module 3

Learning Outcomes:

• Describe and differentiate between various control


structures in Java, including sequential, selection, and
looping constructs.
• Apply control flow statements to determine the flow of
execution in Java programs, using a structured approach.
• Construct decision-making logic to handle multiple
outcomes in a program, enhancing program versatility.
• Design loops to handle a variety of scenarios, such as
iterating through collections or performing tasks until a
condition is met.
Intermediate Programming

CONDITIONAL STATEMENT

Control statements in Java allow the flow of execution to be controlled


within a program.

These statements help in making decisions, repeating tasks, or branching


execution paths based on conditions.

Java control statements:

1. Decision-Making Statements
2. Looping (Iteration) Statements

These statements evaluate a condition (boolean expression) and execute

blocks of code depending on whether the condition is true or false.

if Statement
• The simplest decision-making statement. Executes a block of code if the
condition is true.

if (condition) {
// Code to be executed if the condition is true
}

int age = 18;


if (age >= 18) {
System.out.println("You are an adult.");
}
Intermediate Programming

CONDITIONAL STATEMENT
These statements evaluate a condition (boolean expression) and execute blocks

of code depending on whether the condition is true or false.

else if Ladder
• Allows testing multiple conditions in sequence. The first true condition's block
gets executed, and the rest are skipped.

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if all conditions are false
}

int marks = 85;


if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 80) {
System.out.println("Grade: A");
} else {
System.out.println("Grade: B");
}
Intermediate Programming

LOOPING STATEMENT

Looping allows executing a block of code multiple times based on A condition.

while Loop
• Executes a block of code as long as the condition is true.

while (condition)
{
// Code to execute repeatedly
}
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}

do-while Loop
Similar to while loop, but it guarantees that the block of code is executed at
least once, because the condition is checked after the block is executed.

do {
// Code to execute
} while (condition);

.
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
Intermediate Programming

LOOPING STATEMENT
Looping allows executing a block of code multiple times based on a condition.

for Loop
Used when you know exactly how many times you want to loop through a
block of code..

for (initialization; condition; update)


{
// Code to execute repeatedly
}
for (int i = 1; i <= 5; i++)
{
System.out.println("Count: " + i);
}

Enhanced for Loop (for-each loop)


Used to iterate over elements of an array or a collection.

for (dataType variable : array)


{
// Code to execute for each element
}

int[] numbers = {10, 20, 30, 40};

for (int number : numbers)


{
System.out.println(number);
}
Intermediate Programming

SWITCH STATEMENT

A multi-way branch statement that selects a block of code to execute based


on the value of an expression.

switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}

int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Intermediate Programming

BRANCHING STATEMENT
Branching statements are used to transfer control from one part of the

program to another.

break Statement
Exits from a loop or switch statement.

for (int i = 1; i <= 5; i++) {


if (i == 3)
{
break; // Exit the loop when i is 3
}
System.out.println(i);

return Statement
Exits from the current method and returns a value (if the method is not
void).

public class Example {


public static void main(String[] args) {
System.out.println(add(5, 10));
}

public static int add(int a, int b) {


return a + b; // Returns the sum of a and b
}
}
Intermediate Programming

BRANCHING STATEMENT

continue Statement
Skips the current iteration of the loop and proceeds to the next iteration.

for (int i = 1; i <= 5; i++)


{
if (i == 3) {
continue; // Skip the iteration when i is 3
}
System.out.println(i);
}
ASSESSMENT TASK

ACTIVITY
TASK 1: CONDITIONAL STATEMENTS

Exercise 1: Simple Conditional Statement

Write a Java program that prompts the user to enter their age and then displays
a message indicating whether they are eligible to vote or not as a person must
be at least 18 years old to vote.
ASSESSMENT TASK

ACTIVITY
Exercise 2: Conditional Statement with Multiple Conditions

Write a Java program that prompts the user to enter their score on a test
and then displays a message indicating their grade based on the following
criteria:
A: 90-100
B: 80-89
C: 70-79
D: 60-69
F: below 60
ASSESSMENT TASK

ACTIVITY

Exercise 3: Nested Conditional Statements

Write a Java program that prompts the user to enter their age and income and
then displays a message indicating whether they are eligible for a loan based on
the following criteria:

Age: at least 21 years old


Income: at least $30,000 per year
ASSESSMENT TASK

ACTIVITY
Exercise 4: Conditional Statement with Logical Operators

Write a Java program that prompts the user to enter their height and weight
and then displays a message indicating whether they are underweight,
normal weight, or overweight based on the following criteria:
Underweight: BMI < 18.5
Normal weight: BMI >= 18.5 and BMI < 25
Overweight: BMI >= 25
ASSESSMENT TASK

ACTIVITY
Exercise 5: Conditional Statement with Switch Statement

Write a Java program that prompts the user to enter their favorite color and
then displays a message indicating the corresponding color code based on the
following criteria:

Red: #FF0000
Green: #00FF00
Blue: #0000FF
Yellow: #FFFF00
Other: Unknown color
ASSESSMENT TASK

ACTIVITY
TASK 2: LOOPING CONSTRUCTS

EXERCISE 6:
For Loop Example: Print Numbers 1 to This for loop starts at 1 and increments by
1 until it reaches 10, printing each number along the way.

EXERCISE 7:
While Loop Example: Print Even Numbers Less than 20. This while loop runs as
long as number is less than 20, printing even numbers and increasing by 2 each
time.
ASSESSMENT TASK

ACTIVITY

EXERCISE 8:
Do-While Loop Example: Print "Hello" 5 TimeS.
The do-while loop ensures the code inside the loop is executed at least
once before checking the condition. This example prints "Hello" five times.
Intermediate Programming

Module 4

Learning Outcomes:

• Understand the concept of arrays and their significance


in storing multiple values of the same data type in a
single structure.
• Describe the memory allocation and indexing system
used in arrays, distinguishing between single-
dimensional and multi-dimensional arrays.
• Recognize scenarios where arrays are beneficial for
organizing and managing data.
Intermediate Programming

ARRAYS
An array is a data structure that allows you to store multiple values of the
same type in a single variable.

Arrays are useful for handling large sets of data efficiently and are widely
used in programming.

Characteristics of Arrays

• Fixed size: Once declared, the size of the array cannot be changed.
• Same type: All elements in an array must be of the same type.
• Indexed access: Array elements are accessed using an index, starting at 0.

Syntax of Arrays
Intermediate Programming

ARRAYS

EXAMPLE CODE:
Intermediate Programming

ARRAYS
Types of Arrays

1. One-Dimensional Array
A simple list of elements:

A one-dimensional array is essentially a list of elements, all of the same data


type, organized in a single row. Think of it as a straight line of values.

Characteristics
• Stores a sequence of elements.
• Accessed using a single index (starting from 0).
• Ideal for linear data like scores, prices, or names.
Intermediate Programming

ARRAYS

Example Code
Intermediate Programming

ARRAYS
Types of Arrays
2. Two-Dimensional Array
A grid or table of elements:

Accessing elements:

A two-dimensional array is like a table or matrix. It consists of rows and


columns, where each element is identified using two indices: one for the row
and one for the column.

Characteristics
• Represents data in tabular form.
• Accessed using two indices: array[row][column].
• Useful for data like grids, matrices, or board games (e.g., chess).
Intermediate Programming

ARRAYS

Example Code
Intermediate Programming

ARRAYS
Real-World Example

Storing Student Grades

Arrays are a foundational data structure in Java that allow for efficient
data storage and manipulation. Mastering arrays is essential for
solving more complex problems and understanding advanced data
structures.
Intermediate Programming

ARRAYS
Key Differences Between
One-Dimensional and Two-Dimensional Arrays
ASSESSMENT TASK

ACTIVITY
Activity: Exploring 1D and 2D Arrays in Java

Objective
• Understand the structure and functionality of 1D and 2D arrays in Java.
• Practice accessing, modifying, and traversing arrays.

Instructions
1. Problem 1: One-Dimensional Array
Write a program to do the following:
1. Create an array of integers to store 5 student scores.
2. Ask the user to input the scores (use Scanner).
3. Calculate and display the average score.
4. Find and display the highest score.
5. Find and display the lowest score.

EXAMPLE INPUT/OUTPUT:
ASSESSMENT TASK

ACTIVITY
2. Problem 2: Two-Dimensional Array
Write a program to do the following:
1. Create a 3x3 2D array to store integers.
2. Fill the 2D array with multiplication table values (e.g., row * column).
3. Print the array in matrix format.

3. Problem 3: Enhanced Two-Dimensional Array


Extend the program from Problem 2:
1. Calculate the sum of all elements in the 2D array.
2. Find and display the largest value in the array.

EXAMPLE OUTPUT:
ASSESSMENT TASK

ACTIVITY
Array Activities for Java

1. Activity: Reverse a One-Dimensional Array


Task:
Write a program that:
1. Prompts the user to enter 5 numbers.
2. Stores these numbers in an array.
3. Reverses the order of elements in the array.
4. Prints both the original and reversed arrays.

2. Activity: Find Duplicates in a One-Dimensional Array


Task:
Write a program that:
1. Accepts 10 integers from the user.
2. Stores them in an array.
3. Identifies and displays any duplicate numbers in the array.
ASSESSMENT TASK

ACTIVITY
3. Activity: Row and Column Sum in a Two-Dimensional Array
Task:
Write a program that:
1. Initializes a 3x3 matrix with integer values.
2. Calculates the sum of each row and each column.
3. Prints the matrix along with the row and column sums.

4. Activity: Search in a Two-Dimensional Array


Task:
Write a program that:
1. Initializes a 4x4 matrix with random integers between 1 and 100.
2. Prompts the user to enter a number to search.
3. Searches for the number in the matrix and returns its location (row, column)
if found, or a message indicating it wasn’t found.
ASSESSMENT TASK

ACTIVITY
5. Activity: Transpose of a Matrix
Task:
Write a program that:
1. Creates a 3x3 matrix and fills it with values.
2. Finds and displays the transpose of the matrix (rows and columns
swapped).

6. Activity: Sorting Elements in a One-Dimensional Array


Task:
Write a program that:
1. Takes 7 numbers as input from the user.
2. Sorts the numbers in ascending order.
3. Displays the sorted array.
Intermediate Programming

Module 5

Learning Outcomes:

Understand the concepts of classes and objects and apply


them to define and create classes in Java.
• Differentiate between methods and constructors and use
them effectively in Java programming.
• Understand the basics of debugging and error handling and
apply debugging techniques to identify and fix issues in Java
programs.
• Implement exception handling strategies to manage
runtime errors and improve program reliability.
• Identify and differentiate between types of exceptions and
apply best practices for effective exception handling in Java.
Intermediate Programming

INTRODUCTION TO
CLASS AND METHODS

What is a Class?

• A class is a blueprint or template that defines the structure and behavior


(methods) of objects.

• It consists of:

• Attributes (also called fields or variables) - Define the properties.


• Methods - Define the behaviors or actions.
Intermediate Programming

INTRODUCTION TO
CLASS AND METHODS

What is a Method?

• A method is a block of code within a class that performs a specific task.


• It is similar to a function in other programming languages.

• Benefits:
• Code reusability.
• Improved readability and modularity.

What is an Object?

• An object is an instance of a class.


• Objects are created using the new keyword.
Intermediate Programming

INTRODUCTION TO
CLASS AND METHODS
Understanding Classes and Objects

1. Class:
1. Think of it as a template or blueprint (e.g., a "Car").
2. Contains attributes (e.g., color, model) and methods (e.g., drive,
brake).
2. Object:
1. The actual instance created from the class (e.g., a specific car,
"Honda Civic").
Intermediate Programming

DEFINING AND CREATING


CLASSES AND OBJECTS
Defining a Class
A class is defined using the class keyword.

Example:

Creating an Object
Objects are created using the new keyword.

Example:
Intermediate Programming

CREATING METHODS

Types of Methods

Instance Methods:
Belong to an object and are called using the object reference.

Example:

Static Methods:
Belong to the class and can be called without creating an object.

Use the static keyword.


Intermediate Programming

METHODS STRUCTURE

• Modifiers: public, private, static, etc.


• Return Type: void, int, String, etc.
• Method Name: Follows camelCase naming.
• Parameters: Optional values the method accepts.

Example Usage :Calling the Method


Intermediate Programming

Example Program with Classes, Objects, and Methods


ASSESSMENT TASK

ACTIVITY
Activity: Create a Simple "Student" Class

Objective:
• Understand how to define a class.
• Learn how to create objects.
• Implement methods to interact with the object’s data.

Instructions:

1. Define the Student Class:


1. The class should have the following attributes (fields):
1. name (String)
2. age (int)
3. studentID (String)
2. Add the following methods:
1. Constructor to initialize the name, age, and studentID.
2. Method introduce() to print out the student’s details (name, age,
and student ID).
3. Method isAdult() to return a boolean value: true if the student is 18
or older, false otherwise.
2. In the Main class:
1. Create at least two student objects with different values for name, age,
and studentID.
2. Call the introduce() method for each student.
3. Call the isAdult() method and print the result.
ASSESSMENT TASK

PROGRAMMING CHALLENGE
This activity combines the topics of classes and objects, methods and constructors, instance
vs. static variables, and method overloading.

Activity: Library Management System

Objective:

Design a simple library management system that allows them to manage books and
members. Create classes, utilize constructors and methods, and differentiate between
instance and static variables.

Instructions:
Class Design:
Class: Book
Attributes:
title (String)
author (String)
isbn (String)
isAvailable (boolean)

Methods:
Constructor to initialize the book details.
displayInfo(): Prints the book's title, author, ISBN, and availability status.
checkOut(): Marks the book as checked out (sets isAvailable to false).
returnBook(): Marks the book as available (sets isAvailable to true).

Class: LibraryMember
Attributes:
name (String)
memberId (String)
booksCheckedOut (int)

Methods:
Constructor to initialize member details.
checkOutBook(): Increments booksCheckedOut and displays a message.
returnBook(): Decrements booksCheckedOut and displays a message.
ASSESSMENT TASK

ACTIVITY

Class: Library
Attributes:
libraryName (String)
books (ArrayList<Book>) to hold the list of books
Static variable totalBooks to count the total number of books in the library

Methods:
Constructor to initialize the library name.
addBook(Book book): Adds a book to the library and increments totalBooks.
displayBooks(): Displays all books in the library.
getTotalBooks(): Returns the total number of books.

Implementation:
In the main method, create an instance of the Library.
Create several Book objects and add them to the library using addBook().
Create a few LibraryMember objects and allow them to check out and return books.

Demonstrate the following:


Display all available books.
Display total books in the library.
Show the current number of books checked out by a member.

Challenge:
Implement method overloading in the Book class:
Add a method displayInfo(String format) that takes a format parameter (e.g., "full" or
"short") to display book info differently based on the format.

Assessment Criteria:
Correct implementation of classes and methods.
Proper use of instance and static variables.
Clarity and organization of code.
Creativity in the challenge.
Intermediate Programming

ACTIVITY

SAMPLE OUTPUT:
Intermediate Programming

INTRODUCTION TO
DEBUGGING
AND
ERROR HANDLING

Debugging and error handling are essential practices in software


development to ensure that programs behave correctly, even when
faced with unexpected situations.

In Java, debugging helps developers find and fix issues, while error
handling ensures that programs can handle exceptions gracefully
without crashing.
Intermediate Programming

DEBUGGING

Debugging is the process of identifying and resolving issues or bugs in the code.

Java provides several tools and techniques to debug programs effectively.

Steps for Debugging:


1. Understand the Problem:
1. Reproduce the bug consistently.
2. Understand the expected behavior and actual outcome.
2. Use Debugging Tools:
1. Modern Integrated Development Environments (IDEs) like IntelliJ IDEA,
Eclipse, and NetBeans offer built-in debugging tools.
2. These tools help step through the code, inspect variable values, and
monitor program flow in real time.

3. Common Debugging Techniques:


1. Print Statements: Insert System.out.println() statements to print variable
values or track where the code is executing.
2. Breakpoints: Set breakpoints in an IDE to pause the program execution at
a specific line and inspect the state of the program at that point.
3. Step Through Code: After setting breakpoints, step through the code line
by line to observe how it behaves and identify where things go wrong.
Intermediate Programming

ERROR HANDLING

• An exception is an event that disrupts the normal flow of a program.

• In Java, exceptions are objects that represent these errors.

• When an error occurs, an exception object is created, and the normal

flow of the program is interrupted.

Java provides robust error handling mechanisms to deal with


exceptions (unexpected events) and ensure that programs don’t crash
or behave unpredictably

Java provides a powerful mechanism to handle exceptions using try,

catch, and finally blocks.

try Block:
• The code that might throw an exception is placed inside the try
block.
• If an exception occurs, the control is immediately transferred to
the appropriate catch block.
Intermediate Programming

ERROR HANDLING

catch Block:
• The catch block contains code that handles the exception.
• You can have multiple catch blocks to handle different types of exceptions.

finally Block:
• The finally block is always executed, regardless of whether an exception
occurs or not.
• It's often used to release resources such as files or database
connections.
Intermediate Programming

ERROR HANDLING
Multiple catch Blocks:
Java allows you to catch multiple exceptions by using multiple catch blocks or
by using multi-catch syntax in a single block.

Throwing Exceptions Using throw and throws

throw Keyword:
•You can manually throw exceptions using the throw keyword.
Intermediate Programming

ERROR HANDLING

Throwing Exceptions Using throw and throws

throws Keyword:
• The throws keyword is used in method signatures to declare the exceptions
that a method might throw.
•.
Intermediate Programming

ERROR HANDLING
TYPES OF EXCEPTION

Checked Exceptions:

• Checked exceptions are exceptions that are checked at compile time.


• The programmer must handle these exceptions (either with try-catch or by
declaring them with throws).

Examples:

• IOException
• SQLException
• FileNotFoundException

Unchecked Exceptions (Runtime Exceptions):

• Unchecked exceptions occur at runtime and are not checked at compile


time.
• These exceptions generally result from programming errors like
accessing an array out of bounds or dividing by zero.

Examples:

• NullPointerException
• ArrayIndexOutOfBoundsException
• ArithmeticException
Intermediate Programming

ERROR HANDLING

BEST PRACTICE FOR EXCEPTION HANDLING

• Catch specific exceptions: Always try to catch specific exceptions


rather than using a generic Exception class.

• Use meaningful messages: When throwing exceptions, provide a


clear and informative error message.

• Avoid overusing exceptions: Exceptions should only be used for


exceptional conditions, not for control flow.

• Release resources: Always release resources (e.g., file streams or


database connections) in a finally block or use the try-with-resources
statement.

• Log exceptions: Log exceptions using proper logging frameworks


such as Log4j or java.util.logging instead of printing stack traces to
System.out.
Intermediate Programming

ERROR HANDLING

SUMMARY

Debugging helps developers identify and resolve issues in their code, often

using breakpoints and logging.

Error Handling ensures programs continue to run smoothly even when

unexpected situations arise. Java uses the try, catch, and finally constructs

for handling exceptions.

Checked Exceptions are caught at compile time, while

Unchecked Exceptions occur at runtime.Using proper exception handling

techniques ensures that the application behaves predictably and prevents

crashes due to unexpected events.


ASSESSMENT TASK

ACTIVITY

DEBUGGING AND ERROR HANDLING

EXERCISE 1: Program: Calculator Program with Error Handling

• Java program that acts as a simple calculator, allowing users to perform


basic arithmetic operations (addition, subtraction, multiplication, and
division) on two numbers.
• The program should handle errors and exceptions properly. Use a try-catch
block to handle errors and exceptions that may occur during the
calculation. Display the result of the calculation or an error message if an
exception occurs.

Example Output:

Input: num1 = 10, num2 = 2, operation = /

Output: Result: 5.0

Input: num1 = 10, num2 = 0, operation = /

Output: Error: Division by zero is not allowed.

Input: num1 = 10, num2 = abc, operation = +

Output: Error: Invalid input. Please enter a valid number.


ASSESSMENT TASK

ACTIVITY
ASSESSMENT TASK

PROGRAMMING CHALLENGE

Problem : Bank Account Management System:

Write a Java program that simulates a simple Bank Account Management System. The
program should allow users to create a new account, deposit money, withdraw money,
and check their account balance. The program should handle errors and exceptions
properly. Use Scanner to get input from the users and System.out.println to display the
output. Remember to handle errors and exceptions properly using try-catch blocks and
informative error messages.

Instructions:
• Create a Java program that prompts the user to create a new account by entering
their name and initial balance.
• Use a try-catch block to handle errors and exceptions that may occur during the
account creation, deposit, and withdrawal operations.
• Implement the following methods:
o createAccount: creates a new account with the given name and initial balance.
o deposit: adds money to the account balance.
o withdraw: subtracts money from the account balance.
o checkBalance: displays the current account balance.
• Handle the following errors and exceptions:
o Invalid account name (e.g., empty string or null)
o Insufficient balance for withdrawal
o Negative deposit or withdrawal amount
o Any other unexpected errors

Sample Output:
Create account: John, 1000
Deposit: 500
Balance: 1500
Withdraw: 200
Balance: 1300
Withdraw: 1500 (insufficient balance)
Error: Insufficient balance for withdrawal.
Intermediate Programming

Module 6

Learning Outcomes:

• Understand the importance of file handling in Java for


reading, writing, and managing data in files.
• Perform basic file operations, such as creating, renaming,
and deleting files or directories.
• Identify and handle common exceptions in file handling,
such as FileNotFoundException, IOException, and
EOFException.
• Write data to a file using character-based and byte-based
streams, demonstrating control over output formatting and
content.
• Read data from a file and process it in a Java program,
handling both character-based and line-based input.
Intermediate Programming

INTRODUCTION TO
FILE HANDLING
File handling in Java allows programs to create, read, write, and
manipulate files stored on the file system.

Java provides the java.io and java.nio packages to facilitate file handling.
These packages include classes and methods for working with files and
directories efficiently.

Files are commonly used to store and retrieve data in a persistent


manner. Whether you're reading a configuration file, writing logs, or
saving user data, file handling is essential for many Java applications.

KEY CLASSES FOR FILE HANDLING IN JAVA

File Class:
• The File class is part of the java.io package and provides an abstraction for
file and directory names.
• It allows you to perform operations like checking if a file exists, creating or
deleting files and directories, and getting file properties (size, permissions,
etc.).

• Note: The File class does not read or write data to the file; it's used for file
management.

FileReader and BufferedReader:


• These classes are used for reading data from files. FileReader reads
character data, while BufferedReader improves efficiency by buffering the
input.
Intermediate Programming

INTRODUCTION TO
FILE HANDLING
FileWriter and BufferedWriter:
• These classes are used for writing data to files. FileWriter writes character
data, while BufferedWriter improves efficiency by buffering the output.

PrintWriter:
• This class provides an easy way to write formatted text to files (like System.out
for console output).

Scanner:
• The Scanner class can be used to read data from a file as well as parse input
(e.g., integers, doubles, strings).

Files (Java NIO):


• The Files class in the java.nio.file package provides static methods to work
with file I/O operations. It's more efficient and has additional functionality
compared to the traditional java.io classes.
Intermediate Programming

BASIC FILE OPERATIONS

Creating a File
To create a file in Java, you use the File class and its createNewFile()
method. This method returns true if the file was successfully created, or
false if the file already exists.
Intermediate Programming

BASIC FILE OPERATIONS

Writing to a File
You can write data to a file using FileWriter or BufferedWriter. Here's an
example of writing text to a file:
Intermediate Programming

BASIC FILE OPERATIONS

Reading from a File


You can read data from a file using FileReader and BufferedReader or by
using a Scanner. Here's an example of reading text from a file:
Intermediate Programming

BASIC FILE OPERATIONS

Appending to a File
To append text to an existing file without overwriting it, you can
pass true as the second parameter to the FileWriter constructor.
Intermediate Programming

BASIC FILE OPERATIONS

Deleting a File
You can delete a file using the delete() method from the File class.
Intermediate Programming

SUMMARY OF KEY CLASSES


FOR FILE HANDLING
Intermediate Programming

COMMON EXCEPTIONS
IN FILE HANDLING
FileNotFoundException:
• Thrown when an attempt to open a file denoted by a specified pathname has failed
(e.g., the file does not exist or is inaccessible).
• It is a subclass of IOException.

IOException:
• A general class for exceptions produced by failed or interrupted I/O operations
(e.g., reading from a closed stream, failure to write, etc.).

SecurityException:
• Thrown when the security manager denies access to the file system (e.g., trying to
write to a file without proper permissions).
Intermediate Programming

COMMON SCENARIO

Handling a Missing File:


• You should handle the case where the file you're trying to open does not
exist by catching FileNotFoundException.

Handling Permissions Issues:


• If the program lacks permission to read/write to a file, a SecurityException
or IOException will be thrown.

Handling I/O Interruptions:


• If the program is interrupted while performing I/O operations (e.g.,
reading/writing), an IOException may be thrown, which should be handled.
Intermediate Programming

BEST PRACTICE

Use Specific Exceptions: Catch specific exceptions like


FileNotFoundException or IOException instead of catching general
Exception classes. This makes the code more understandable and
maintains proper error handling.

Use Try-With-Resources: To avoid resource leaks (e.g., open files or


streams), use try-with-resources where possible. This ensures that the
resource is automatically closed after use.

Provide Meaningful Messages: When catching exceptions, always provide


meaningful error messages or logging to help in debugging.

Always Close Resources: Ensure that resources like file readers or writers
are closed to avoid memory leaks or file locks. Try-with- resources is ideal
for this.

Use Logging: For production systems, log exceptions rather than printing
stack traces to the console, so you have a record of what went wrong.

Graceful Error Handling: Avoid abrupt program termination due to file


errors. Instead, handle the exception gracefully and provide fallback
mechanisms (e.g., asking the user for another file path).
ASSESSMENT TASK

ACTIVITY
Exercise 1: Read and Write a File in Java with Exception Handling

Objective:

Write a Java program that creates a text file, writes data to it, and reads the
data back from the file. Handle any exceptions (like IOException) that may
occur during file operations.

Step-by-Step Procedure:

Step 1: Set Up the Project

Create a new Java project or file where you will write the code.
Create a class (e.g., FileHandlingExample.java).

Step 2: Import Required Classes

java.io.FileWriter (to write data to a file)


java.io.FileReader (to read data from a file)
java.io.BufferedReader (to read the file line by line)
java.io.IOException (to handle exceptions during file operations)
ASSESSMENT TASK

ACTIVITY

Step 3: Write to a File

Use FileWriter to create and write data to a text file. Handle any exceptions
using a try-catch block.
ASSESSMENT TASK

ACTIVITY

Step 4: Read from a File

Use FileReader and BufferedReader to read the file content.


Again, wrap the code in a try-catch block to handle potential
IOException.
ASSESSMENT TASK

ACTIVITY

Step 5: Exception Handling

Try-with-resources Statement: This ensures that the FileWriter,


FileReader, and BufferedReader resources are automatically closed
after the try block is executed.

Catch Block: The catch (IOException e) part will catch any exceptions
that occur during file operations and print an appropriate message to
the console.

Step 6: Run the Program

After writing the code: Run the program.


It will:
Create a file called sample.txt in the working directory.
Write the specified text into the file.
Read the text from the file and print it to the console.

Expected Output:
ASSESSMENT TASK

ACTIVITY
Exercise 2: Fill in the Blanks – File Handling in Java

Objective:
Fill in the missing parts of a Java program that writes data to a file, reads the content from it,
and handles exceptions.

Scenario:
The following program has missing code. Rewrite the code and fill in the blanks to complete
the program so it can write data to a file, then read the data and display it on the console.
ASSESSMENT TASK

ACTIVITY

Extension: After writing the correct code, extend the code by:

o Modifying it to append data to the file instead of overwriting it.


o Allowing the program to accept user input from the console and write it to the
file.
o Introducing an option to delete or clear the contents of the file if required.

How the Program Works:

Prompt the User:


The program presents three options:
1: Append to the file.
2: Clear the file.
3: Read the file.
Append Mode:
If the user chooses to append, the program accepts text input and adds
it to the existing file content.
Clear Mode:
If the user chooses to clear, the program overwrites the file with an
empty string, removing all existing content.
Read Mode:
If the user chooses to read, the program reads the file line by line and
displays its content.
ASSESSMENT TASK

ACTIVITY
Key Features of the Extended Program:
Append to the File:

o When the user selects option 1, the program appends the entered data to
the output.txt file instead of overwriting it.
o This is achieved by passing true as the second argument to the FileWriter
constructor (FileWriter(fileName, true)), enabling append mode
Clear the File (Delete Contents):
o Option 2 clears the file by writing an empty string to it.
o FileWriter is used without the append mode (true argument), so it
overwrites the file and effectively clears the content
Read the File:
o Option 3 reads the file using FileReader and BufferedReader, printing each
line to the console.

SAMPLE EXPECTED OUTPUT:


ASSESSMENT TASK

REFERENCES:

[1] Burd, B. (2021). Beginning Programming with Java for Dummies. (6th ed.).
[2] Clark, N. (2021). Computer programming for beginners: fundamentals of programming
terms and concepts. (2nd ed.).
[3] Crutcher, P. (2021). Essential computer science: a programmer’s guide to foundational
concepts.
[4] Ellison, B. (2022). Java for Beginners: A Crash Course to Learn Java Programming in 1
Week (Programming Languages for Beginners).
[5] Sebesta, R. (2020). Concepts of Programming Languages. (11 th ed.)

You might also like