CC102 Computer Programming
CC102 Computer Programming
Programming 1
This is a property of
PRESIDENT RAMON MAGSAYSAY STATE UNIVERSITY
NOT FOR SALE
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.
Evaluators:
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
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
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.
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
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
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
Software Requirements
5. Launch Eclipse
Once the installation is complete you can now launch Eclipse. The Eclipse
Installer has done its work.
3. On the package editor right click your java project to create a new class,
javaProgrammingLanguage > New > Class
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
• 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/
Variables
Variables are containers for storing data values.
For example:
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:
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.
Primitive data types - includes byte, short, int, long, float, double, boolean and char
A sequence of characters
String varies
Ex: “Hello World!”
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
Assignment
Search and Study java user input ( Scanner Class ).
Define the use and importance of java user input ( Scanner Class ).
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
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;
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) {
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
code:
int age = ?;
switch (age) {
case 1:
case 2:
case 3:
case 4:
default:
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
Laboratory Activities
Assignment
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
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.
Refference:
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
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);
Creating Constructors
Constructor method are named after their Class Name.
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.
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();
}
}
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");
}
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
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.
t.drink();
}
output
Name : Juan
Sex : M
Age : 30
Name : Jose
Sex : M
Age : 1
Drinking milk
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
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 {
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{
} }
Main.java Animal.java(super-class)
public class Main { public class Animal {
cat1.animalSound(); }
dog1.animalSound();
output
meow meow
Arf Arf
Refference:
Laboratory Activies
Using polymorphism make 4 animal sounds excluding dog and cat.
example output:
meow meow
Arf Arf
Moo
Quack
Quiz
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”};
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
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.
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;
System.out.println(cars);
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
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”);
Remove an Item
To remove an item, use the remove() method and refer to the key:r:
capitalCities.remove(“England”);
HashMap Size
To find out how many items there are, use the size() method:
capitalCities.size();
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>();
https://www.w3schools.com/java
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
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).
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
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 {
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”);
}
}
Refference:
example output: