CCPRGG2L Course Manual-1
CCPRGG2L Course Manual-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.
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:
INTRODUCTION TO JAVA
This means that compiled Java code can run on all platforms that
support Java without the need for recompilation.
The language was initially called "Oak" after an oak tree that stood
outside Gosling's office.
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
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
CODE:
OUTPUT:
Intermediate Programming
Expected Output:
Intermediate Programming
Module 2
Learning Outcomes:
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
• 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.
JAVA OPERATORS
Arithmetic Operators
Used for mathematical calculations, including:
• Addition (+), Subtraction (-), Multiplication (*), Division (/),
Modulus (%).
EXAMPLE:
Assignment Operators
JAVA OPERATORS
Comparison Operators
EXAMPLE:
Logical Operators
JAVA OPERATORS
Logical Operators
OUTPUT OPERATIONS
EXAMPLE:
CODE:
OUTPUT:
Intermediate Programming
OUTPUT OPERATIONS:
EXAMPLE CODE:
OUTPUT:
Intermediate Programming
INOUT OPERATIONS:
Using the Scanner Class
To read input, you first need to import the Scanner class from the java.util package.
Use various methods to read input (depending on the type of input required).
Intermediate Programming
EXAMPLE CODE:
Intermediate Programming
EXAMPLE CODE:
ASSESSMENT TASK
Operations:
• Arithmetic operations (addition, subtraction, multiplication, and division) are performed on integers.
• String concatenation (+ operator) combines two strings.
ASSESSMENT TASK
• Basic input and output operations using the Scanner class for input and
System.out.println for output:
ASSESSMENT TASK
LABORATORY ACTIVITY 1
Instructions:
What to Do:
LABORATORY ACTIVITY
Questions to Answer:
Assessment:
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.
LABORATORY ACTIVITY 2
Requirements:
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:
CONDITIONAL STATEMENT
1. Decision-Making Statements
2. Looping (Iteration) Statements
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
}
CONDITIONAL STATEMENT
These statements evaluate a condition (boolean expression) and execute blocks
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
}
LOOPING STATEMENT
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..
SWITCH STATEMENT
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.
return Statement
Exits from the current method and returns a value (if the method is not
void).
BRANCHING STATEMENT
continue Statement
Skips the current iteration of the loop and proceeds to the next iteration.
ACTIVITY
TASK 1: CONDITIONAL STATEMENTS
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
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:
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:
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:
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:
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
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.
EXAMPLE OUTPUT:
ASSESSMENT TASK
ACTIVITY
Array Activities for Java
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.
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).
Module 5
Learning Outcomes:
INTRODUCTION TO
CLASS AND METHODS
What is a Class?
• It consists of:
INTRODUCTION TO
CLASS AND METHODS
What is a Method?
• Benefits:
• Code reusability.
• Improved readability and modularity.
What is an Object?
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
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.
METHODS STRUCTURE
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:
PROGRAMMING CHALLENGE
This activity combines the topics of classes and objects, methods and constructors, instance
vs. static variables, and method overloading.
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.
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
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.
ERROR HANDLING
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.
throw Keyword:
•You can manually throw exceptions using the throw keyword.
Intermediate Programming
ERROR HANDLING
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:
Examples:
• IOException
• SQLException
• FileNotFoundException
Examples:
• NullPointerException
• ArrayIndexOutOfBoundsException
• ArithmeticException
Intermediate Programming
ERROR HANDLING
ERROR HANDLING
SUMMARY
Debugging helps developers identify and resolve issues in their code, often
unexpected situations arise. Java uses the try, catch, and finally constructs
ACTIVITY
Example Output:
ACTIVITY
ASSESSMENT TASK
PROGRAMMING CHALLENGE
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:
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.
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.
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).
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
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
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
Deleting a File
You can delete a file using the delete() method from the File class.
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
BEST PRACTICE
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.
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:
Create a new Java project or file where you will write the code.
Create a class (e.g., FileHandlingExample.java).
ACTIVITY
Use FileWriter to create and write data to a text file. Handle any exceptions
using a try-catch block.
ASSESSMENT TASK
ACTIVITY
ACTIVITY
Catch Block: The catch (IOException e) part will catch any exceptions
that occur during file operations and print an appropriate message 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:
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.
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.)