Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
144 views

CC102 Computer Programming

Uploaded by

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

CC102 Computer Programming

Uploaded by

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

CC102 Computer

Programming 1

This is a property of
PRESIDENT RAMON MAGSAYSAY STATE UNIVERSITY
NOT FOR SALE

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Copyright. Republic Act 8293 Section 176 provides that “No copyright shall subsist in any
work of the Government of the Philippines. However, prior approval of the government
agency or office wherein the work is created shall be necessary for exploitation of such work
for profit. Such an agency or office may, among other things, impose as a condition the
payment of royalties.

Borrowed materials included in this module are owned by their respective copyright
holders. Every effort has been exerted to reach and seek permission to use these materials
from their respective copyright owners. The University and authors do not claim ownership
over them.

Learning Module Development Team

Assigned Chapter Title Author/s


Chapter 1 Course Overview

Chapter 2 Introduction to Java Programming

Chapter 3 Variables, Data types, Operators

Chapter 4 Conditional Statements Mr. Jason S. Artates, MSCS


Chapter 5 Looping statements

Chapter 6 Object-Oriented Programming

Chapter 7 Array and Collections

Chapter 8 Exception Handling

Evaluators:

Dr. Esmen D. Cabal, Director for Instruction/Quality Assurance


Dr. Felipa M . Rico, Vice-President for Academics and Student Affairs

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


TABLE OF CONTENTS

CHAPTER 1: INTRODUCTION TO CC102 Page 5


Lesson 1: PRMSU Vison and Mission
Lesson 2: College Goals and Program
Objectives
Lesson 3: Introductory and Course Overview
CHAPTER 2: INTRODUCTION TO JAVA Page 8
Lesson 1: Overview of Java
Lesson 2: Installing IDE
Lesson 3: Creating Simple Java Program
CHAPTER 3: VARIABLES DATA TYPES OPERATORS Page 15
Lesson 1: Declaring and Initializing Variables
Lesson 2: Primitive and Reference Data Types
Lesson 3: Arithmethic Assignment,
Comparison, and Logical Operators
CHAPTER 4: CONDITIONAL STATEMENTS Page 19
Lesson 1: If . . . Then
Lesson 2:If . . . Then . . . Else
Lesson 3: Ladderized If’s
Lesson 4: Nested If
Lesson 5: Select Case
CHAPTER 5: LOOPING STATEMENTS Page 25
Lesson 1: For Loop
Lesson 2: Do . . . While Loop
Lesson 3:While Loop
Lesson 4: For Each Loop
CHAPTER 6: OBJECT-ORIENTED Programming Page 29
Lesson 1: Classes and Objects
Lesson 2: Constructors and Methods
Lesson 3: Encapsulation
Lesson 4: Inheritance
Lesson 5: Polymorphism
CHAPTER 7: Array and Collections Page 38

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Lesson 1: Declaring and Initializing Arrays
Lesson 2: One-Dimensional and Multi-
Dimensional Arrays
Lesson 3: ArrayList and Hash Maps
CHAPTER 8: Exception Handling Page 45
Lesson 1: Handling Exception Using try/catch
blocks
Lesson 2: Creating Custom Exceptions

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 1

PRMSU VISION
PRMSU shall be a premier learner-centered and proactive university in a digital and global society.
PRMSU MISSION
The PRMSU shall primarily provide advance and higher professional, technical, and special
instructions in various disciplines; undertake research, extension and income generation programs
for the sustainable development of Zambales, the region and the country.

COMPUTER PROGRAMMING 1

Introduction to Computer Programming


Overview
The 21st-century world runs on computers. And computers run on programs. Understanding
computer programming unlocks the power of computing systems and programming opens career
doors. Computer programs communicate information to computing devices. Computers then carry
out tasks based on the program instructions. Simple programs tell computers to run calculations,
while complex programs can run video games, analyze big data, or drive a car

What is Computer Programming?


Programming, also known as coding, refers to the process of writing instructions for computing
devices and systems. A computer program translates those instructions into a language that
computers can understand.

Programming Language
Computer programmers use many different languages to command computers.
Here’s a few popular programming languages:
 Java
 JavaScript
 Python
 Swift
 C / C++
 C#
 PHP

How is computer programming used?


Computer programmers created every application that computers run -- from photo editing
software to word processors and web browsers. Programming languages unlock the power of
computing systems. And without computer programming, our computing devices would not
function.

In addition to the uses of programming visible to users, programming languages also


manage the hidden side of computing. Programs pull information from databases, implement
security procedures to protect private data, and operate memory backup systems

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


What computer programmers do?
Computer programmers write code in languages like JavaScript, Python, and C++. Depending
on their focus area, web development, mobile application development, software engineering, and
so on.
Computer programmers need more than fluency in one or more programming languages.
They also need to know how to debug and modify code. Programmers often work in teams.
The process of creating a program is complex and involves steps such as:
 Conceptualizing the goal of the application
 Building a layout of the different parts of the program
 Writing code
 Debugging the code and resolving any errors
 Testing the application
 Releasing the program to beta users

Computer programming jobs


Web Developer
Web developers design and create websites. They're responsible for both how the site looks
and how it functions.

Computer Systems Engineer


Computer systems engineers work to make sure their clients' computer systems are all fully
functional and efficient.

Systems Analyst
A systems analyst evaluates a business' technology and looks for ways to fix issues or
optimize systems.

Database Administrator
A database administrator (DBA) handles the large, complex, and often confidential
information within a company's database.

Front-End Developer
A front-end developer creates and maintains the elements on a website or web application
that end users interact with, such as videos or clickable buttons.

Mobile App Developer


Mobile app developers design and code software for mobile devices like cell phones and
tablets.

Software Developer
Software developers design and create software programs for a variety of computer
systems.

Cloud Engineer
A cloud engineer designs, optimizes, and maintains a business' cloud computing system.

Game Developer

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Game developers help to program video game structures and mechanics from concept to
final product.
References
https://prmsu.edu.ph/
https://www.zdnet.com/education/computers-tech/what-is-computer-programming/
https://www.indeed.com/career-advice/finding-a-job/types-of-programming-jobs

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 2
Introduction to Java Programming Language
Overview
Java is a versatile and widely-used programming language known for its portability,
performance, and reliability. Developed by Sun Microsystems (now owned by Oracle
Corporation), Java is designed to be platform-independent, making it suitable for a variety
of applications, from mobile devices to enterprise systems.
Key features:
 Platform Independent - Compiler converts source code to bytecode and then the
JVM executes the bytecode generated by the compiler. This bytecode can run on
any platform be it Windows, Linux, or macOS which means if we compile a program
on Windows, then we can run it on Linux and vice versa.
 Object-Oriented Programming Language - Organizing the program in the terms of a
collection of objects is a way of object-oriented programming, each of which
represents an instance of the class.
The four main concepts of Object-Oriented programming are:
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Simple - Java is one of the simple languages as it does not have complex features
like pointers, operator overloading, multiple inheritances, and Explicit memory
allocation.
 Robust - Java language is robust which means reliable. It is developed in such a way
that it puts a lot of effort into checking errors as early as possible, that is why the
java compiler is able to detect even those errors that are not easy to detect by
another programming language.
 Secure - In java, we don’t have pointers, so we cannot access out-of-bound arrays
i.e it shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several
security flaws like stack corruption or buffer overflow are impossible to exploit in
Java. Also, java programs run in an environment that is independent of the
os(operating system) environment which makes java programs more secure.
 High Performance - Java architecture is defined in such a way that it reduces
overhead during the runtime and at some times java uses Just In Time (JIT)
compiler where the compiler compiles code on-demand basics where it only
compiles those methods that are called making applications to execute faster.

Lesson 1: Integrated development environment (IDE)

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Integrated development environment (IDE)
An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. It normally
consists of at least a source code editor, build automation tools, and a debugger. IDEs help
programmers create code by combining a number of functions into a single program,
allowing users to write, test, and execute programs all from the same place, sometimes
even with a graphical user interface.
Eclipse as an IDE?
Eclipse is an integrated development environment (IDE) used in computer programming. It
contains a base workspace and an extensible plug-in system for customizing the environment. It is
the second-most-popular IDE for Java development.

Benefits of using eclipse:

 Simplified interface - eclipse is known for its user-friendly interface and classic three-
panel layout. This layout consists of a navigation pane on the left-hand side, an
editor pane in the middle, and a task pane on the right. This layout makes it simple
for programmers to efficiently manage their coding process, projects, source files,
and tasks
 Language support - eclipse has a reputation as a Java-specific IDE, but that view is
short-sighted. Over the years, Java has grown to support a wide-range of
programming languages.

1. Java 4.JavaScript

2. C/C++ 5.PHP

3. Python 6.HTML and CSS

 Code editing and code refactoring - eclipse features a robust built-in text editor with
standard capabilities like syntax highlighting and code completion. It goes beyond
with intelligent code suggestions to enhance coding speed and reduce errors.
Additionally, Eclipse offers code refactoring tools for tasks like renaming variables
and organizing code, all of which make codebases cleaner and more maintainable.
 Community - As an open-source IDE, Eclipse benefits from a vibrant community that
offers extensions, documentation, tutorials, and forums for developers to seek
assistance. The active community contributes to regular updates and bug fixes,
ensuring the IDE's stability and security.

Eclipse Installation:

Hardware Requirements

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


The hardware specifications play a vital role in the smooth operation of Eclipse. A
minimum of 4GB RAM is recommended, although 8GB or more is preferable for
better performance, especially when working on larger projects. At least 2GB of free
disk space is required for installation, though more may be needed for additional
plugins and projects.

Software Requirements

Eclipse is compatible with various operating systems, including Windows, macOS,


and Linux. It requires Java Runtime Environment (JRE) or Java Development Kit (JDK)
to be installed on the system. The latest version of Eclipse typically requires the
most recent or a recent version of the Java JDK.

Steps by steps installation


1. Download the Eclipse Installer
Download Eclipse Installer from http://www.eclipse.org/downloads
2. Start the Eclipse Installer executable
For Windows users, after the Eclipse Installer executable has finished
downloading it should be available in your download directory. Start the
Eclipse Installer executable.

3. Select the package to install


The new Eclipse Installer shows the packages available to Eclipse users. You
can search for the package you want to install or scroll through the list but
for us select the Eclipse IDE for Java Developers.

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


4. Select your installation folder Specify the folder where you want Eclipse to
be installed. Happy coding.Specify the folder where you want Eclipse to be
installed

5. Launch Eclipse
Once the installation is complete you can now launch Eclipse. The Eclipse
Installer has done its work.

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Lesson 2: Simple Java Program
Making your first program in Java might feel like a big accomplishment its actually quite
simple to create a simple java program.
1. You need to create a new Java project, File > New > Java Project

2. Enter your Java Project Name then click finish

3. On the package editor right click your java project to create a new class,
javaProgrammingLanguage > New > Class

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


4. Enter your class name, check the method to use, public static void main (String[] args).

5. In package explorer you can see you created a new class.


Type your First line of code in java :

System.out.println("Simple Java Program");

And click Run

6. Congrats you just made your first Simple Java Program, in eclipse java program run without ui runs
on console, make the console appear by clicking on Window>Show View>Console

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


References

• https://www.eclipse.org/downloads/packages/installer
https://www.codecademy.com/article/cpp-object-oriented-programming
• https://marketsplash.com/tutorials/eclipse/install-eclipse-ide/#:~:text=System
%20Requirements%20For%20Installing%20Eclipse%20IDE
%201%20Hardware,resolution%20of%201024x768%20is%20recommended%20for
%20Eclipse.%20
• http://www.eclipse.org/downloads
• Eclipse IDE Review | Developer.com
• https://www.geeksforgeeks.org/introduction-to-java/

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 3
Variables, Data Types, Operators
Overview
Java employs variables, data types, and operators as foundational elements of its
syntax. Variables act as containers for storing data values, each declared with a specific data
type indicating the kind of data it can hold. Primitive data types, like integers and booleans,
represent single values directly, while reference data types, such as strings and arrays,
encapsulate more complex structures. Operators in Java, including arithmetic, assignment,
comparison, and logical operators, facilitate various operations on variables and data values,
enhancing the language's expressive power.

LESSON 1: Declaring and Initializing Variables


Declaring variables in Java involves specifying their type and name, indicating the kind of
data they will hold. Initialization, which can occur at the time of declaration or later in the program,
assigns an initial value to the variable, ensuring it's ready for use. Together, declaration and
initialization set the stage for efficient and organized programming in Java.

Variables
Variables are containers for storing data values.
For example:

int age = 21;

In this example the underlined word or “age” is the variable it is used to store the value “21”

Data Types
A variable in Java must be a specified data type
For example:

int age = 21;

In this example the data type is “int” short for integer which is use for declaring whole
numbers.

Declaration int age; Specify the data type and variable name.
Initialization age = 21; Assign initial value to declared variable.

Declaration and Simplify the code by combining declaration


int age = 21;
Initialization and initialization

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


LESSON 2: Primitive and Reference data types
data types are divided into two groups primitive and reference:

Primitive data types - includes byte, short, int, long, float, double, boolean and char

data type size value


boolean 1 bit true or false
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2 billion to 2 billion
long 8 bytes -9 quintillion to 9 quintillion
Fractional number up to 6-7 digits ex:
float 4 bytes
3.123456f
Fractional number up to 15 digits ex.
double 8 bytes
3.123456789012345
Single character/letter/ASCII value ex:
char 2 bytes
`f`

Non-primitive/reference data types - such as String, Arrays and Classes.

A sequence of characters
String varies
Ex: “Hello World!”

LESSON 3: Arithmetic, Assignment, Comparison


And Logical Operators

Operators
Arithmethic operators are used to perform common mathematical operations.
Operators Name Description Example
+ Addition Adds together two values x+y
- Substraction Substract one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increase the value of variable by 1 ++x
-- Decrement Decreses the value of variable by 1 - -x

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Reference:
 https://www.w3schools.com/java
 https://youtu.be/xk4_1vDrzzo?t=1226&si=EkOTWD-A9G1UPYTs

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Assesment
Quiz
1-5. Enumerate 5 types of data types.
6-7. What is the two groups of data types?
8. What is the symbol of the operator “increment”?
9. What is the name of the operator with the simble with two plus(++)?
10. What does the operator modulus do?

Assignment
Search and Study java user input ( Scanner Class ).
Define the use and importance of java user input ( Scanner Class ).

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 4
Conditional Statements
Overview
Conditional statements in Java are fundamental constructs that allow for decision-
making within a program's flow. They enable the execution of specific code blocks based on
certain conditions. Java supports several types of conditional statements, including
"if...then," "if...then...else," ladderized if statements, nested if statements, and the "switch"
statement. Each type offers distinct functionalities, providing flexibility in designing
programs to respond dynamically to varying situations.
 Use if to specify a block of code to be executed, if a specified condition is true
 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

LESSON 1: if … then
The "if...then" statement in Java evaluates a condition and executes a block of code if the
condition is true. It's a simple form of decision-making in which the subsequent action depends on
whether the condition evaluates to true.

Code:
if (20 > 18 ) {
System.out.println(“20 is greater than 18”);
}
Output:
20 is greater than 18

LESSON 2: if … then … else


The "if...then...else" statement extends the functionality of the "if" statement by providing
an alternative action to execute when the condition evaluates to false. This allows for branching in
the program flow, enabling different paths based on the outcome of the condition.

Situation 1 Code:
int age = 21;
if (age >= 18) {
System.out.println(“You are an adult”);
}
else {
System.out.println(“You are not an adult”);
}

Output:
You are an adult
Situation 2 Code:
int age = 16;

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


if (age >= 18) {
System.out.println(“You are an adult”);
}
else {
System.out.println(“You are not an adult”);
}
Output:
You are not an adult

LESSON 3: Ladderized if’s


Ladderized if statements involve multiple "if" and "else if" clauses, forming a sequence of
conditional checks. This structure allows for checking multiple conditions sequentially, executing the
corresponding block of code associated with the first true condition encountered.

Situation 1 Code:
int age = 21;
if (age >= 18) {
System.out.println(“You are an adult”);
}
else if (age >=13) {
System.out.println(“You are a teenager”);
}
else {
System.out.println(“You are still a kid”);
}
Output:
You are an adult

Situation 2 Code:
int age = 16;
if (age >= 18) {
System.out.println(“You are an adult”);
}
else if (age >=13) {
System.out.println(“You are a teenager”);
}
else {
System.out.println(“You are still a kid”);
}
Output:
You are a teenager

Situation 3 code:
int age = 12;
if (age >= 18) {
System.out.println(“You are an adult”);
}
else if (age >=13) {

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


System.out.println(“You are a teenager”);
}
else {
System.out.println(“You are still a kid”);
}
Output:
You are still a kid

LESSON 4: Nested if
Nested if statements involve placing one "if" statement inside another. This technique
allows for more complex decision-making scenarios where certain conditions depend on the
outcome of other conditions. However, nesting should be used judiciously to maintain code
readability and avoid excessive complexity.

code:
int age = ?;
if (age <= 30) {
if (age >=18 ) {
System.out.println("you are an adult");
}
else if (age >= 13) {
System.out.println("you are a teenager");
}
else{
System.out.println("you are very young");
}
}
else {
if (age >= 60 ) {
System.out.println("you are very old");
}
else {
System.out.println("you are not that old");
}
}
}
Output
int age = ?; output
12 you are very young
16 you are a teenager
24 you are an adult
32 you are not that old
64 you are very old

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


LESSON 5: Select(Switch) Case
The "switch" statement provides a means to select one among many code blocks to be
executed. It evaluates an expression and compares its value to multiple case labels, executing the
code associated with the matching case. This statement is particularly useful when dealing with
multiple possible values for a variable and simplifies the code compared to using nested "if"
statements.

code:
int age = ?;

switch (age) {

case 1:

System.out.println("you are 1 year old");

case 2:

System.out.println("you are 2 years old");

case 3:

System.out.println("you are 3 years old");

case 4:

System.out.println("you are 4 years old");

default:

System.out.println("you are too old for this system");

Output:
int age = ?; output
1 you are 1 year old
2 you are 2 years old
3 you are 3 years old
4 you are 4 years old
5 you are too old for this system

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Refference:
 https://www.w3schools.com/java
 https://www.youtube.com/watch?v=wcwWlasmLWs

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Assesment

Laboratory Activities

Use Java user input Scanner Class in if . . . then . . . else statement.

Assignment

List and define looping statements in java.

Quiz

1. BLANK statement provides a means to select one among many code blocks to be
executed.
2. BLANK statements involve multiple "if" and "else if" clauses, forming a sequence
of conditional checks.
3. BLANK statements involve placing one "if" statement inside another.
4. BLANK statement in Java evaluates a condition and executes a block of code if the
condition is true. It's a simple form of decision-making in which the subsequent action
depends on whether the condition evaluates to true.
5. BLANK statement extends the functionality of the "if" statement by providing an
alternative action to execute when the condition evaluates to false

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 5
Looping Statements
Overview

Loops in Java come into play when we need to repeatedly execute a block of
statements .Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.

LESSON 1: For Loop


The for loop in Java is used to iterate over a range of values. It consists of three
parts: initialization, condition, and increment/decrement. The loop continues until the
condition evaluates to false.
The syntax for writing For Loop in java is: for (initialization, condition, increment/decrement) {
//code block to be executed
}
Here’s a code snippet:
for (int i = 0; I < 5; i++) {
System.out.println(i);
}
Output:
0
1
2
3
4

LESSON 2: Do While Loop


The do-while loop in Java executes a block of code at least once before checking the
loop condition. It ensures that the loop body is executed at least once, even if the condition
is initially false.
The syntax for DO While Loop in java is: do {
//code to be executed
}
while (condition)
Here’s a code snippet:
int i = 0
do {
System.out.println(i);
i++;
}
while (i < 5);
Output:
0
1

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


2
3
4

LESSON 3: While Loop


The while loop in Java repeatedly executes a block of code as long as the specified
condition is true. It evaluates the condition before each iteration and continues until the
condition becomes false.
The syntax for While Loop in java is: while (condition) {
// code block to be executed
}
Here’s a code snippet:
int i = 0;
while ( i < 5 ) {
System.out.println(i);
i++;
}
Output:
0
1
2
3
4

LESSON 4: For-Each Loop


The for-each loop, also known as the enhanced for loop, simplifies iteration over
collections such as arrays or collections. It iterates through each element of the collection,
eliminating the need for explicit indexing.
The syntax for For-each Loop in java is: for ( type variableName : arrayName) {
//code to be executed
}
Here’s a code snippet:
String[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
for (String i : cars) {
System.out.println(i);
}
Output
Volvo
BMW
Ford
Mazda

Refference:

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


 https://www.w3schools.com/java

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Assesment

Lab Activities
Make a program that uses java user input ( scanner class ) and for loop that ask and
print a number and all the numbers before that..

Example Output:
Enter a number: 10
12345678910

Assignment:
Research and Study about Object Oriendted Programming in java and define the
following
1. Class
2. Objects
3. Constructor
4. methods
5. encapsulation
6. inheritance
7. polymorphism

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 6
Object-Oriented Programming
Overview
Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating objects that
contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time

LESSON 1: Classes and Objects


Classes
It is created by the programmer, It will act as a blueprint of an object that you want to implement in
your program
They contain all the attributes and methods that your desired object should have

Objects
It is created by instantiating a class. It is anything that has an attribute and a purpose.
ex: Person, Furniture and Food

Attribute
These are the global variables declared inside the class of our object. It is used to create variations of
an object using only one class.

Class ceation
CLASS CREATION
Person public Person class{
-Name //Attributes
-Sex String name;
-Age char sex;
int age;

//Methods or Purpose
}

Class Instantiation
The process of creating an Object using a class so we can use it on our program.
syntax for writing Object: ClassName identifier = new ClassName();
syntax for writing attributes: identifier.attribute = value;
syntax for reading attributes: System.out.println(identifier.attribute);

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Main.java Person.java
Person p = new Person(); Public class Person {
p.name = “Myer”; String name;
p.sex = ‘M’; char sex;
p.age = 23 ; int age;
}
System.out.println(p.name);
System.out.println(p.sex);
System.out.println(p.age);
output
Myer
M
23

LESSON 2: Constructors and Methods


Constructors
Constructor is the method called when you instantiate a class / create an object. it is used to
initialize the attributes of an object or run a block of code when an object is created.

Creating Constructors
Constructor method are named after their Class Name.

syntax for Constructors:

Constructors are used to Initialize attributes.


syntax for initializing attributes:

public class className{


//attributes
//constructors
}

syntax for writing attributes using constructors:

className identifier = new className(parameters)


example:
Product1 p1 = new Product(“Milk”,150.0f);

THIS KEYWORD
this keyword referes to the class itself. The this keyword enables you to access global variables
inside the class if you have the same variable names in a parameter.

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


example:
Main.java Product.java
package main; package main;

public static void main(Strings[] args) { public class Product {

Product p1 = new Product(“Milk”,150.0f); String name;


Product p2 = new Product(“Softdrinks” ,12.50f); float price;
Product p3 = new Product(“Noodles” ,20.24f);
Product(String name, float price){
} this.name = name;
this.price = price;
}
System.out.println(name + “ Created”

output
Milk Created
Softdrinks Created
Noodles Created

Methods
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known as
functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can
also create your own methods to perform certain actions:

To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
public class main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
myMethod();
}
}

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Output
I just got executed!

Information can be passed to methods as parameter. Parameters act as variables inside the method.

Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as parameter. When the
method is called, we pass along a first name, which is used inside the method to print the full name:
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Pogi");
}

public static void main(String[] args) {


myMethod("Liam");
}
}
Output
Liam Pogi

Multiple Classes Method


it is a good practice to create an object of a class and reuse it in another class.

Main.java Car.java
public class Main { public class Car {
public static void main (String[] args) { public void fullThrottle() {
Car myCar = new Car (); System.out.println(“The car is going fast as it can!”);
myCar.fullThrottle(); }
myCar.speed(200);
} public void speed (int maxSpeed) {
} System.out.println(“Max speed is: “ + maxSpeed);
}
}
Output
The car is going as fast as it can!
Max speed is: 200

LESSON 3: Encapsulation
Encapsulation
This principle states that all important information is contained inside an object and only
select information is exposed. The implementation and state of each object are privately held inside a
defined class. Other objects do not have access to this class or the authority to make changes. They
are only able to call a list of public functions or methods. This characteristic of data hiding provides
greater program security and avoids unintended data corruption.
To achieve this, you must:
 declare class variables/attributes as private
 provide public get and set methods to access and update the value of a private
variable

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


syntax for declaring attributes as private:
private String name;
private int age;

Get and Set


private variables can only be accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.
syntax for get
public String getName() {
return name;
}
syntax for set
public void setName(String newName) {
this.name = newName;
}

Why Encapsulation?
 Better control of class attributes and methods
 Class attributes can be made read-only (if you only use the get method), or
write-only (if you only use the set method)
 Flexible: the programmer can change one part of the code without affecting
other parts
 Increased security of data

LESSON 4: Inheritance
overview
Classes can reuse code from other classes. Relationships and subclasses between objects can
be assigned, enabling developers to reuse common logic while still maintaining a unique hierarchy.
This property of OOP forces a more thorough data analysis, reduces development time and ensures a
higher level of accuracy.

In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from

extend keyword
used after the class name and it indicates that the certain class will inherit from another class.

To inherit from a class, use the extends keyword in subclass


syntax: public class subClassName extends superClassName {
//code to be executed
}
main class superclass subclass
public static void main(String[] public class Parent { public class Toddler extends
args) { Parent{

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Parent p = new Parent(); String name, sex; void drink() {
Toddler t = new Toddler(); int age; System.out.println("Drinking
milk");
p.name = "Juan"; void checkStatus() { }
p.sex = "M"; System.out.println("Name : " + }
p.age = 30; name);
System.out.println("Sex : " +
t.name = "Jose"; sex);
t.sex = "M"; System.out.println("Age : " +
t.age = 1; age);
}
p.checkStatus();
t.checkStatus(); }

t.drink();
}

output
Name : Juan
Sex : M
Age : 30
Name : Jose
Sex : M
Age : 1
Drinking milk

Inheritance using contractors


To be able to use contractors in inheritance you are required to call the constructor of the superclass.

super keyword
Super keyword can only be used by a subclass and it is used to call their superclass so we can access
their constructors, attributes and method

syntax for using contractors in inheritance:


class parent { class toddler extends parent {

person(arguments){ toddler(arguments){
//constructors super(arguments);
} //add attributes
}
}
}
Overriding Methods
To retain the functionality from the Super Class use the super keyword with the method name.
class parent { class toddler extends parent {

void checkStatus(){ void checkStatus() {


//output attributes super.checkStatus();
} //add Functionalities
}
}
}

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


LESSON 5: Polymorphism
overview
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.

Like we specified in the previous Lesson; Inheritance lets us inherit attributes and methods from
another class. Polymorphism uses those methods to perform different tasks. This allows us to perform
a single action in different ways.

For example, think of a superclass called Animal that has a method called animalSound(). Subclasses
of Animals could be Cats and Dogs - And they also have their own implementation of an animal sound
(the pig oinks, and the cat meows, etc.):

Dog.java(sub-class) Cat.java(sub-class)
public class Dog extends Animal { public class Cat extends Animal{

public void animalSound() { public void animalSound() {


System.out.println("Arf Arf"); System.out.println("meow meow");
} }

} }

Main.java Animal.java(super-class)
public class Main { public class Animal {

public static void main(String[] args) { public void animalSound() {


System.out.println("The animal makes a
Animal cat1 = new Cat(); sound");
Animal dog1 = new Dog(); }

cat1.animalSound(); }
dog1.animalSound();

output
meow meow
Arf Arf

Refference:

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


 https://www.w3schools.com/java

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Assesment

Laboratory Activies
Using polymorphism make 4 animal sounds excluding dog and cat.

example output:
meow meow
Arf Arf
Moo
Quack

Quiz

1-2. Enumerate 2 advantages of Object Oriented Programming


3.These are the global variables declared inside the class of our object.
4. It is created by the programmer, It will act as a blueprint of an object that you want to implement
in your program
5.It is created by instantiating a class. It is anything that has an attribute and a purpose.
6. The process of creating an Object using a class so we can use it on our program.
7. Blank is the method called when you instantiate a class / create an object. it is used to initialize the
attributes of an object or run a block of code when an object is created.
8. is a block of code which only runs when it is called.
9. This principle states that all important information is contained inside an object and only select
information is exposed.
10. In Java, it is possible to inherit attributes and methods from one class to another through which
method?

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 7
Array and Collections
Overview
Java provides powerful data structures to work with collections of elements. Arrays
are a fundamental part of Java, allowing you to store multiple values of the same type in a
single variable. Collections, such as ArrayLists and HashMaps, provide dynamic data
structures for storing and manipulating groups of objects.

Lesson 1: Declaring and Initializing


Arrays
overview
In Java, Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.

To declare an array, define the variable type with square brackets:


String[] identifier;

We have now declared a variable that holds an array of strings. To insert values to it, you can
place the values in a comma-separated list, inside curly braces:
String user = {“value1”, “value2r”, “value3”, “value4”};

To create an array of integers, you could write:


int[] myNumber = {01, 02, 03, 04}

To change an array element:


dataType identifier = newValue;

Lesson 2: One-Dimmesional and multi-


Dimensional Arrays
overview
Java supports both one-dimensional and multi-dimensional arrays. One-dimensional
arrays are like lists, while multi-dimensional arrays are arrays of arrays.

one dimensional arrays


A one-dimensional array in Java is a sequential collection of elements of the same
type. It can be thought of as a list where each element is accessed by its index. One-
dimensional arrays are declared by specifying the data type of the elements followed by
square brackets [] and then the identifier.

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


example:
public class Main {
public static void main(String[] args) {
String[] studentName = {“Dave”, “Mico”, “Jayrold”, “ Ej”};
System.out.println(studentName[2]);
}
}
Output:
Jayrold

multi-dimensional arrays
A multi-dimensional array in Java is an array of arrays. It allows you to store data in a
tabular form with rows and columns. Unlike one-dimensional arrays, which have a single
index to access elements, multi-dimensional arrays have multiple indices, one for each
dimension. multi-dimensional arrays are declared by specifying data type of the elements
followed by two square brackets [][] and then the identifier.

example:
public class Main {
public static void main(String[] args) {
String[][] users = {
{“daveD”, “daveDPass”},
{“micoA”, “micoAPass”},
{“jayL”, “jayLPass”},
{“ejD”, “ejDpass”}
};
System.out.println(“username ” + users[0][0]);
System.out.println(“username ” + users[0][1]);
}
}
Output:
username: daveD
password: daveDPass

Lesson 3: Array List and Hash Maps


ArrayList
The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array
cannot be modified (if you want to add or remove elements to/from an array, you have to
create a new one). While elements can be added and removed from an ArrayList whenever
you want.

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


The syntax is also slightly different:
import java.util.ArrayList;

ArrayList<String> cars = new ArrayList<String>();

Add Items
The ArrayList class has many useful methods. For example, to add elements to the ArrayList,
use the add() method:
cars.add(“BMW”);
cars.add(“Ford”);
cars.add(“Mazda”);

Access an Item
To access an element in the ArrayList, use the get() method and refer to the index number:
cars.get(0);

Change an Item
To modify an element, use the set() method and refer to the index number:
cars.set(0, “Opel”);

Remove an Item
To remove an element, use the remove() method and refer to the index number:
cars.remove(0);

To remove all the elements in the ArrayList, use the clear() method:
cars.clear();

ArrayList Size
To find out how many elements an ArrayList have, use the size method:
cars.size();

Sort an ArrayList
Another useful class in the java.util package is the Collections class, which include sort()
method for sorting list alphabetically or numerically:
import java.util.ArrayList;
import java.util.Collections;

public class Main {

public static void main (String[] args) {


ArrayList<String> cars = new ArrayList<String>();
cars.add(“Volvo”);
cars.add(“BMW”);
cars.add(“Ford”);
cars.add(“Mazda”);

System.out.println(cars);

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Collections.sort(cars);
for (String i : cars) {
System.out.println(i);
}
}
}

output
[Volvo, BMW, Ford, Mazda]
BMW
Ford
Mazda
Volvo

Other types
Elements in an ArrayList are actually objects. Remember that a String in Java is an object
(not a primitive type).

To use other types, such as int, boolean, char, double, etc… you must specify an equivalent
wrapper class: Integer, Boolean, Character ,Double etc..

for example
ArrayList<Integer> myNumbers = new ArrayList<Integer>();

HashMap
In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and
you have to access them with an index number (int type). A HashMap however, store items
in "key/value" pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store different types:
String keys and Integer values, or the same type, like: String keys and String values

The syntax is also slightly different:


import java.util.HashMap;

HashMap<String, String> capitalCities = new HashMap<String, String>();

Add Items
The HashMap class has many useful methods. For example, to add items to it, use the put()
method:
capitalCities.put(“England”, “London”);
capitalCities.put(“Germany”, “Berlin”);
capitalCities.put(“Norway”, “Oslo”);
capitalCities.put(“USA”, “Washington DC”);

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Access an Item
To access a value in the HashMap, use the get() method and refer to its key:
capitalCities.get(“England”);

Remove an Item
To remove an item, use the remove() method and refer to the key:r:
capitalCities.remove(“England”);

To remove all items, use the clear() method:


capitalCIties.clear();

HashMap Size
To find out how many items there are, use the size() method:
capitalCities.size();

Loop Through a HashMap


Loop through the items of a HashMap with a for-each loop.

Note: Use the keySet() method if you only want the keys, and use the values() method if you
only want the values:
//Print keys
for (String i : capitalCities.keyset()) {
System.out.println(i)
};

//Print Values
for (String i : capitalCities.values()) {
System.out.println(i)
};

//Print both
for (String i : capitalCities.keyset()) {
System.out.println(“key : “ + i + “value: “ + capitalCities.get(i));
};

Other types
Keys and values in a HashMap are actually objects. In the examples above, we used objects
of type "String". Remember that a String in Java is an object (not a primitive type). To use
other types, such as int, you must specify an equivalent wrapper class: Integer. For other
primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

for example
HashMap<String, Integer> people = new HashMap<String, Integer>();

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Refference:

 https://www.w3schools.com/java

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Assesment

Laboratory Activities:
Make a multi-dimensional array with atleast 5 name and nickName and use for loop
to print all the name and nickName

example output:
name: Juan Delacruz, nickName: JuanD
name: Taylor Swift, nickName: Swiftie

Quiz:
Differentiate array and arrayList in java( 10points )

Assignment:
Define Try and Catch blocks
Define Custom exception

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


CHAPTER 8
Handling Exception
Overview
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).

Lesson 1: Try and Catch Block


overview
The try statement allows you to define a block of code to be tested for errors while it is
being executed.
try {
// Block of code to try
}

The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
catch(Exception e) {
// Block of code to handle errors

The try and catch keywords come in pairs.

EXAMPLE
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1,2,3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println(“Something went wrong.”);
}
}
}
output:
Something went wrong.

finally
The finally statement lets you execute code, after try . . . catch, regardless of the result:
try {
//code
} catch {
// code
} finally {

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


//code
}

Lesson 2: Custom Exception


Java allows developers to define custom exception types by extending Exception or
RuntimeException. By using the throw keyword, developers can explicitly signal specific
exceptional conditions within their code.

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception
types available in Java: ArithmeticException, FileNotFoundException, , SecurityException
ArrayIndexOutOfBoundsException, etc:
EXAMPLE
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmethicException(“Access denied - you must be atleast 18 years old.”);
}
else {
System.out.println (“Access granted”);
}
}

public static void main(String[] args {


checkAge(15);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at
least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

if age was 20, you would not get an exception:


checkAge(20);
Output: Acess granted

Refference:

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


 https://www.w3schools.com/java

Computer Programming 1 Page PAGE 42 of NUMPAGES 48


Assesment
Laboratory Activies:
Use java user input to make a if then statement with try and catch block.

example output:

Enter your age: 12


Access denied - you must be at least 18 years old.

Enter your age: 23


Access granted

Computer Programming 1 Page PAGE 42 of NUMPAGES 48

You might also like