You are on page 1of 275

ST.

JOHN PAUL II COLLEGE OF DAVAO


COLLEGE OF INFORMATION AND
COMMUNICATIO N TECHNOLOGY

Physically Det ached Yet Academically At tached

SIMPLIFIED COURSE PACK (SCP) FOR SELF-


DIRECTRED LEARNING

PF103 – Object-Oriented Programming

This Simplified Course Pack (SCP) is a draft version only and may not be used,
published, or redistributed without the prior written consent of the Academic Council of
SJPIICD. Contents of this SCP is only intended for the consumption of the students who
are officially enrolled in the course/subject. Revision and modification process of this
SCP are expected.

PF103 – Object – Oriented Programming | 1


ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIO N TECHNOLOGY

Physically Det ached Yet Academically At tached

By 2023, a recognized professional institution providing


Vision
quality, economically accessible, and transformative education
grounded on the teachings of St. John Paul II.
Serve the nation by providing competent JPCean graduates
through quality teaching and learning, transparent
governance, holistic student services, and meaningful
Mission
community-oriented researches, guided by the ideals of St.
John Paul
II.
● Respect
● Hard Work
● Perseverance
Core Values
● Self-Sacrifice
● Compassion
● Family Attachment
● Inquisitive
● Ingenious
Graduate Attributes ● Innovative
● Inspiring
Course Code/Title PF103/Object-Oriented Programming
This course provides in-depth coverage of object-oriented
programming principles and techniques. Topics include
classes, abstraction data types, encapsulation, inheritance,
Course Description polymorphism, simple data and file structures, and program
development in a modular, object-oriented manner. Focus is
on the Object-Oriented language features, including data
hiding and exception handling.
Course System Application Proiect
Requirement
Time Frame 54 Hours
“Based 40” Cumulative Averaging Grading System
Periodical Grading = Attendance (5%) + Participation (10%) +
Grading System Quiz (25%) + Exam (60%)
Final-Final Grade = Prelim Grade (30%) + Midterm Grade
(30%) + Final Grade (40%)
Contact Details
Instructor Martzel Baste (09151362897)
Dean/Program Head Karen Shane O. Adorico (09662456713)

PF103 – Object – Oriented Programming | 2


ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIO N TECHNOLOGY

Physically Det ached Yet Academically At tached

Course Map

PF103- Simplified Course Pack (SCP)

SCP-Topics: Prelim Period SCP- Topics: Midterm Period SCP- Topics: Final Period

Review: Java Basics and Intro to OOP Concepts and UML Advanced GUI
Week 1 Week 7 Week 13
Selection Structures-If Designing (OOD)

Advanced OOP Principles:


Week 2 Review: Loop Structures Week 8 Principle 1: Encapsulation Week 14 Abstract and Interface

Principle 1: Inheritance and Exception Handling


Week 3 Arrays: 1D and Multidimensional Week 9 Week 15
Polymorphism Techniques

Week 4 Methods and Linear Searching Week 10 Intro to GUI Components Week 16 JDBC: Basic Database in Java

List Structures : ArrayList and Project


Week 5 Week 11 Java Layout Managers Week 17
Vector Making/Presentation

Week 6 Preliminary Examination Week 12 Midterm Examination Week 18 Final Examination

1. Compare and contrast procedural/functional approach to object-oriented programming


approach
2. Design, implement, test, and debug programs using OOP concepts like abstraction,
encapsulation, inheritance, and polymorphism.

Welcome Aboard! This course provides in-depth coverage of object-


oriented programming principles and techniques. Topics include
classes, abstraction data types, encapsulation, inheritance,
polymorphism, simple data and file structures, and program
development in a modular, object-oriented manner. Focus is on the
Object-Oriented language features, including data hiding, GUI
components, and exception handling.

PF103 – Object – Oriented Programming | 3


ST. JOHN PAUL II COLLEGE OF DAVAO
COLLEGE OF INFORMATION AND
COMMUNICATIO N TECHNOLOGY

Physically Det ached Yet Academically At tached

SCP-TOPICS: PRELIM PERIOD TOPICS

Week 1 Basic Programming


Lesson Title Datatypes and variables, Selection Structures, Switch
The students are expected to learn the basic programming
Learning construct such as datatypes, variables, selection structures, and
Outcome(s) switch statements.
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!

Terms to Ponder

• Local variables − Variables defined inside methods, constructors or


blocks are called local variables. The variable will be declared and
initialized within the method and the variable will be destroyed when
the method has completed.

• Instance variables − Instance variables are variables within a class


but outside any method. These variables are initialized when the class
is instantiated. Instance variables can be accessed from inside any
method, constructor or blocks of that particular class.

• Class variables − Class variables are variables declared within a


class, outside any method, with the static keyword.

• Primitive Datatypes – are the basic types of data: byte , short , int
, long , float , double , boolean , char. It stores the actual values.

• Reference types are any instantiable class as well as arrays: String


, Scanner , Random , Die , int[] , String[] , etc. Reference variables store
addresses to locations in memory for where the data is stored. Also
known as Wrapper classes.

PF103 – Object – Oriented Programming | 4


ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content
Data Types in Java

Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

• Primitive data types: The primitive data types include boolean,


char, byte, short, int, long, float and double.
• Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays.

Primitive Data Types

There are eight primitive datatypes supported. Primitive datatypes are


predefined by the language and named by a keyword.
1. byte - is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
2. short - can also be used to save memory as byte data type. A short
is 2 times smaller than an integer.
3. int - is generally used as the default data type for integral values
unless there is a concern about memory.
4. long - is used when a wider range than int is needed
5. float - is never used for precise values such as currency. It is mainly
used to save memory in large arrays of floating point numbers
6. double - should never be used for precise values such as currency.
It is generally used as the default data type for decimal values, generally
the default choice
7. boolean - is used for simple flags that track true/false condition. It
represents one bit of information
8. char - is used to store any character. It is a single 16-bit Unicode
character.
SCP-PF103 | 2
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Variable Types

A variable provides us with named storage that our programs can


manipulate
Local Variables are declared in methods, constructors, or blocks.
o Local variables are created when the method, constructor or block
is entered and the variable will be destroyed once it exits the method,
constructor, or block
o Access modifiers cannot be used for local variables.
o Local variables are visible only within the declared method,
constructor, or block.
o Local variables are implemented at stack level internally.
o There is no default value for local variables, so local variables should
be declared and an initial value should be assigned before the first use.

Instances Variables are declared in a class, but outside a method,


constructor or any block.
o When a space is allocated for an object in the heap, a slot for each
instance variable value is created.
o Instance variables are created when an object is created with the
use of the keyword 'new' and destroyed when the object is destroyed.
o Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's state
that must be present throughout the class.
o Instance variables can be declared in class level before or after use.
o Access modifiers can be given for instance variables.

SCP-PF103 | 3
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

o The instance variables are visible for all methods, constructors and
block in the class. Normally, it is recommended to make these variables
private (access level). However, visibility for subclasses can be given for
these variables with the use of access modifiers.
o Instance variables have default values. For numbers, the default
value is 0, for Booleans it is false, and for object references it is null.
Values can be assigned during the declaration or within the
constructor.
o Instance variables can be accessed directly by calling the variable
name inside the class. However, within static methods (when instance
variables are given accessibility), they should be called using the fully
qualified name

• Static Variable o Class variables also known as static variables are


declared with the static keyword in a class, but outside a method,
constructor or a block.
o There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
o Static variables are rarely used other than being declared as
constants. Constants are variables that are declared as public/private,
final, and static. Constant variables never change from their initial
value.
o Static variables are stored in the static memory. It is rare to use
static variables other than declared final and used as either public or
private constants.

o Static variables are created when the program starts and destroyed
when the program stops.
o Visibility is similar to instance variables. However, most static
variables are declared public since they must be available for users of
the class.
o Default values are same as instance variables. For numbers, the
default value is 0; for Booleans, it is false; and for object references, it
is null. Values can be assigned during the declaration or within the
constructor. Additionally, values can be assigned in special static
initializer blocks.

SCP-PF103 | 4
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Arithmetic Operators

Logical Operators

Relational Operators

SCP-PF103 | 5
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Conditions and If Statement

• 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

The if statement

Use the if statement to specify a block of Java code to be executed if a


condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will
generate an error.

Example

if (20 > 18) {


System.out.println("20 is greater than 18");
}

We can also test variables:

Example

int x =
20; int y
= 18; if (x
> y) {
System.out.println("x is greater than y");
}

SCP-PF103 | 6
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

The else statement


Use the else statement to specify a block of code to be executed if the
condition is false.

Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example

int time = 20;


if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."

The else if statement

Use the else if statement to specify a new condition if the first


condition is false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}

SCP-PF103 | 7
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Example

int time =
22; if (time
< 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."

Short Hand If…Else (Ternary Operator)

Syntax
variable = (condition) ? expressionTrue : expressionFalse;
int time =20;
if (time <
18){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
To

int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result);

Switch Statement
Use the switch statement to select one of many code blocks to be
executed.
Syntax

switch(expression){
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
SCP-PF103 | 8
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

This is how it works:


ü The switch expression is evaluated once.
ü The value of the expression is compared with the values of each case.
ü If there is a match, the associated block of code is executed.
ü The break and default keywords are optional, and will be
described later in this chapter

Example

int day = 4;
switch (day){
case 1:
System.out.println("Monday"); break;
case 3:
System.out.println("Wednesday"); break;
case 4:
System.out.println("Thursday"); break;
case 5:
System.out.println("Friday"); break;
case 7:
System.out.println("Sunday"); break;
} // Outputs "Thursday" (day 4)

The Break Keyword


• When Java reaches a break keyword, it breaks out of the switch
block.
• This will stop the execution of more code and case testing inside the
block.
• When a match is found, and the job is done, it's time for a break.
There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution
of all the rest of the code in the switch block.

The Default Keyword

The default keyword specifies some code to run if there is no case match:

Example
int day =4;
switch(day) {
case 6: System.out.println("Today is Saturday");break;
case 7:
System.out.println("Today is Sunday"); break; default:
System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"

SCP-PF103 | 9
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SELF-SUPPORT: You can click the URL Search Indicator below to


help you further understand the lessons.

Search Indicator
https://www.w3schools.com/java/java_arrays.asp
https://www.guru99.com/java-arrays.html
https://www.geeksforgeeks.org/difference-between-inheritance-and-
polymorphism/ https://www.tutorialspoint.com/java/java_array.htm

General Instructions:

1. Answer the activities in the succeeding pages.


2. Submit it in a .PDF format with a filename convention <SURNAME>_<WEEK#>
such that BASTE_WEEK1.
3. The deadline of submission will be 5 days after it was discussed.

Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

NOTE: Put your names in all of your outputs.

LET’S INITIATE!
Activity 1.1. Class name : GradeValidation

Create a program that will evaluate the grade based on the following:

90 – 100 - Excellent
85 – 89 - Very Good
80 – 84 - Good
75 – 79 - Poor
74 down to 0 -Fail

Display ‘out of range’ if grade input is not defined above.

SCP-PF103 | 10
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your Source Code:

Your Output:

Activity 1.2. Class name : DevelopmentalTask

Robert Havighurst (1972), developmental task theory is a task that arises at a certain
period in our life, the successful achievement of which leads to happiness and success
with later tasks while failure leads to unhappiness, social disapproval, and difficulty
with later tasks. Create a program that will take age as an input and then display
what stage of developmental task that age is.

Infancy and Early Childhood – birth to 5 years


Middle Childhood – 6 to 12 years
Adolescence – 13 to 17 years
Early Adulthood – 18 to 35 years
Middle Age – 36 to 60 years
Later Maturity – over 60 years

Your Source Code:

Your Output:

Activity 1.3. Class name : PointGradeValidation

Create a simple application that will take inputs from a student the following
basic information and outputs the information as necessary. See figures
attached or in powerpoint uploaded [slide 29].
Use the following formula : (100-grade+10)/10
NOTE : This program requires Nested-If as a programming concept. Find a better
way it can be applied as a concept or programming construct. Please follow the
desired output shown in the sample.

SCP-PF103 | 11
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your Source Code:

Your Output:

LET’S INQUIRE!
Activity 1.4. Class name : MenuCalculatorIf

Create a simple calculator which will perform basic mathematical functions to two
input numbers using If statement. It will have the following menu

[A]dd [S]ubtract [M]ultiple [D]ivide [Q]uit

The user will choose which mathematical function (after taking two inputs from the
user) to perform by inputting the first letter of the character of the choice. For
example, if the user wants to multiply, he/she will input ‘M’ or ‘m’. If he/she wants
to add, ‘A’ or ‘a’ will be entered. Display ‘Program terminating…’ If a user choose ‘Q’
or ‘q’ and perform nothing.

SCP-PF103 | 12
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your Source Code:

Your Output:

LET’S INFER!
Activity 1.5. Modify the previous activity "MenuCalculatorIf” by converting its
source code to the advantage of using switch statements.

Your Source Code:

Your Output:

SCP-PF103 | 13
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics:

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 14
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP-TOPICS: PRELIM PERIOD TOPICS

Week 2 Loop Structures


Lesson Title while, do-while, and for loop
The students are expected to learn more about looping or iterations
Learning which allows them to make good programs specifically for a certain
Outcome(s) process and/or calculation.
Time Frame

At SJPIICD, I Matter!

I
LEARNING NTENT!

Terms to Ponder

Welcome Aboard! This course provides in-depth coverage of object-


oriented programming principles and techniques. Topics include classes,
abstraction data types, encapsulation, inheritance, polymorphism,
simple data and file structures, and program development in a modular,
object-oriented manner. Focus is on the Object-Oriented language
features, including data hiding, GUI components, and exception
handling.

loop in a computer program is an instruction that repeats until a specified


condition is reached.

count-controlled loop uses a loop control variable in the logical expression.


The loop control variable should be initialized before entering the while loop,
and a statement in the body of the while loop should increment/decrement the
control variable.

sentinel-controlled loop use a special data value, called sentinel, in


conjunction with the logical expression to signal the loop exit. As long as the
sentinel value does not meet the logical expression (specified data value), the
loop is executed.

flag-controlled while loop. It uses Boolean variable called a flag which is a


boolean variable (only can be set to true or false). If a flag is used in a while
loop to control the loop execution,.

EOF-controlled loop is often used to repeatedly read data. When a program


uses a stream to read data, the stream state is set after each read from the
input data stream. After the last data item has been read from the input data
stream, the data stream state is fine. But the next attempt to read input data
from the stream will cause an end-of-file (EOF, for short) to be encountered. At
this time the data stream enters a fail state.

SCP-PF103 | 15
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content
Looping in Java is defined as performing some lines of code in an
ordered fashion until a condition is false. The condition is
important because we do not want the loop to be running forever. As
soon as this condition is false, the loop stops.

In Java there are three primary types of loops:-


1. for loop
2. while loop
3. do-while loop
4. Enhanced for loop

For loop in Java


Java for loop consists of 3 primary factors which define the loop itself.
These are the initialization statement, a testing condition, an increment
or decrement part for incrementing/decrementing the control variable.

The basic syntax of java for loop goes like this:

for(initializing statement; expression; increment/decrement) {


//statement(s)
}

The initializing statement marks the beginning of the loop structure. It


contains a variable with some initial value that is defined by the
programmer. This is the value of the control variable when the control
shifts into the loop. However this statement is executed only once.
If a particular variable is declared within this part, then the scope of the
variable remains limited within the loop.

The control flow can be explained with a flowchart diagram:

SCP-PF103 | 16
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

An example Java program explaining the functioning of a for loop:

1. package com.oop.loops;
2. import java.io. * ;
3. public class ForLoop {
4. public static void main(String[] args) {
5. int i;
6. for (i = 0; i <= 10; i++) {
7. System.out.println("Studying for loops");
8. System.out.println("Value of i = " + i);
9. }
10. }
11. }
Output

Studying for loops


Value of i = 0
Studying for loops
Value of i = 1
Studying for loops
Value of i = 2
Studying for loops
Value of i = 3
Studying for loops
Value of i = 4
Studying for loops
Value of i = 5
Studying for loops
Value of i = 6
Studying for loops
Value of i = 7
Studying for loops
Value of i = 8
Studying for loops
Value of i = 9
Studying for loops
Value of i = 10

Observe the value of the loop’s control variable i as it increases from 0 to


10 and then stops because the value of i becomes 11 and the condition
becomes false. Hence it goes out of the loop.

While loop in Java


While loops are very important as we cannot know the extent of a loop
everytime we define one. For example if we are asked to take a dynamic
collection and asked to iterate through every element, for loops would be

SCP-PF103 | 17
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

impossible to use because we do not know the size of the collection. Then
we would have to use an enhanced for loop or a while loop.

A while loop iterates through a set of statements till its boolean condition
returns false. As long as the condition given evaluates to true, the loop
iterates.

The condition of the loop structure is checked at first and then the control
proceeds into the loop structure only if the condition evaluates to true.
Hence it is called an entry-controlled loop. The body of the loop generally
contains a variable which controls the boolean condition mentioned.

The basic syntax of Java while loop is:

while(boolean condition) {
//statements;
}

As soon as the condition hits false, the loop terminates.

If you are still confused about the working flow of the while loop, refer
to the flowchart below.

An example java program to illustrate the use of a while loop:


1. package com.oop.loops;
2. import java.io. * ;
3. public class WhileLoop {
4. public static void main(String[] args) {
5. int i = 0;
6. while (i < 5) {
7. System.out.println("Learning Java while loop");
8. System.out.println("The value of i is = " + i);
SCP-PF103 | 18
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

9. i++;
10. }
11. System.out.println("The value of i became " + i + " that is
why it broke out of the loop");
12. }
13.
14. }
Output:
Learning Java while loop
The value of i is = 0
Learning Java while loop
The value of i is = 1
Learning Java while loop
The value of i is = 2
Learning Java while loop
The value of i is = 3
Learning Java while loop
The value of i is = 4
The value of i became 5 that is why it broke out of the loop

do while loop in Java


Java do while loop executes the statement first and then checks for the
condition. Other than that it is similar to the while loop. The difference
lies in the fact that if the condition is true at the starting of the loop the
statements would still be executed, however in case of while loop it would
not be executed at all.

This is an exit-controlled loop because of the fact that it checks the


condition after the statements inside it are executed.

An example Java program to illustrate the use of do while loop:


1. package com.oop.loops;
2. public class DoWhileLoop {
3. public static void main(String[] args) {
4. int i = 0;
5. do {
SCP-PF103 | 19
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

6. i++;
7. System.out.println("Learning Java do-while loop");
8. System.out.println("The value of i is " + i);
9. } while ( i != 5 );
10. }
11. }
Output
Learning Java do-while loop
The value of i is 1
Learning Java do-while loop
The value of i is 2
Learning Java do-while loop
The value of i is 3
Learning Java do-while loop
The value of i is 4
Learning Java do-while loop
The value of i is 5

Notice that even when the condition is false at i=5(bold), the statements
still execute.

For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop


through elements in an array:

Syntax

for (type variableName : arrayName) {

// code block to be executed


}

String[] cars = {"Volvo", "BMW", "Ford",


"Mazda"}; for (String i : cars) {
System.out.println(i);
}

Nested Loops in Java

As the name suggests, nested loops are basically one loop functioning
inside another one. After the first iteration of the outer loop starts, the
inner loop starts. As soon as the innerloop finishes it’s iterations and
exits, the first iteration of the outer loop completes and then it goes for

SCP-PF103 | 20
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

the second iteration. This keeps on repeating till the outermost loop
finishes its iterations.

However nested loops doesn’t necessarily mean two loops. You can
include as many loops as you want inside one another. If there are two
loops one inside another, one of them having N iterations and the other
one having M iterations. Then the total number of iterations would be M
x N.

Basic syntax for a for loop inside a for loop:


for(initializer; condition; increment/decrement) {
for(initializer; condition; increment/decrement) {
//statement(s)
}
}

A java program to understand the concept of nested loops:


1. package com.oop.loops;
2. public class NestedLoop {
3. public static void main(String[] args) {
4. int i, j, k=0;
5. for (i = 0; i < 6; i++) {
6. for (j = 0; j < 6; j++) {
7. System.out.print(k + "\t");
8. k++;
9. }
10. System.out.println("");
11. }
12. }
13. }
Output
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
18 19 20 21 22 23
24 25 26 27 28 29
30 31 32 33 34 35

This is a matrix(6×6) which is made by using a nested for loop.

Some Common Mistakes While Coding Loops

Infinite loop in Java


While designing loops, we can always commit mistakes like forgetting to
update the condition variable or not defining a proper condition which
leads to the loop being run infinite number of times. Different IDE’s have
different mechanisms to stop live execution of code. It’s important to

SCP-PF103 | 21
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

know your own IDE’s shortcut to stop live execution of a program incase
you have the unfortunate incident of java infinite loop.

Example of infinite loop in java:


1. package com.oop.loops;
2. import java.io. * ;
3. public class InfiniteWhileLoop {
4. public static void main(String[] args) {
5. int i = 0;
6. while (i < 5) {
7. System.out.println("Learning Java at DataFlair");
8. System.out.println("The value of i is = " + i);
9. }
10. }
11. }
The program outputs infinite times of the statement and you can see the
value of i remaining the same.

Break and Continue


The break statement can also be used to jump out of a
loop.

Example
This example jumps out of the loop when i is equal to 4:

for (int i = 0; i <


10;i++) {
if (i == 4) { break;
}
System.out.println(i);

This example skips the value of 4:

SELF-SUPPORT: You can click the URL Search Indicator below to


help you further understand the lessons.

Search Indicator
https://www.w3schools.com/java/java_arrays.asp
https://www.guru99.com/java-arrays.html
https://www.geeksforgeeks.org/difference-between-inheritance-and-
polymorphism/ https://www.tutorialspoint.com/java/java_array.htm
SCP-PF103 | 22
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

General Instructions:

1. Answer the activities in the succeeding pages.


2. Submit it in a .PDF format with a filename convention <SURNAME>_<WEEK#>
such that BASTE_WEEK2.
3. The deadline of submission will be 5 days after it was discussed.

Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

NOTE: Put your names in all of your outputs.

LET’S INITIATE!
Activity 2.1. Write a program that prints all even numbers from 1 to 50 inclusive
using the for loop, while loop, and do…while loop. The class name is EvenNum.

Expected output:

Your Source Code:

Your Output:

Activity 2.2. Write a program that sums the integers from 1 to 50 using any
looping statement. The class name is Sum50.
Expected output:

SCP-PF103 | 23
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your Source Code:

Your Output:

Activity 2.3. Write a program that prints every integer value from 1 to 20 along
with its squared value using the following looping structures (for, while, and do-while
loop). The class name is TableOfSquares.
.
Expected output:

Your Source Code:

Your Output:

SCP-PF103 | 24
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INQUIRE!
Activity 2.4. Create a program that will iterate the statement to accept any
character or string value. Afterwards, the program will then count how many special
characters, consonants, and vowels, odd and even digits entered from a console
or a JOptionPane. The program will only terminate if the word “DONE”. Note that a
null value will not be accepted, so prompt a warning message to notify the user. Your
program should be case sensitive.

Your Source Code:

Your Output:

LET’S INFER!
Activity 2.5. Write a fragment of code that will compute the sum of the first n positive
odd integers. For example, if n is 5, you should compute 1 + 3 + 5 + 7 + 9. Thus, the
result is 25. Class name : SumOfNOdd.

Expected Output:

SCP-PF103 | 25
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your Source Code:

Your Output:

Activity 2.6. Write a for statement to compute the sum of an N as an


entered integer 1 + 2² + 3² + 4² + 5² + ... + N².

Expected Output:

Your Source Code:

Your Output:

SCP-PF103 | 26
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics:

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 27
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 3 Arrays
Lesson Title Introduction to Arrays
Learning Students are expected to explore and deepens
Outcome(s) their knowledge more in Arrays.
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

This section provides meaning and definition of the terminologies that are
significant for better understanding of the array concepts.

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

Index is a number associated with each element of an array. It is used to


access elements of an array which always start at 0 to positive integers in
order.

length( ) is a method you can call or use to know the size or length of an
array

[] An array variable can also be declared like other variables with this symbol
after a data type.

One-dimensional Array is an array with only one index or [].

Two-dimensional Array is an array with only two indices or [][].

Multidimensional Array is an array with multiple indices such that


[][][],…[].

Ragged Array is array of arrays such that member arrays can be of different
sizes. It means that is an array with more than one dimension and each
dimension has different size. It is also known as jagged array.

Declaration – Any statement with variable name and a type.

Instantiation - A declaration plus with new keyword and an intention to define


a length which aims to create an allocation to your memory.

Initialization – Any declaration with an intention to give or assign an initial


values to a variable.

SCP-PF103 | 28
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

An array is a collection of elements of same data type referred by a


common name. The elements of the array are stored in consecutive
memory locations.

Types of Array

ü One-dimensional
ü Multidimensional
ü Ragged Array

One-dimensional Array – is an array having only one index.

1D Array : Declaration and Instantiation

Line 3 It declares an array object of int type with num1 variable. No


initial size yet.
Line 4 It instantiates an array object of int type with num2 variable.
The length or size of the array is initialize to 10.
Line 5 is another way to declare an object array where [] comes first
before variable.
Line 6 declares all variables as array objects of type int.
Line 7 declares all variables of type int but NOT all as an array objects
of type int. Only num7, num9, and num10 are arrays.
Line 9 Notice that at Line 3, you just declared the num1 as an array
but with no defined length. This is how you define a length for your array
right after you declare it.

1D Array: Initialization

SCP-PF103 | 29
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Line 3 initializes the array num1 with integers. It has length of 5.


Lines 4 through 6 are arrays that initializes values based on their types
required.

1D Array : Accessing elements through Index

The individual elements can be accessed using the index. The index of
the first elements starts with 0. So, if you have array definition int
array[]=new int[10]. The array has 10 elements which starts at index
[0], then [1],[2],[3],…,[9] index.

Output:
1D Array : Adding elements

When you insert elements to an array, all you need to do is declare an


input statement. Afterwards, you should use any looping structure for
entering value to each index. Look at the codes shown below (Lines 5
through 10).

Based on the above codes on Lines 12 through 15, it displays the values
or elements of an array using a for loop structure. It only means that
elements are stored to an array object. Thus, we are able to retrieve

SCP-PF103 | 30
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

records from it. That is one of the advantage of an array from other simple
variables which are discussed previously.

Modify your codes above same as the codes below:

Though it gives the same output, it does not show retrieval of elements
from an array objects since a normal variable can actually achieve the
same goal even without using an array. The only differ is that arrays store
all elements entered in a contiguous part of your memory while normal
variable only store the recent or last entered value.

1D Array : Changing elements

Changing the elements to your array is simple, you just have to assign a
new value to it via index and then it will be replaced by the new value
you have assigned. Notice that in Line 16, index 2 will be replaced by
‘pineapple’ fruit regardless of what fruit it has assigned previously.

NOTE: You can change the value by allowing the user to enter what fruit
you will replace through asking index from a user and then ask a new fruit
value.
SCP-PF103 | 31
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

1D Array : Removing elements

Java arrays do not provide a direct remove method to remove an element.


In fact, we have already discussed that arrays in Java are static so the
size of the arrays cannot change once they are instantiated. Thus we
cannot delete an element and reduce the array size.

So if we want to delete or remove an element from the array, we need to


employ different methods that are usually workarounds.

2D Array : Declaration

Datatype arrayname[][]=new datatype[row size][column size];

such that

Where the first index is the row value and the second index is the column
which can be denoted as row x column. Thus, 3 x 2 yields to 6 storage.
Below depicts the 3 x 2 table of a 2D array above.

The intersection between 0 and 0 such that [0][0] is an element 3.


While [0][1] is 6, [1][0] is 8, and so on and so forth.

0 1

0 3 6
1 8 9
2 2 12

For example: If we intend to achieve the output above, then this is how you
should do it in a program.

Let us enhance the depiction of the program:

SCP-PF103 | 32
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

NOTE: Adding, accessing, and changing array elements to 2D array


is as the same as doing it in 1D array only that you will need to
use two indices and knows how to distinguish between row and
column.

Ragged Arrays

Continuing with the idea of that a two-dimensional array is an array of


arrays, we can create the array in several steps. First, we declare and
create the linear array:

int[][] rag_array;
rag_array = new int[3][];

To this point, we have created a linear array with three rows, where each
row is an array of integers that have not yet been created. We can create
these arrays separately. This allows us to define different array’s sizes for
each row. For example:

rag_array[0] = new int[2];


rag_array[1] = new int[10];
rag_array[1] = new int[5];

These arrays, where different rows can have different number of columns,
are called ragged arrays. Using as base the program that you created for
getting final grades, define a new program that reads the final grades of
the courses taken by some students and that calculates the GPAs. Since
different students may have taken different number of courses, you
should use a two-dimensional ragged array to keep the information. The
program can ask the user how many students are going to be processed,
and for each student how many courses he/she has taken. After asking
SCP-PF103 | 33
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

the information of all the students, the program has to display the list of
GPAs.

We will discuss and do more examples during code demonstration.

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand
the lessons.

Search Indicator
https://www.w3schools.com/java/java_arrays.asp
https://www.guru99.com/java-arrays.html
https://www.geeksforgeeks.org/difference-between-inheritance-and-polymorphism/
https://www.tutorialspoint.com/java/java_array.htm

General Instructions:

1. Answer the activities in the succeeding pages.


2. Submit it in a .PDF format with a filename convention <SURNAME>_<WEEK#>
such that BASTE_WEEK4.
3. The deadline of submission will be 5 days after it was discussed.

Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

NOTE: Put your names in all of your outputs

LET’S INITIATE!
Activity 1. Answer the following questions.

1. What are the new things that you have discovered in array concepts?

2. How do you apply arrays to your program. Cite an example program you
think it can be applied.

SCP-PF103 | 34
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

3. Are there any things you still don’t understand in array. What are
these and what is/are the reasons?

LET’S INQUIRE!
Analyze the questions below and answer based on your understanding of
the topics. You are free to browse the Internet to look for appropriate
answers or access the online compilers provided in Self-Support section.
1. Program Tracing. Write the output of the program below. Explain
your answer and show your solution.

2. Program Tracing. Write the output of the program below and show
your solution.

LET’S INFER!
NOTE: Include your name in all of your outputs.

Activity 1. Write a simple program that accepts 10 integers and store it


to array object. Afterwards, group all the elements based on the following:
Assume that you have entries:
12,-45,18,-100,50,30,3,-8,9, 1
a. All odd numbers such that -45, 3, 9, 1
b. All even numbers such that 12, 18, -100, 30, -8
c. All negative integers such that -45, -100,-8
d. All positive integers such that 12, 18, 50, 30, 3, 1
SCP-PF103 | 35
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your source codes:

Your output:

Activity 2. Write a program that accepts an integer max value which


denotes as the capacity of your array object. The said value will be the basis
for how many elements your array can store.

Next, is identify the lowest and highest value amongst all integers entered.
Assume that you have this input/output:

Enter max capacity: 5


Input integer : 3
Input integer : 89
Input integer : 69
Input integer : 2
Input integer : 5

The lowest is 2
The highest is 69

Your source codes:

SCP-PF103 | 36
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your output:

Activity 3. Create a program that will define the following properties for
customer:

1. int MAX=10;
2. int customer_ID[]=new int[MAX];
3. String customer_name[]=new String[MAX];
4. int customer_age[]=new int[MAX];
5. Create the following menu:
5.a. [A]dd New Customer - Add New Customer's info (ID, NAME, GENDER, AGE)
5.b. [V]iew Customer - View Customer List (ID, NAME, GENDR, AGE)
5.c. [S]search Customer - Display found customer after search.
- Display NOT found otherwise.
5.d. [E]dit Customer - Modify existing customer's records(only NAME,
GENDER, GENDER). Display NOT found otherwise.
5.e. [D]elete Customer - Remove existing customer's record from array.
Display NOT found otherwise. Perform Cascade
delete.
5.f. [E]nd - Terminates the entire program

NOTE : Avoid possible errors.

Copy the Sample Program:

import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Customer {
public static void main(String[] args) {
String menu[]={"[A]dd Customer","[V]iew Customer","[S]earch Customer", "[E]dit
Customer", "[D]elete Customer", "[E]xit"};
int MAX=10, index=0;
int customer_id[]=new int[MAX];
String customer_name[]=new String[MAX];
String customer_gender[]=new String[MAX];
int customer_age[]=new int[MAX];
String choice="";
do{
choice=JOptionPane.showInputDialog(null, "Please Select", "Menu",
1,null,menu,menu[0]).toString();
switch(choice){
case "[A]dd Customer":

customer_id[index]=Integer.parseInt(JOptionPane.showInputDialog("Customer Id: "));

customer_name[index]=JOptionPane.showInputDialog("Customer Name: ");

customer_age[index]=Integer.parseInt(JOptionPane.showInputDialog("Customer Age: "));

customer_gender[index]=JOptionPane.showInputDialog("Customer Gender: ");


JOptionPane.showMessageDialog(null, "Added new
customer successfully");
index++;

SCP-PF103 | 37
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

break;
case "[V]iew Customer":
String all="Customer's
Info\nID\tName\tAge\tGender\n";
for(int x=0;x<index;x++){

all=all+customer_id[x]+"\t"+customer_name[x]+"\t"+customer_age[x]+"\t"+customer_gender[x]
+"\n";
}
JOptionPane.showMessageDialog(null, new
JTextArea(all));
break;
case "[S]earch Customer":
}
}while(!choice.equals("[e]xit"));
}
}

Your source codes:

Your output:

Activity 4. The Fruit Shop (2D Array )


The John Paul Local shop sells 3 types of fruits:

mango - 45.00 each


durian - 78.97 each
banana - 5.67 each

And this is how many they sold in 5 days. And this is how they
recorded it:

(fruits.txt) - > textfile

Mon Tue Wed Thurs Fri


Mango 12 14 17 19 5
Durian 5 7 10 3 0
Banana 15 12 18 19 12
SCP-PF103 | 38
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Develop a program which will determine as described below:

1. How many Mangoes were sold within 5 days. Display it with its total cost.
(20pts)
2. How many Durian were sold within 5 days. Display it with its total cost.
(20pts)
3. How many Banana were sold within 5 days. Display it with its total cost.
(20pts)
4. How many were sold per day for all the fruits. Display sold fruits per day.
(20)
5. Overall Sales. (20pts)

Your source codes:

Your output:

SCP-PF103 | 39
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 40
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP -TOPICS: PRELIM PERIOD TOPICS

Week 4 Methods and Linear Searching


Lesson Title review methods and introduction to linear
searching.
Students are expected to explore and deepens their
Learning
knowledge more in methods, and linear searching in
Outcome(s)
arrays.
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

This section provides meaning and definition of the terminologies that are
significant for better understanding of the methods and linear searching
concepts.

Methods are group of statements or procedures that invokes an action once it is


called.

Parameter is any argument inside a method heading and during a method call.

Formal parameter is an argument when a method is created or defined.

Actual parameter is an argument when a method is called.

Value returning method is any method that returns a value of any type such as
int, double, float, String, etc.

Non-value returning method is any method that returns nothing. Also known as
void method.

Non-parameterized method is any method having no parameter or argument.

Parameterized method is any method having one or multiple parameters or


arguments

Local Variable is any variable declared inside of a method body.


Global variable is any variable declared outside of any method. It is normally declared
in a class.
Static method is a method that can be called without instantiating an object.

Non-static method is a method that can be called only when you instantiate an
object.
SCP-PF103 | 41
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

A method is group of interrelated statements or codes that performs a


certain actions once it is called. It is also known as function. A method
may or may contain an argument or parameter to which you can pass
data to it.

In programming, it is very important because once a method is defined


or created it can be used or called many times.

Types of Method

ü Predefined method – is a built-in method which you can call as part of


the programming package.
o Examples:
§ nextInt(), nextDouble(), charAt(), toLowerCase(), subString(), etc.
ü User-defined method – a method which is created by someone outside
from an organization or company that created the programming
language. These methods take-on names that you assign to them and
perform tasks that you create.

Syntax:

Example:

Creating your own method.

SCP-PF103 | 42
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

Line 7 It defined a method with name welcomeSpeech().

Line 8 It executes the statement which prints the message Hello


there! My name is Kelsey, how may I help you?

Line 4 a method call. It means you want perform an action associated


in that method. A method can be called any time you want.

Static vs non-static method.

Static method is a method that can be called without instantiating an object. The
above method is an example of this method. You are free to call it without
instantiating an object (Line 4).

On the other hand, non-static method is any method which requires object
instantiation before it can be used or called. Try to remove the keyword static in that
method and you will see an error because it violates such rule.

Line 4 notice that the program gives an error because of the changes you
invoked to it, specifically in Line 7 where you removed the static
keyword.

Now, to make it working all you need to do is modify your codes at Line
4 to this.

Good work!

SCP-PF103 | 43
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Here’s another example where there are multiple methods defined and a
certain method is called more than once.

Output:

Kinds of method.
1. Non-value returning without parameter (Line16)
2. Non-value returning with parameter (Line 25)
3. Value returning without parameter (Line 29)
4. Value returning with parameter (Line 38)

SCP-PF103 | 44
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

Non-value returning without parameter (Line16)

This method requires no parameter, thus no need to sends data to it. Also,
it doesn’t return any value since it was defined as void. Notice that this
kind of methods normally does all the processes inside of a method body.

Non-value returning with parameter (Line 25)

This method doesn’t return any value since it is void, but it requires two
arguments. The formal parameters num1, num2 of type int means that
an int values should be passed to it as an actual parameter.

SCP-PF103 | 45
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Value returning without parameter (Line 29)

This method is similar to Kind 1, only that it returns a value once it is


called.

Value returning with parameter (Line 38)

This method is similar to Kind 2, only that it returns a value once it is


called.

You can modify your main to this without changing the structure of your
method. That is one advantage of a method-based program since you
organized your codes and in case any change you invoked doesn’t
necessarily affect the entire program.

Line 10 is simply assigning the resulting value of a method


addTwoIntegersThird() to sum. Since based on its definition at Line 29,
it returns an int value.

Line 14 The same purpose from Line 10 only that it requires two
arguments or parameters to be valid.

Further, you can freely change your codes in your main without
compromising the defined method.

SCP-PF103 | 46
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

Lines 4 and 5 declares local variables only known to main method.


You can define any name to it as long as you don’t violate naming rules.
The same thing you did at Lines 17, 18, 30, and 31 in page 4. These
variables are locally declared in each method. To avoid confusion, you
might as well use different variable names to it. Whenever you declare a
variable after Line 2, it will now be considered as global variables. Thus,
these variables are known to any method of this class. We will expound
that concept in OOP.

Methods are NOT limited to an int type returning value. You can always
do like these by adding new method definitions to your class.

SCP-PF103 | 47
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Based on the methods above, the first one means that a method returns
double value and requires two double arguments when it is called.
While, the second one requires two double arguments but returns a
String value if it will be called.

Take away:

Based on my experience and knowledge, when creating a method make


sure to remember the following:

1. A good method must have a name and should be meaningful as to


what it will do or its purpose.
2. A good method must only perform specific purpose. Methods with a
lot of things to do can be more confusing.
3. You can freely define method of any ways you like as long as you follow
the correct structure and syntax.

Linear searching. is a method for finding an element within a list. It


sequentially checks each element of the list until a match is found or the
whole list has been searched.

Linear searching can be done in these ways:

• Start from the leftmost element of arr[] and one by one compare x with
each element of arr[]
• If x matches with an element, return the index.
• If x doesn’t match with any of elements, return -1.

Example 1: A program that searches for a number in the list with its
associated index. Once an integer is found, it displays the message at Line
12 and then ends the loop.

SCP-PF103 | 48
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

Example 2: A modified program of Example 1 where it explicitly display


a message if an integer is found or not at all using while-loop.

Output:

SCP-PF103 | 49
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Example 3: A modified program of Example 2 and 3 using a method. The


method returns true and exits the loop once a values is already found.
Otherwise, it returns false.

We will discuss and do more examples during code demonstration.

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the
lessons.

Search Indicator
https://www.geeksforgeeks.org/linear-search/
https://www.w3schools.com/java/java_methods.asp

LET’S INITIATE!
Activity 1. Answer the following questions.

1. What are the new things that you have discovered in methods? List down
all in here.

2. What are your observations in static and non-static methods?

SCP-PF103 | 50
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

3. When do you plan to use the following?


a. Non-value returning without parameter
b. Non-value returning with parameter
c. Value returning without parameter
d. Value returning with parameter

LET’S INQUIRE!
Analyze the questions below and answer based on your understanding of
the topics. You are free to browse the Internet to look for appropriate
answers or access the online compilers provided in Self-Support section.

4. Program Tracing. Write the output of the program below. Explain your
answer and show your solution.

Output:

5. Program Tracing. Write the output of the program below and show your
solution.

Output:

SCP-PF103 | 51
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

6. Program Tracing. Write the output of the program below and show your
solution.

Output:

LET’S INFER!
NOTE: Include your name in all of your outputs.

Activity 1. A class named hi() and hello() will display string “Hi!” and
“Hello!” respectively. The class hi() will impart an action if the word “hi” is
entered, hello() will be called when “hello” is entered. Otherwise, display the
word “JAVA” ten times. The program should then ask how many times will
the string “hi” and “hello” respectively to be passed as parameter for each
method.

Your source codes:

Your output

Activity 2. Given two int values, return their sum. Unless the two values
are the same, then return double their sum.

sumDouble(1, 2) → 3
sumDouble(3, 2) → 5
sumDouble(2, 2) → 8

SCP-PF103 | 52
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your source codes:

Your output:

Activity 3. Create a method definition binary(int val) that will return


the converted decimal equivalent in an entered integers.

Output:

The above program is the answer for this activity using a built-in method.
However, you will create your own method definition without using it as
it shows below:

SCP-PF103 | 53
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your source codes:

Your output:

Activity 4. Create a program that accepts a string value with mix of


letters and numbers. Find how many numbers entered and display these
numbers and where it is located.

Your source codes:

Your output:

Programming Challenge. Create a program that accepts a string value


with mix of letters, numbers, and special characters. Then, find the
following:

a. All letters and its occurrence


b. Consonants and its occurrence
c. Vowels and its occurrence
d. Digits and its occurrence
e. Special characters and its occurrence

SCP-PF103 | 54
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 55
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP -TOPICS: PRELIM PERIOD TOPICS

Week 5 List Structures


Lesson Title ArrayList and Vector
Students are expected to learn dynamic arrays
Learning
such as ArrayList and Vector to store, retrieve,
Outcome(s)
search, and remove elements.
Time Frame

LEARNING INTENT!
Terms to Ponder

This section provides meaning and definition of the terminologies that are
significant for better understanding of the ArrayList and Vector.

java.util package – is a java utilitiy package which consist collections


of classes including ArrayList and Vector.

ArrayList class is a resizable array, which can be found in


the java.util package. It uses a dynamic array for storing the elements.
It is like an array, but there is no size limit.

Vector is like ArrayList, it also maintains insertion order but it is rarely


used in non-thread environment as it is synchronized and due to which
it gives poor performance in searching, adding, delete and update of its
elements.

Constructor – is used to create an object of a class.

Constructors of ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? It is used to build an array list that is


extends E> c) initialized with the elements of the
collection c.

ArrayList(int capacity) It is used to build an array list that has


the specified initial capacity.

SCP-PF103 | 56
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Java Vector Constructors

SN Constructor Description

1) vector() It constructs an empty vector


with the default size as 10.

2) vector(int It constructs an empty vector


initialCapacity) with the specified initial capacity
and with its capacity increment
equal to zero.

3) vector(int It constructs an empty vector


initialCapacity, int with the specified initial capacity
capacityIncrement) and capacity increment.

4) Vector( Collection<? It constructs a vector that


extends E> c) contains the elements of a
collection c.

Essential Content

Hello programmers, Good day!

Welcome back! I’m so glad to see you around writing programs here. We
have been discussing java programming basic constructs. So far, we
knew already how to write programs using conditional statements like if,
if-else, and switch to make our program process decision on its own.
Then, iterations to help us becomes efficient in solving computer
problems. Then, creating our own methods to minimize the lines of code
in our program leads to its readability and accessibility. Lastly, array
which allows us to store, retrieve, search, modify, and delete data. It is
but helpful, however we know that once you use array you must know
how many values it has to store by defining its desired size. Thus, it is
insufficient to store values or records in an array via large amount of data
collection.

Yet, programmers are really great and so Java. Indeed, they created
another better way of keeping the data or records to address problems we
most programmers encounter from using an array. We will name a few
like “ArrayList” and “Vector” that both can be found in array collections
java.util package. It both supports dynamic arrays that can grow as
needed. Standard Java arrays are of a fixed length. After arrays are
created, they cannot grow or shrink, which means that you must know
in advance how many elements an array will hold. Now let’s talk about
ArrayList first.

SCP-PF103 | 57
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

ArrayList is a part of collection framework that provides us with


dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is
needed.

It is created with an initial size. When this size is exceeded, the collection
is automatically enlarged. When objects are removed, the array may be
shrunk. Here are some of its methods that are quite useful in your
program:

SN Methods with Description


1 void add(int index, Object element). Inserts the specified element at
the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index
< 0 || index > size()).
2 void clear(). Removes all of the elements from this list.
3 boolean contains(Object o). Returns true if this list contains the
specified element. More formally, returns true if and only if this list
contains at least one element e such that (o==null ? e==null : o.equals(e)).
4 Object get(int index). Returns the element at the specified position in
this list. Throws IndexOutOfBoundsException if the specified index is is
out of range (index < 0 || index >= size()).
5 int indexOf(Object o). Returns the index in this list of the first
occurrence of the specified element, or -1 if the List does not contain this
element.
6 int lastIndexOf(Object o). Returns the index in this list of the last
occurrence of the specified element, or -1 if the list does not contain this
element.
7 Object remove(int index). Removes the element at the specified position
in this list. Throws IndexOutOfBoundsException if index out of range
(index < 0 || index >= size()).
8 Object set(int index, Object element). Replaces the element at the
specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is out of range (index
< 0 || index >= size()).
9 int size(). Returns the number of elements in this list.

Now, let’s get some few programming. While doing it, I want you to answer
each question (your observation) as you walk through the following
pages in an A4 bondpaper.

1. Create a class named “MyList”. Then, type the statement at Line 2.

SCP-PF103 | 58
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

2. Type the statements from Line 5 to Line 7.

- Line 5 means that it only holds String values such as “hello”,


“programmers”, and etc.

o Type Line 9 through Line 11. Observe that Line 11 displays error
warning since strList is an object of an ArrayList which only holds String
values. See Line 5.
o Change Line 11 from strList.add(50); to strList.add(“50”);.

What did you observe?


Observation 1:

- Line 6 means that it only holds integer values such as 4, 6, etc.


- Thus, Line 7 holds only double values as 8.9, 5.0, 69.9, and so on.
3. See below program, insert the further statements.

- Explain how you perceive the above codes from Line 9 through Line
19.
SCP-PF103 | 59
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Observation 2:

4. Remove the rest of the codes in your main method. Then, type the
following fragment of codes from Line 7 to Line 10.

Observation 3:
Describe the statement in Line 7.

What is the display output of Line 9?

What is the display output of Line


10?

5. Add the following code snippets (in blue highlights) to your program:

Observation 4:
What is the value of
petList.size() now in Line
15?
How about petList.isEmpty()
in Line 16?

Explain the scenarios above


on how did you grasp it?

6. Add the following codes below:


SCP-PF103 | 60
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

petList.add("Popsy");
petList.add("Pink");
JOptionPane.showMessageDialog(null, petList.get(1));

Observation 5:
Which pet do you think is
accessed by petList.get(1)?
How about petList.get(2)?

What about petList.get(5)?

7. Add the codes below in your program.

petList.add("Toothless");
petList.add(3,"Jerry");
JOptionPane.showMessageDialog(null, petList);

Your program this time should have looked like below:

Observation 6:
Explain how do you understand
petList.add("Toothless"); ?

What about petList.add(3,"Jerry"); ?

JOptionPane.showMessageDialog(null,petList);
What is the display?

SCP-PF103 | 61
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

8. If you add this petList.add(0, "Tom");after Line 23. What is the new
sequence of elements in the petList?

Observation 7:

9. Add this code in your program

Observation 8:
Write here the display output of Line 30.

10. What happen to the list of pets when below statements are
invoked? Write the value or output as prescribed.

Observation 9:
JOptionPane.showMessageDialog(null,
petList.remove(0));
JOptionPane.showMessageDialog(null, petList);
String petDel=petList.remove(4);
JOptionPane.showMessageDialog(null, petDel);
JOptionPane.showMessageDialog(null,
petList.contains("Toothless"));
JOptionPane.showMessageDialog(null,
petList.remove(3));
JOptionPane.showMessageDialog(null,
petList.contains("Jerry"));
petList.set(3,"Lorax");
JOptionPane.showMessageDialog(null, petList.get(3));
petList.remove("Tom");
JOptionPane.showMessageDialog(null, petList);
petList.clear();
JOptionPane.showMessageDialog(null, petList);

SCP-PF103 | 62
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

11. So that is how it should be. I wish you all the best in coding.
Here’s the complete program for this activity.

Observation 10: Run the program and discus here your


observation about the output.

Vector is very similar to ArrayList. In fact changing the above codes of


your ArrayList, particularly at the Line 7 doesn’t matter at all as it would
work the same. Try changing it to this:

Vector <String> petList=new Vector<String>();

Commonly used methods of Vector Class:

1. void addElement(Object element): It inserts the element at the end of


the Vector.
2. int capacity(): This method returns the current capacity of the vector.
3. int size(): It returns the current size of the vector.
SCP-PF103 | 63
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

4. void setSize(int size): It changes the existing size with the specified
size.
5. boolean contains(Object element): This method checks whether the
specified element is present in the Vector. If the element is been found it
returns true else false.
6. boolean containsAll(Collection c): It returns true if all the elements of
collection c are present in the Vector.
7. Object elementAt(int index): It returns the element present at the
specified location in Vector.
8. Object firstElement(): It is used for getting the first element of the
vector.
9. Object lastElement(): Returns the last element of the array.
10. Object get(int index): Returns the element at the specified index.
11. boolean isEmpty(): This method returns true if Vector doesn’t have any
element.
12. boolean removeElement(Object element): Removes the specified
element from vector.
13. boolean removeAll(Collection c): It Removes all those elements from
vector which are present in the Collection c.
14. void setElementAt(Object element, int index): It updates the element
of specifed index with the given element.

NOTE: You must know that capacity() method doesn’t exist in


ArrayList.

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the
lessons.

Search Indicator
https://www.javatpoint.com/java-arraylist
https://www.geeksforgeeks.org/arraylist-in-java/
https://beginnersbook.com/2013/12/java-arraylist/
https://www.geeksforgeeks.org/java-util-vector-class-java/

SCP-PF103 | 64
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INITIATE!
Activity 1. Answer the following questions.

1. What are the benefits of using dynamic arrays compare to fixed-sized


arrays?

2. List down here your observations about the major differences of ArrayList
and Vector?

ArrayList Vector

3. List down here atleast 3 dynamic arrays in Java. Explain briefly.

LET’S INQUIRE!
Activity 2. Analyze the questions below and answer based on your
understanding of the topics. You are free to browse the Internet to look for
appropriate answers or access the online compilers provided in Self-
Support section.

7. Program Tracing. Write the output of the program below.

SCP-PF103 | 65
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

SCP-PF103 | 66
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

8. Program Tracing. Write the output of the program below.

Output:

9. Program Tracing. Write the output of the program below.

Output:

SCP-PF103 | 67
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INFER!
NOTE: Include your name in all of your outputs.

Activity 3. Create a myPetList as an object of an ArrayList class named


PetRecordsSystem. Then, create menu list for the following requirement
specifications:

[A]dd - Allow user to add pet name in a list.


[I]nsert - Insert pet’s name to a specific position of a list.
[S]earch - Display found pet’s name after searching from a list
[E]dit - Modify pet’s name to an existing element from a list.
[V]iew - View all data in a list
[D]elete - Erase pet’s name from a list.
[C]ount - Display the total size of an ArrayList.
[T]erminate - Terminate the entire program.

Note that the program should not terminate while T is not chosen.

Your source codes:

Your output

Activity 3. Create fruitList as an object of a Vector class


named FruitOrderingSystem that will store name of fruit, stocks, and
its price. Then, create menu list for the following requirement
specifications:

• Add New Fruit- Allow user to add fruit's information in a vector.


• Add New Stock- Allow user to add new stocks to fruit's current
stock.
• Insert - Insert fruit's information to a specific position of a
vector.
• Search - Display found fruit's information after searching from
a vector. {Search by index and by value}

SCP-PF103 | 68
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

• Edit - Modify fruit 's information to an existing element from a


vector. {Edit by index and by value}
• View - View all data of a vector.
• Delete - Erase fruit 's information from a vector. {Delete by index
and by value}
• Count - Display the total size of a vector.
• Terminate - Terminate the entire program.

Note that the program will end if Terminate is selected.

Your source codes:

Your output

SCP-PF103 | 69
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 70
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP -TOPICS: MIDTERM PERIOD TOPICS

Week 7 Introduction to OOP


Lesson Title OOP Concepts and UML Diagram
Discuss the concepts of Object oriented principles
Learning
and design unified modeling language (UML)
Outcome(s)
model of a class.
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

Object-oriented programming (OOP) refers to a programming


methodology based on objects, instead of just functions and procedures.
The objects contain the data and the methods (or behavior). In order to
fully understand its concepts, the following terminologies are important
to understand:

Programming Paradigm is a way to classify programming languages


based on their features.
Procedural Programming is a programming model which is derived
from structured programming, based upon the concept of calling
procedure.
Object Oriented Programming (OOP) - models the real world well and
overcomes the shortcomings of procedural paradigm.
Class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
Object can be defined as a data field that has unique attributes and
behavior.
Encapsulation is the wrapping up of data and associated functions into
a single unit.
Inheritance allows classes (subclasses) to use the members of another
class (superclass) as their own members. We use the keyword extends
to make a class a subclass of a superclass.
Polymorphism adds flexibility to the programming. Java provides two
kinds of polymorphism: method overriding and overloading.
Data member − A class variable or instance variable that holds data
associated with a class and its objects.
Class variable − A variable that is shared by all instances of a class.
Class variables are defined within a class but outside any of the class's

SCP-PF103 | 71
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

methods. Class variables are not used as frequently as instance variables


are.
Instance Variables. Data fields in a class declaration

Essential Content

Paradigm: It means organizing principle of a program. It is an approach


to programming.

Procedural Paradigm-the emphasis is on doing things i.e., the procedure


or the algorithm. The data takes the back seat in procedural
programming paradigm. Also, this paradigm does not model real world
well.

Object Oriented programming - models the real world well and


overcomes the shortcomings of procedural paradigm. It views a problem
in terms of objects and thus emphasizes on both procedures as well as
data.

Advantages of OOP

• Simplicity. Software objects model real world objects.


• Modularity. Each object forms a separate entity whose internal
workings are decoupled from other parts of the system.
• Modifiability. It is easy to make minor changes in the data
representation or the procedures in an object-oriented program.
• Extensibility. Adding new features or responding to changing
operating environments can be solved by introducing a few new objects
and modifying some existing ones.
• Maintainability. Objects can be maintained separately, making
locating and fixing problems easier.
• Re-usability. Objects can be reused in different programs.

Procedural Programming
• Emphasis on doing things (function)
• Follow top-down approach in program design
• Due to presence of global variables, there are possibilities of
accidental change in data.

Object-Oriented vs. Procedural Programming


OOP Procedural Programming
Program is divided into small Program is divided into small parts
parts called objects. called functions.
Follows bottom up approach. Follows top down approach.
Have access specifiers like No access specifier in procedural
private, public, protected etc. programming.

SCP-PF103 | 72
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Adding new data and function is Adding new data and function is
easy. not easy.
Provides data hiding so it is No proper way for hiding data so it
more secure. is less secure.
Overloading is possible. Overloading is not possible.
Data is more important than Function is more important than
function. data.
Based on real world. Based on unreal world.
Examples: C++, Java, Python Examples: C, FORTRAN, Pascal etc.
etc.

Fundamentals of object-oriented programming

Object-oriented programming is a programming paradigm where


everything is represented as an object. Objects pass messages to each
other. Each object decides what to do with a received message. OOP
focuses on each object’s states and behaviors. Just like a real-life entity,
an object has two major characteristics :

• Data or States (Property) – tells about the attributes and the state of
the object. Such that a dog has the breed, gender, and age.
• Behavior – gives it the ability to change itself and communicate with
other objects or functionality of an object. Such that a dog can bark, sleep,
and eat.
• Identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. But it is used internally by the JVM to
identify each object uniquely. Such that a dog’s name is Cortana.

For example: Chair

To illustrate, a chair has states like shape, color, material, or brand, etc.
and behaviors it can spin, it will fold, swing, and so on.

SCP-PF103 | 73
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

A chair’s State tells us how a it should looks or what properties it has


while its behavior tells us what the chair does.

For example: Dog

To illustrate, a dog can be described based on it data (states) like name,


color, breed, etc. While its behavior is it can bark, fetch, and wags its
tail.
For example: Car

To illustrate, a car be
described based on its
properties like make, model, color, year, price and so on. While, it does
its purpose like start, drive, park, accelerate, etc.

We can actually represent a real world chair, car, and a dog in a


program as a software object by defining its states and behaviors.

There are two main aspects of OOP:

1. Class. class is a template or blueprint from which objects are


created.
2. Object. Instance of a class

An illustration below will show the difference between Class and Object.

CLASS OBJECT
Fruit Apple

Orange

Banana

SCP-PF103 | 74
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Components of Class
1. Modifiers: A class can be defined to any of the following modifiers:
o public: Indicate that the class can be instantiated or extended by any
class. Without the public class modifier, the class can be used and
instantiated by all classes in the same package.
o abstract: Indicate that the class has abstract methods. Abstract
methods are declared with the abstract keyword and do not have the
body of code.
o final: Indicate that the class can have no subclasses.

2. Class name: Name should begin with an initial letter (capitalized by


convention).

3. Superclass (if any): The name of the class’s parent (superclass), if


any, preceded by the keyword extends.

Assume that Animal is declared as a class, it is a superclass of Dog.

All created classes in java has inherited the Object superclass by default.

4. Interfaces (if any): A comma-separated list of interfaces implemented


by the class, if any, preceded by the keyword implements.

SCP-PF103 | 75
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

5. Body: The class body surrounded by opening and closing braces.

Syntax:
class modifier class class_name {
private: members1;
protected: members2;
public: members3;
}
Class Members

The members of a class are classified into three categories. These are
reserved words and are called member access specifiers. These
specifiers modify the access rights that the members following them
acquire:

1. private members. Only methods of the same class can call the
method.
2. protected members. Only methods of the same package or of
subclass can call the method.
3. public members. Anyone can call the data member/method.

Class variables/methods and constants

1. static: A variable that is associated with the class, not with individial
instances of the class.
2. final: A variable that must have an initial value. And the value cannot
be changed. Used to define constant.

SCP-PF103 | 76
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Instance(Object) variables. Is any variable/method declared without


static or final keywords.

Objects. A new object in Java is created by using the new operator.

CONSTRUCTOR - It is a member function having same name as its class


and which is used to initialize the objects of that class type with a legal
initial value. Constructor is automatically called when object is created.

SCP-PF103 | 77
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Types of Constructor Default Constructor. A


constructor that accepts no
parameters is known as
default constructor. If no
constructor is defined then
the compiler supplies a
default constructor.

Parameterized Constructor.
A constructor that receives
arguments/parameters, is
called parameterized
constructor.

Copy Constructor. A
constructor that initializes
an object using values of
another object passed to it
as parameter, is called copy
constructor. It creates the
copy of the passed object.

NOTE: There can be multiple constructors of the same class, provided


they have different signatures. This feature is called constructor
overloading.

Dog Class : In a nutshell

1. Assume that a Dog class that represents states and behaviors of real
world Dog.

SCP-PF103 | 78
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

2. Now we have successfully defined a template for Dog. Let’s say we


have two dogs. Let’s name them Cortana and Kodu. Create a TestDog
class.

SCP-PF103 | 79
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

NOTE: You can put comments to error and run your program to see the
result.

3. You can also change the object to dog1 and dog2 respectively instead
of Cortana and Kodu.

4. Like the above code examples, we can define our class, instantiate it
(create objects) and specify the states and behaviors for those objects.
Note that there are certain limitations and constraints you defined for
your class Dog making its data members/properties inaccessible like if
you use private, protected, or if it was declared as final, hence it cannot
change its values then. So, make sure you understand them very well.
5. Modify your Dog class as shown below:

SCP-PF103 | 80
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

NOTE: The above program shows an example of overloaded


constructor. It means that there are different versions of constructors
having different behaviors.

6. And your TestClass to this.

Notice that as you type any object of Dog, it will show you with methods
defined associated with its returning type. Look at the figure below:

7. Run your program now and expect this output:

8. If you would like you can also add some additional methods like these
in between Lines 55 and 56.

SCP-PF103 | 81
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

9. And so you can implement or invoke them right away in your program
just like this:

Basic OOP Principles. There are 4 major principles that make a language
Object Oriented.

Encapsulation

is the mechanism of hiding of data implementation by restricting access


to public methods. Instance variables are kept private and accessor
methods are made public to achieve this.

For example, we are hiding the name and dob attributes of person class
in the below code snippet.

Encapsulation — private instance variable and public accessor methods.

public class Employee {


private String name;
private Date dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}

SCP-PF103 | 82
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Abstraction. Abstract means a concept or an Idea which is not


associated with any particular instance. Using abstract class/Interface
we express the intent of the class rather than the actual implementation.
In a way, one class should not know the inner details of another in order
to use it, just knowing the interfaces should be good enough.

Inheritance expresses “is-a” and/or “has-a” relationship between two


objects. Using Inheritance, In derived classes we can reuse the code of
existing super classes. In Java, concept of “is-a” is based on class
inheritance (using extends) or interface implementation
(using implements).

Polymorphism. It means one name with many forms or behaviors. It is


further of two types — static and dynamic. Static polymorphism is
achieved using method overloading and dynamic polymorphism using
method overriding. It is closely related to inheritance. We can write a code
that works on the superclass, and it will work with any subclass type as
well.

Object-oriented designing (OOD)

Design: specifying the structure of how a software system will be written


and function, without actually writing the complete implementation. It is
a transition from "what" the system must do, to "how" the system will do
it.

SCP-PF103 | 83
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

• What classes will we need to implement a system that meets our


requirements?
• What fields and methods will each class have?
• How will the classes interact with each other?

Project Scope/Specifications

It is a class identification from project specification/ requirements

• nouns are potential classes, objects, fields


• verbs are potential methods or responsibilities of a class

Steps in designing classes

• write down classes' names on index cards


• next to each class, list the following:
o responsibilities: problems to be solved; short verb phrases
o collaborators: other classes that are sent messages by this class
(asymmetric)

A Unified Modeling Language (UML) diagram is a modern approach to


modeling and documenting software. In fact, it’s one of the most
popular business process modeling techniques.

It is based on diagrammatic representations of software components.


As the old proverb says: “a picture is worth a thousand words”. By using
visual representations, we are able to better understand possible flaws or
errors in software or business processes.

Facts about UML Diagram:

1. UML is an open standard; lots of companies use it


2. a descriptive language: rigid formal syntax (like programming)
3. a prescriptive language: shaped by usage and convention
4. it's okay to omit things from UML diagrams if they aren't needed by
team/supervisor/instructor

SCP-PF103 | 84
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Uses for UML

1. As a sketch: to communicate aspects of system


a. forward design: doing UML before coding
b. backward design: doing UML after coding as documentation
c. often done on whiteboard or paper
d. used to get rough selective ideas
2. As a blueprint: a complete design to be implemented.
a. sometimes done with CASE (Computer-Aided Software) like EDraw
Max, MS Word, etc.
3. As a programming language: with the right tools, code can be auto-
generated and executed from UML.
a. only good if this is faster than coding in a "real" language

Class Diagram is a type of UML diagram used by java to show a picture of the
classes in an OO system, their fields and methods, and connections between the
classes that interact or inherit from each other.

In software engineering, a class diagram in the Unified Modeling Language


(UML) is a type of static structure diagram that describes the structure of a system
by showing the system's classes, their attributes, operations (or methods), and the
relationships among objects. A class notation consists of three parts:

1. Class Name
• The name of the class appears in the first partition.
2. Class Attributes
• Attributes are shown in the second partition.
• The attribute type is shown after the colon.
• Attributes map onto member variables (data members) in code.
3. Class Operations (Methods)
• Operations are shown in the third partition. They are services
the class provides.
• The return type of a method is shown after the colon at the end
of the method signature.
• The return type of method parameters is shown after the colon
following the parameter name.

SCP-PF103 | 85
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

A sample UML Class diagram from above Dog class that we have created
earlier.

Dog

+ name : String
- breed : String
- gender : String
+ age : int
# price : double
+ Dog() : Dog
+ Dog(String) : Dog
+ Dog (Sting, int) : Dog
+ storeDate(String, int, double) : void
+ display() : String

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the
lessons.

Search Indicator
https://www.visual-paradigm.com/guide/uml-unified-modeling-
language/what-is-class-diagram/
https://www.visual-paradigm.com/guide/uml-unified-modeling-
language/uml-class-diagram-tutorial/
https://howtodoinjava.com/java/oops/object-oriented-programming/
https://www.freecodecamp.org/news/java-object-oriented-
programming-system-principles-oops-concepts-for-beginners/
https://raygun.com/blog/oop-concepts-java/

SCP-PF103 | 86
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INITIATE!
Activity 1. Answer the following questions.

4. As you were writing programs implementing OOP, what are the benefits
or what are the things that changes your way of coding and how it affects
you as a programmer?
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.
5. Why do you think UML class diagram is also important in designing and
developing a good program?
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.
6. Think of a real world object you want to model or simulate. Afterwards, I
want you to create a UML class diagram out of it? Make sure to indicate
proper data or state and behavior of a class. Also, apply necessary visibility
in your diagram.

SCP-PF103 | 87
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INQUIRE!
Program Tracing. Write the output of the followinng program.

Output:

UML Class Diagram. Create a UML diagram based on the following class.

SCP-PF103 | 88
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

UML:

SCP-PF103 | 89
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INFER!
Programa Perfeckta, Inc. sent you a UML class diagram for this week as one of the
modules in the Banking Management System you are developing for ABC Bank
Corporation. Your task is to convert this class diagram into a java class as soon as
possible. Here’s the details of the said class diagram:

BAccount
- accountNo : int
- accountBalance : float
# transactDate :
DateTime

+ BAccount() : BAccount
+ BAccount(int accountNo, float accountBalance) : BAccount
+ setAccount(int accountNo, float accountBalance): void
+ performTrans (char transactType) : void
+ transactionAmount (float amount) : void
+ getAccountNo () : int
+ getBalance () : float
- transactionLogs() : void

Write your codes here (BAccount.java)

SCP-PF103 | 90
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics:

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 91
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 8 Principle 1 : Encapsulation


Lesson Title Encapsulation
Discuss the first OOP principle, Encapsulation
Learning
with its underlying concepts, creating setter and
Outcome(s)
getter, and data hiding.
Time Frame

At SJPIICD, I Matter!

LEARNING INTENT!
Terms to Ponder

One of the most important concepts in OOP is the principle of


Encapsulation. It refers to the bundling of fields and methods inside a
single class. By bundling similar fields and methods inside a class
together also helps in data hiding. Below are some of the terminologies
you would need to familiarized in order for you to understand the concept
of Encapsulation as a whole.

Abstraction. A technique for arranging complexity of computer systems


so that functionality may be separated from specific implementation
details.
Encapsulation. A language mechanism for restricting direct access to
some of an object’s components.
Data/Information hiding. The principle of segregation of the design
decisions in a computer program from other parts of the program. See
encapsulation.
Mutator. A method used to control changes to a private member variable,
also known as a setter method.
Accessor. A method used to return the value of a private member
variable, also known as a getter method.
Private. An access modifier that restricts visibility of a property or
method to the class in which it is defined.
Public. An access modifier that opens visibility of a property or method
to all other classes

SCP-PF103 | 92
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

Encapsulation is a mechanism to wrap up variables(data) and


methods(code) together in a single unit called a class. One of the few
benefits of this principle is that it hides information details, and being
able to protect the data and behavior of the object. In fact creating a class
means it is easy to test and better for unit testing.

In Java, it can be achieved by:

• Declaring the variables of a class as private.


• Providing public setter and getter methods to modify and view the
variables values.

Encapsulate : Why would I do it?

Suppose a hacker managed to gain access to the code of school’s students


account. There can be two ways to override or hack the said code. Below
is a sample code of your StudentAccount class.
Approach #1: A hacker tries to pay an invalid amount such as any
negative value to manipulate the code.

SCP-PF103 | 93
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Aw! Snap. The first approach was a complete failure. It is Not possible
because a variable studBalance (Line 3) was declared as private in
StudentAccount class. It only means that the said variable can only be
accessed within the class where it was defined. Hence, no other class or
object can access them. As you can notice at Line 4 in StudentHacker
caused an error.

NOTE that mathematically, when the above attempt was successful, student balance
can have value of -5000. So, what does it means? Simple. He can file a complaint that
he might over paid the school which made the school to pay 5000 pesos on him. And
it can increase if let it is repeatedly done. (I mean some sort of).

Approach 2: Since the first approach was an epic fail. He tried to pay an
amount of -5000 by using pay method.

Approach #2 seemed to work this time. But little did he know that a
method has a validation/condition to meet. When he attempted to run
his program, it has a check condition for any negative entry. Hence, the
second attempt was a failure too displaying the prompt message below
and making the student’s balance unchanged.

Thus, you should never expose your data to an external party. Which
makes your application becomes more secured. The entire code
(StudentAccount) can be thought of a capsule, and you can only
communicate through the messages. With this concept, developers can
change one part of the code easily without affecting other.

SCP-PF103 | 94
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Data Hiding. Is a way of restricting the access of our data members by


hiding the implementation details from the user. Encapsulation also
provides a way for data hiding. But more than data hiding, it is meant for
better management or grouping of related data.

Data hiding can be achieved with the help of access modifiers. Recall in
our previous topics, there are four access modifiers:
• public - visible from anywhere. ()
• private - visible from only within the class
• protected - visible within the package, and among its subclasses
• default - visible within the package

To achieve a higher degree of encapsulation in Java, you can use


modifiers like "private" followed by default (no specifier). The other two
modifiers makes a lesser degree of encapsulation.

Let’s Get Set Aw!


Getter and Setter property are two conventional methods used to
retrieve and update values of a variable. They are mainly used to create,
modify, delete and view the variable values.
The setter (mutator) method is used for updating values. While the
getter (accessor) method is used for reading or retrieving the values.
The following code is an example of getter and setter methods:

In above example, getStudBalance() Line 34 and getStudID() Line 33


methods are a getter methods that reads value of variable studID and
studBalance. While setID() Line 25 and setBalance() Line 28 methods
are setter methods that sets or update value for variable studID and
studBalance respectively.

Below is the complete code for StudentAccount class:

SCP-PF103 | 95
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

NOTE: In java, is a good practice to name a method for setter and getter
with set and get prefixes respectively.

getName() // provides read-only access


setName() // provides write-only access
where name is any name or word that represents the value (which is
normally based on the name of a variable).
Advantages of Encapsulation:

• Data Hiding: The user will have no idea about the inner
implementation of the class. It will not be visible to the user that how the
class is storing values in the variables. He only knows that we are passing
the values to a setter method and variables are getting initialized with
that value.

• Increased Flexibility: We can make the variables of the class as read-


only or write-only depending on our requirement. If we wish to make the
variables as read-only then we have to omit the setter methods like
setName(), setAge() etc. from the above program or if we wish to make the
variables as write-only then we have to omit the get methods like
getName(), getAge() etc. from the above program.
SCP-PF103 | 96
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

• Reusability: Encapsulation also improves the re-usability and easy


to change with new requirements.

• Testing code is easy: Encapsulated code is easy to test for unit


testing.

Encapsulation: Encapsulating a class.

1. Create a Student (encapsulated) class.

2. Create a TestStudent class.

SCP-PF103 | 97
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

3. You can convert this to array and then we can now use loop to retrieve
all students information.

Output:

SCP-PF103 | 98
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Notice that the age of Kyle, Anna and Honey are NOT calculated
properly since we only put a codes for processing the current year
(conversion) at default constructor. See Line 13 to 17 in Student class.
Unless you will add this method to your Student class:

And then do some modification in every all of your constructor in Student


class just like below:

Similarly, Anna’s average was NOT calculated too because we did not call
the setAverage method. Unless you will write it after Line 19.

And then you will derive this output:

SCP-PF103 | 99
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

If you would like to arrange it to present a better data formation, you will
need to change Anna’s course to “BSA” to balance the number of String
values, do some “\t” or anything you can think or imagine to fix it. Here
are some codes that I have modified:

st[1].setMonth("January");

to

st[1].setMonth("Jan");

st[2]=new Student(003,"Anna","BS Astronaut","June",14,2014);

to

st[2]=new Student(003,"Anna","BSA","June",14,2014);

to

Output:

4. You can also add this additional setters and getters for our Student
class.

SCP-PF103 | 100
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

And use them in your TestStudent class.

Output:

SCP-PF103 | 101
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Notice that average is NOT calculated since we did NOT include it our
setStudentInfo method. If you like you can do it by yourselves.
5. Here’s the UML of the above Encapsualted class:

6. Based on the above steps, I hope you are able to grasp that you can
do whatever you like to your Encapsulated class as long as you make the
data member secured from user.
7. Complete code for Student class:
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class Student {
private int studID;
private String name;
private String month;
private int day, year, age;
private String course;
private double average;
private int currYear;

public Student() {

SCP-PF103 | 102
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

setCurrYear(); //Add this


}
public Student(int studId, String name,String course) {
setStudID(studId);
setCourse(course);
setName(name);
setCurrYear(); //Add this
}

public Student(int studId, String name,String course, String month, int day, int year) {
setStudID(studId);
setCourse(course);
setName(name);
setBirthdate(month, day, year);
setCurrYear(); //Add this
}

public Student(int studId, String name,String course,


String month, int day, int year,
double prelim, double midTerm, double finalTerm) {
setStudID(studId);
setCourse(course);
setName(name);
setBirthdate(month, day, year);
setAverage(prelim, midTerm, finalTerm);
setCurrYear(); //Add this
}

//Setters
public void setStudID(int studID) { this.studID = studID; }
public void setName(String name) { this.name = name; }
public void setMonth(String month) { this.month = month; }
public void setDay(int day) { this.day = day; }
public void setYear(int year) { this.year = year; }
public void setBirthdate(String month, int day, int year) {
setMonth(month);
setDay(day);
setYear(year);
}
public void setCourse(String course) { this.course = course; }
public void setAverage(double prelim, double midTerm, double finalTerm) {
this.average = (prelim+midTerm+finalTerm)/3;
}
public void setAge() { age=currYear-year; }
//Getters
public int getStudID() { return studID;}
public String getName() { return name; }
public double getAverage() { return average; } public String getMonth() { return month; }
public int getDay() { return day; }
public int getYear() { return year; }
public String getCourse() { return course; }
public int getAge() {
setAge();
return age;
}
public String getBirthdate() { return month+" "+day+", "+year; }

public void setCurrYear() {


Date d = new Date();
LocalDate localDate = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
currYear = localDate.getYear();
}

//Additional setter
public void setStudentInfo(int studId, String name,String course, String month, int day, int year) {
setStudID(studId);
setCourse(course);
setName(name);
setBirthdate(month, day, year);
}

//Additional getters
public String getStudentInfo1() {
return getStudID()+"\t"+getName()+"\t"+getCourse()+"\t"
+ getBirthdate()+"\t"+getAge()+"\t"+String.format("%.2f", getAverage())+"\n";
}
public String getStudentInfo2() {
return "ID\t: "+getStudID()
+"\nName\t: "+getName()
+"\nCourse\t: "+getCourse()
+"\nBirthdate\t: "+ getBirthdate()
+"\nAge\t: "+getAge()
+"\nAverage\t: "+String.format("%.2f", getAverage())+"\n";
}
public void getStudentInfo3() {
System.out.println("ID\t: "+getStudID()
+"\nName\t: "+getName()
+"\nCourse\t: "+getCourse()
+"\nBirthdate\t: "+ getBirthdate()
+"\nAge\t: "+getAge()
+"\nAverage\t: "+String.format("%.2f", getAverage())+"\n");
}

}//End of Class

8. Modify your TestStudent to this:


import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class TestStudent {


public static void main(String[] args) {
String menu[]={"Add Student","View All","Search","Edit","Delete","End"};
String choice="",hold="";
JOptionPane j=new JOptionPane();

int i=0;
String name, course;
int id;

Student st[]=new Student[5]; //Array object for Student

do{
choice=j.showInputDialog(null,"Select","Menu",1,null,menu,menu[0]).toString();
switch(choice){
case "Add Student":
if(i<st.length) {
id=Integer.parseInt(j.showInputDialog("ID: "));
name=j.showInputDialog("Name: ");
course=j.showInputDialog("Course: ");
String birthdate[]=j.showInputDialog("Type [mm/dd/yy] in this format:
").split("/");
String average[]=j.showInputDialog("Type [prelim, midterm, final] separated by
comma: ").split(",");

st[i]=new Student();

SCP-PF103 | 103
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

st[i].setStudentInfo(id, name,
course,birthdate[0],Integer.parseInt(birthdate[1]),Integer.parseInt(birthdate[2]));
st[i].setAverage(Double.parseDouble(average[0]), Double.parseDouble(average[1]),
Double.parseDouble(average[2]));
hold="Student records successfully added.";
i++;
j.showMessageDialog(null, hold);
}else {
hold="Storage is full.";
}
break;
case "View All":
hold="ID\tName\tCourse\tBirthdate\tAge\tAverage\n";
for (int a = 0; a < i; a++) {
hold+=st[a].getStudentInfo1();
}
j.showMessageDialog(null, new JTextArea(hold));
break;
case "Search":
break;
case "Edit":
break;
case "Delete":
break;
case "End":
} //end of switch
}while(!choice.equals("End"));
}
}

Abstraction is a process of hiding the implementation details and


showing only functionality to the user. It only shows essential things to
the user and hides the internal details.

For example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does
it. In java it can be achieved using the keyword abstract. We will discuss
this in a few weeks.

Abstraction vs. Encapsulation

Often encapsulation is misunderstood with Abstraction.

• Encapsulation is more about "How" to achieve a functionality


• Abstraction is more about "What" a class can do.

A simple example to understand this difference is a mobile phone. Where


the complex logic in the circuit board is encapsulated in a touch screen,
and the interface is provided to abstract it out.

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the
lessons.

Search Indicator
https://www.guru99.com/java-oops-class-objects.html
https://beginnersbook.com/2013/05/encapsulation-in-java/
https://www.programiz.com/java-programming/encapsulation
https://www.edureka.co/blog/encapsulation-in-java/
https://www.geeksforgeeks.org/encapsulation-in-java/

SCP-PF103 | 104
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INITIATE!
Activity 1. Answer the following questions.

7. Write the new things that you have learned in the first OOP principle
which is Encapsulation?
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.
8. Choose the any of the following (Flower, Car, Jeans). Create an
encapsulated class out of it?
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.
9. Create a test class of your chosen item above. Implement the methods
that you have created in it and print a sample output.

LET’S INQUIRE!
Object Modeling. Decide a real-world object that you find interested to model as a class
(to encapsulate), then make a UML diagram and provide description of each method.
Afterwards, create a class implementation of the said object.

Example: Consider a WaterTank as class being encapsulated with below UML and method
definition:

WaterTank
- Capacity: int
- CurrentWater : int
+ WaterTank() : WaterTank
+ WaterTank(int capacity) : WaterTank
+ isFull() : boolean
+ isEmpty() : boolean
+ fillWater(int quantity) : void
+ removeWater(int quantity) : void
+ currentWater() : int
+ setCapacity(int capacity) : void
+ getCapacity() : int
+ clearWater() : int

SCP-PF103 | 105
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Definition:

a) WaterTank() -initializes current water to 0 and capacity to 1000.


b) WaterTank(int capacity) -capacity is based on its parameter, initializes current water
to 0.
c) isFull() -Determine if waterTank is FULL.
d) isEmpty() -Determine if waterTank is EMPTY.
e) fillWater(int quantitiy) -Filling up water to the tank.
f) removeWater(int quantity) -Eradicating water from the tank.
g) currentWater() -Display current water in the tank.
h) setCapacity() -sets new capacity to WaterTank based on parameter value.
i) getCapacity() - return the Capacity of a tank
j) clearWater() - Empty the waterTank. Set Current Water to 0.

UML (Class) Implementation. Out of the UML provide above this is the
Encapsulated class for WaterTank.

WaterTank (Encapsulated class)

SCP-PF103 | 106
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP-PF103 | 107
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Class Tester. (Sample program is attached.)

Write your codes here.

LET’S INFER!
Object Modeling. Decide a real-world object that you find interested to model as a class
(to encapsulate) just like what you did in WaterTank. Then, make a UML diagram and provide
description of each method. Afterwards, create a class implementation of the said object.

Your UML:

Definition:

Implementation:

SCP-PF103 | 108
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Encapsulated Class

Tester Class
Tester Class

SCP-PF103 | 109
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubrics:

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 110
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 9 Principle 2 : Inheritance


Principle 3 : Polymorphism
Lesson Title Inheritance and Polymorphism
Learning Discuss the other two OOP principles which
Outcome(s) are Inheritance and Polymorphism.
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

In programming, it is very important to create relationship between


classes and objects. It is one of the things that makes any programming
language a good and a powerful tool to create great applications. By
allowing each class to make relationship with other classes and its
objects and being able to behave in many forms, things might get easier
for every programmer. The following are important terms you must nee
to know:

Inheritance can be defined as the concept where one class acquires the
properties (methods and fields) of another class. With the use of
inheritance the information is made manageable in a hierarchical order.
Superclass. The class whose properties (data/behavior) are inherited by
other class. Also known as parent/based class.
Subclass. The class which inherits the properties of other class. Also
known as child/derived class.
extends. It is a keyword used to inherit a class’ properties.
super. It is a keyword used to override property of a class.
overloading. A method with same name but different behaviors.
overriding. A method with same name and same behavior.
Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the
existing class.

SCP-PF103 | 111
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

Inheritance is one of the key features of OOP (Object-oriented


Programming) that allows us to define a new class from an existing class.

Class Animal
{
// eat() method
// sleep() method
}
class Dog extends Animal
{
// bark() method
}

In Java, we use the extends keyword to inherit from a class. Here, we


have inherited the Dog class from the Animal class. The Animal is the
superclass (parent class or base class), and the Dog is a subclass (child
class or derived class). The subclass inherits the fields and methods of
the superclass.

is-a relationship
Inheritance is an is-a relationship. We use inheritance only if an is-
a relationship is present between the two classes.

Here are some examples:


• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.

Example 1: Java Inheritance

class Animal {

public void eat() {


System.out.println("I can eat");
}

public void sleep() {


System.out.println("I can sleep");
}
}

class Dog extends Animal {


public void bark() {
System.out.println("I can bark");
SCP-PF103 | 112
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

}
}

class Main {
public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.eat();
dog1.sleep();

dog1.bark();
}
}

Output

I can eat
I can sleep
I can bark

Here, we have inherited a subclass Dog from superclass Animal.


The Dog class inherits the methods eat() and sleep() from
the Animal class. Hence, objects of the Dog class can access the
members of both the Dog class and the Animal class.

protected Keyword
We learned about private and public access modifiers in previous
tutorials.

• private members can be accessed only within the class


• public members can be accessed from anywhere
SCP-PF103 | 113
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

You can also assign methods and fields protected. Protected members
are accessible.

• from within the class


• within its subclasses
• within the same package

Here's a summary from where access modifiers can be accessed.


Class Package subclass World(User)
public Yes Yes Yes Yes
private Yes No No No
protected Yes Yes Yes No

Example 2: protected Keyword

class Animal {
protected String type;
private String color;

public void eat() {


System.out.println("I can eat");
}
public void sleep() {
System.out.println("I can sleep");
}
public String getColor(){
return color;
}
public void setColor(String col){
color = col;
}
}

class Dog extends Animal {


public void displayInfo(String c){
System.out.println("I am a " + type);
System.out.println("My color is " + c);
}
public void bark() {
System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {

Dog dog1 = new Dog();


dog1.eat();
SCP-PF103 | 114
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

dog1.sleep();
dog1.bark();

dog1.type = "mammal";
dog1.setColor("black");
dog1.displayInfo(dog1.getColor());
}
}

Output

I can eat
I can sleep
I can bark
I am a mammal
My color is black

Here, the type field inside the Animal class is protected. We have
accessed this field from the Main class using.

dog1.type = "mammal";

It is possible because both the Animal and Main classes are in the same
package (same file).

Java Method overriding

From the above examples, we know that objects of a subclass can also
access methods of its superclass. What happens if the same method is
defined in both the superclass and subclass?

Well, in that case, the method in the subclass overrides the method in
the superclass. For example,

Example 3: Method overriding Example

class Animal {
protected String type = "animal";

public void eat() {


System.out.println("I can eat");
}

public void sleep() {


SCP-PF103 | 115
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

System.out.println("I can sleep");


}
}

class Dog extends Animal {

@Override
public void eat() {
System.out.println("I eat dog food");
}

public void bark() {


System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {

Dog dog1 = new Dog();


dog1.eat();
dog1.sleep();
dog1.bark();
}
}

Output

I eat dog food


I can sleep
I can bark

Here, eat() is present in both the superclass Animal and subclass Dog.
We created an object dog1 of the subclass Dog.

When we call eat() using the dog1 object, the method inside the Dog is
called, and the same method of the superclass is not called. This is
called method overriding.

In the above program, we have used the @Override annotation to tell


the compiler that we are overriding a method. However, it's not
mandatory.

If we need to call the eat() method of Animal from its subclasses, we use
the superkeyword.

SCP-PF103 | 116
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Example 4: super Keyword

class Animal {
public Animal() {
System.out.println("I am an Animal");
}

public void eat() {


System.out.println("I can eat");
}
}

class Dog extends Animal {


public Dog(){
super();
System.out.println("I am a dog");
}
public void eat() {
super.eat();
System.out.println("I eat dog food");
}

public void bark() {


System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();

dog1.eat();
dog1.bark();
}
}

Output

I am an Animal
I am a dog
I can eat
I eat dog food
I can bark

Here, we have used the super keyword to call the constructor


using super(). Also, we have called the eat() method of Animal superclass
using super.eat().

SCP-PF103 | 117
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Note the difference in the use of super while calling constructor and
method.

Types of inheritance

There are various types of inheritance as demonstrated below:

• Single inheritance - Class B extends from class A only.


• Multilevel inheritance - Class B extends from class A; then
class C extends from class B.
• Hierarchical inheritance - Class A acts as the superclass for
classes B, C, and D.
• Multiple inheritance - Class C extends from interfaces A and B.
• Hybrid inheritance - Mix of two or more types of inheritance.

A very important fact to remember is that Java does not support multiple
inheritance. This means that a class cannot extend more than one class.
Therefore following is illegal −

Example
public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has


helped Java get rid of the impossibility of multiple inheritance. This will
be discussed in the next chapter.

HAS-A Relationship:

SCP-PF103 | 118
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Composition(HAS-A) simply mean the use of instance variables that are


references to other objects. For example Maruti has Engine, or House has
Bathroom.

Let’s understand these concepts with an example of Car class.

class Car {
// Methods implementation and class/Instance members
private String color;
private int maxSpeed;
public void carInfo(){
System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed);
}
public void setColor(String color) {
this.color = color;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
}

As shown above, Car class has a couple of instance variable and few
methods. Maruti is a specific type of Car which extends Car class means
Maruti IS-A Car.

class Maruti extends Car{


//Maruti extends Car and thus inherits all methods from Car (except final and static)
//Maruti can also define all its specific functionality
public void MarutiStartDemo(){
Engine MarutiEngine = new Engine();
MarutiEngine.start();
}
}
Maruti class uses Engine object’s start() method via composition. We can
say that Maruti class HAS-A Engine.

public class Engine {


public void start(){
System.out.println("Engine Started:");
}
public void stop(){
System.out.println("Engine Stopped:");
}
}
SCP-PF103 | 119
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

RelationsDemo class is making object of Maruti class and initialized it.


Though Maruti class does not have setColor(), setMaxSpeed() and
carInfo() methods still we can use it due to IS-A relationship of Maruti
class with Car class.

public class RelationsDemo {


public static void main(String[] args) {
Maruti myMaruti = new Maruti();
myMaruti.setColor("RED");
myMaruti.setMaxSpeed(180);
myMaruti.carInfo();
myMaruti.MarutiStartDemo();
}
}

If we run RelationsDemo class we can see output like below.

Comparing Composition and Inheritance

• It is easier to change the class implementing composition than inheritance. The


change of a superclass impacts the inheritance hierarchy to subclasses.
• You can't add to a subclass a method with the same signature but a different
return type as a method inherited from a superclass. Composition, on the other hand,
allows you to change the interface of a front-end class without affecting back-end
classes.
• Composition is dynamic binding (run-time binding) while Inheritance is static
binding (compile time binding)
• It is easier to add new subclasses (inheritance) than it is to add new front-end
classes (composition) because inheritance comes with polymorphism. If you have a
bit of code that relies only on a superclass interface, that code can work with a new
subclass without change. This is not true of composition unless you use composition
with interfaces. Used together, composition and interfaces make a very powerful
design tool.
• With both composition and inheritance, changing the implementation (not the
interface) of any class is easy. The ripple effect of implementation changes remains
inside the same class.

o Don't use inheritance just to get code reuse If all you really want is to
reuse code and there is no is-a relationship in sight, use composition.
o Don't use inheritance just to get at polymorphism If all you really want
is a polymorphism, but there is no natural is-a relationship, use composition with
interfaces.

Summary
SCP-PF103 | 120
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

• IS-A relationship based on Inheritance, which can be of two types Class


Inheritance or Interface Inheritance.
• Has-a relationship is composition relationship which is a productive way of code
reuse.

Why use inheritance?


• The most important use is the reusability of code. The code that is
present in the parent class doesn’t need to be written again in the child
class.
• To achieve runtime polymorphism through method overriding. We
will learn more about polymorphism in later chapters.

Java Polymorphism

In this tutorial, we will learn about Java polymorphism and its


implementation with the help of examples.

Polymorphism is an important concept of object-oriented programming.


It simply means more than one form.

That is, the same entity (method or operator or object) can perform
different operations in different scenarios.

Example: Java Polymorphism

class Polygon {

// method to render a shape


public void render() {
System.out.println("Rendering Polygon...");
}
}

class Square extends Polygon {

// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}

class Circle extends Polygon {

// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}

SCP-PF103 | 121
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

class Main {
public static void main(String[] args) {
// create an object of Square
Square s1 = new Square();
s1.render();
// create an object of Circle
Circle c1 = new Circle();
c1.render();
}
}

Output

Rendering Square...
Rendering Circle...

In the above example, we have created a superclass: Polygon and two


subclasses: Square and Circle. Notice the use of the render() method.

The main purpose of the render() method is to render the shape.


However, the process of rendering a square is different than the process
of rendering a circle.

Hence, the render() method behaves differently in different classes. Or,


we can say render() is polymorphic.

Why Polymorphism?

Polymorphism allows us to create consistent code. In the previous example, we


can also create different methods: renderSquare() and renderCircle() to
render Square and Circle, respectively.

This will work perfectly. However, for every shape, we need to create
different methods. It will make our code inconsistent. To solve this,
polymorphism in Java allows us to create a single method render() that
will behave differently for different shapes.

Note: The print() method is also an example of polymorphism. It is used to


print values of different types like char, int, string, etc.

We can achieve polymorphism in Java using the following ways:

1. Method Overriding
2. Method Overloading
3. Operator Overloading

SCP-PF103 | 122
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Java Method Overriding

During inheritance in Java, if the same method is present in both the


superclass and the subclass. Then, the method in the subclass overrides
the same method in the superclass. This is called method overriding.

In this case, the same method will perform one operation in the
superclass and another operation in the subclass. For example,

Example 1: Polymorphism using method overriding

class Language {
public void displayInfo() {
System.out.println("Common English Language");
}
}

class Java extends Language {


public void displayInfo() {
System.out.println("Java Programming Language");
}
}
class Main {
public static void main(String[] args) {
// create an object of Java class
Java j1 = new Java();
j1.displayInfo();
// create an object of Language class
Language l1 = new Language();
l1.displayInfo();
}
}

Output:

Java Programming Language


Common English Language

In the above example, we have created a superclass


named Language and a subclass named Java. Here, the
method displayInfo() is present in both Language and Java.

The use of displayInfo() is to print the information. However, it is printing


different information in Language and Java.

Based on the object used to call the method, the corresponding


information is printed.

SCP-PF103 | 123
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Working of Java Polymorphism


Note: The method that is called is determined during the execution of the
program. Hence, method overriding is a run-time polymorphism.

2. Java Method Overloading

In a Java class, we can create methods with the same name if they differ
in parameters. For example,

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.

Example 3: Polymorphism using method overloading

class Pattern {
// method without parameter
public void display() {
for (int i = 0; i < 10; i++) {
System.out.print("*");
}
}
// method with single parameter
public void display(char symbol) {
for (int i = 0; i < 10; i++) {
System.out.print(symbol);
}
}
}

class Main {
public static void main(String[] args) {
Pattern d1 = new Pattern();

SCP-PF103 | 124
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

// call method without any argument


d1.display();
System.out.println("\n");
// call method with a single argument
d1.display('#');
}
}

Output:

**********

##########

In the above example, we have created a class named Pattern. The class
contains a method named display() that is overloaded.

// method with no arguments


display() {…}
// method with a single char type argument
display(char symbol) {…}

Here, the main function of display() is to print the pattern. However,


based on the arguments passed, the method is performing different
operations:
• prints a pattern of *, if no argument is passed or
• prints pattern of the parameter, if a single char type argument is
passed.

Note: The method that is called is determined by the compiler. Hence, it is


also known as compile-time polymorphism.
3. Java Operator Overloading
Some operators in Java behave differently with different operands. For
example,
• + operator is overloaded to perform numeric addition as well as
string concatenation, and
• operators like &, |, and ! are overloaded for logical and bitwise
operations.
Let's see how we can achieve polymorphism using operator overloading.
The + operator is used to add two entities. However, in Java,
the + operator performs two operations.
1. When + is used with numbers (integers and floating-point numbers),
it performs mathematical addition. For example,

SCP-PF103 | 125
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

int a = 5;
int b = 6;
// + with numbers
int sum = a + b; // Output = 11

2. When we use the + operator with strings, it will perform string


concatenation (join two strings). For example,

String first = "Java ";


String second = "Programming";
// + with strings
name = first + second; // Output = Java Programming

Here, we can see that the + operator is overloaded in Java to perform


two operations: addition and concatenation.

Note: In languages like C++, we can define operators to work differently


for different operands. However, Java doesn't support user-defined
operator overloading.
Polymorphic Variables
A variable is called polymorphic if it refers to different values under
different conditions. Object variables (instance variables) represent the
behavior of polymorphic variables in Java. It is because object variables
of a class can refer to objects of its class as well as objects of its
subclasses.
Example: Polymorphic Variables

class ProgrammingLanguage {
public void display() {
System.out.println("This is Programming Language.");
}
}
class Java extends ProgrammingLanguage {
public void display() {
System.out.println("This is Java.");
}
}
class Main {
public static void main(String[] args) {
// declare an object variable
ProgrammingLanguage pl;
// create object of Animal class
pl = new ProgrammingLanguage();
pl.display();
// create object of Java class
pl = new Java();
SCP-PF103 | 126
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

pl.display();
}
}

Output:

This is Programming Language.


This is Java.

In the above example, we have created an object variable pl of


the ProgrammingLanguage class. Here, pl is a polymorphic variable. This
is because,
• In statement pl = new ProgrammingLanguage(), pl refer to the object
of the ProgrammingLanguage class.
• And, in statement pl = new Java(), pl refer to the object of
the Java class.
This is an example of upcasting in Java.
Object Upcasting and Downcasting
In Java, an object of a subclass can be treated as an object of the
superclass. This is called upcasting. Java compiler automatically
performs upcasting.

Example 4: Object Upcasting

class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal { }
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
Animal a1 = d1;
a1.displayInfo();
}
}

Output:

I am an animal.

In the above example, we have created an object d1 of the Dog class. We


use that d1 object to create an object a1 of the Animal class. This is
called upcasting in Java.

SCP-PF103 | 127
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

The code executes without any problem. This is because upcasting is


automatically done by Java compilers.

Downcasting is a reverse procedure of upcasting.

In the case of downcasting, an object of the superclass is treated as an


object of the subclass. We have to explicitly instruct the compiler to
downcast in Java.

Example 5: Object Downcasting Problem

class Animal {
}

class Dog extends Animal {


public void displayInfo() {
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Animal a1 = new Animal();
Dog d1 = (Dog)a1; // Downcasting

d1.displayInfo();
}
}

When we run the program, we will get an exception


named ClassCastException. Let's see what happens here.

Here, we have created an object a1 of the superclass Animal. We then


tried to cast the a1 object to the object d1 of the subclass Dog.

This caused the problem. It is because the a1 object of the


superclass Animal may also refer to other subclasses. Had we created
another subclass Cat along with Dog; the Animal maybe Cat or it
maybe Dog causing ambiguity.

To resolve this problem we can use the instanceof operator. Here's how

Example 6: Resolving Downcasting Using instanceof

class Animal { }
class Dog extends Animal {
public void displayInfo() {
System.out.println("I am a dog");

SCP-PF103 | 128
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
Animal a1 = d1; // Upcasting
if (a1 instanceof Dog){
Dog d2 = (Dog)a1; // Downcasting
d2.displayInfo();
}
}
}

Output:

I am a dog

In the above example, we use the instanceof operator to check whether


the a1 object is an instance of Dog class or not. The downcasting is done
only when the expression a1 instanceof Dog is true.

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the
lessons.

Search Indicator

https://www.geeksforgeeks.org/
https://www.tutorialspoint.com/java/
https://beginnersbook.com/2013/03/
https://www.programiz.com/java-programming/

SCP-PF103 | 129
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INITIATE!

Activity 1. Answer the following questions.

1. In your own opinion, why would we need to apply/implement the concepts


of Inheritance and Polymorphism when we write programs?
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.

2. Explain what is the difference between is-A and has-A relationship? Give
example such as Student is-A person and car has-a (an) engine.
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.

3. How important is method overloading and overriding in OOP concepts?


_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.

LET’S INQUIRE!

Program Tracing. Write the output of the program below:

SCP-PF103 | 130
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP-PF103 | 131
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INFER!

Program Design. Create a class Person and copy the codes below:

public class Person {


private String name, gender;
private int age;
private static String address;
Person(){
name=gender="";
age=0;
}
Person(String name){
this.name=name;
}
Person(String name, String gender){
this.name=name;
this.gender=gender;
}
Person(String name, String gender, int age){
this.name=name;
this.gender=gender;
this.age=age;
}
//setters
public void setName(String name) { this.name = name; }
public void setGender(String gender) { this.gender = gender; }
public void setAge(int age) { this.age = age; }
public void setPersonInfo(String name, String gender, int age){
this.name=name;
this.gender=gender;
this.age=age;
}
public void setPersonInfo(String name, String gender){
this.name=name;
this.gender=gender;
}
public void setPersonInfo(String name){
this.name=name;
}

public static void setAddress(String address) {


Person.address = address;
}
public static String getAddress() {
return address;
}
//getters

SCP-PF103 | 132
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

public String getName() { return name; }


public String getGender() { return gender; }
public int getAge() { return age; }

public String getPersonInfo(){


return name+"\t"+gender+"\t"+age;
}
public String getPersonInfo2(){
return "Name\t: "+name+"\nGender\t:"+gender+"\nAge\t:"+age+"\n";
}
}

Based on the Person class below, design and create a class that shows
the following relationship or inheritance types:

1. Single Inheritance (such that Student is-A Person), thus you will
create a class that would make Student class extends a Person class.

Example:

Now, create your own:

2. Multilevel Inheritance.

3. Hierarchical Inheritance.
SCP-PF103 | 133
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubric

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 134
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 10 Intro to GUI


Lesson Title JFrame and other Basic Swing Components
Learning Discuss the basic swing components in creating
Outcome(s) GUI.
Time Frame

At SJPIICD, I Matter!

LEARNING INTENT!
Terms to Ponder

GUI (Graphical User Interface) In Java gives programmers an easy-to-use visual


experience to build Java applications. It is mainly made of graphical components like
buttons, labels, windows, etc. through which the user can interact with the applications.
Swing GUI in Java plays an important role in building easy interfaces.

JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border,
menu, buttons, text fields and several other components. A Swing application must have
a frame to have the components added to it.

JPanel – A panel is an instance of JPanel. A frame can have more than one panels and
each panel can have several components. You can also call them parts of Frame. Panels
are useful for grouping components and placing them to appropriate locations in a frame.

JLabel – A label is an instance of JLabel class. A label is unselectable text and images. If
you want to display a string or an image on a frame, you can do so by using labels. In the
above example we wanted to display texts “User” & “Password” just before the text fields
, we did this by creating and adding labels to the appropriate positions.

JTextField – Used for capturing user inputs, these are the text boxes where user enters
the data.

JButton – A button is an instance of JButton class. In the above example we have a button
“Login”.

SCP-PF103 | 135
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

Now that we have already covered the basics of Java programming and
perhaps you are quite good about OOP concepts, and how I’d wish you
will become better and better every single day. You know what, just keep
on believing yourself. Remember, “Programming is hard. It is harder
when you think it is.” Find best way of learning these concepts and I
tell you there is no single programming problem you can’t solve.

Drama is over. Please keep in mind that I can’t promise to teach you
everything I know because it is with you, it must be you to decide it. There
are lots of resources like books, training, and video tutorials you can find
through internet. So, you go get and read them. Today, I’m just going to
give you a practical way of learning through basics in GUI components
enough for you to get on your own feet. Hence, you can explore on your
own to expand your knowledge. Further, Java API is the most promising
reference you will have to deal with towards learning every component
and how to use it.

So let us start by defining basic terms first.

Swing. Swing is the principal GUI toolkit for the Java programming
language. It is a part of the JFC (Java Foundation Classes), which is an
API for providing a graphical user interface for Java programs.

It is a lightweight GUI toolkit which has a wide variety of widgets for


building optimized window based applications.
Container Class
Any class which has other components in it is called as a container class.
For building GUI applications at least one container class is necessary.
Following are the three types of container classes:
1. Panel – It is used to organize components on to a window
2. Frame – A fully functioning window with icons and titles
3. Dialog – It is like a pop up window but not fully functional like the
frame

Difference Between AWT and Swing


AWT SWING
• Platform Dependent • Platform Independent
• Does not follow MVC • Follows MVC
• Lesser Components • More powerful components
• Does not support • Supports pluggable look and
pluggable look and feel feel
• Heavyweight • Lightweight

SCP-PF103 | 136
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Swing : Class Hierarchy

Explanation: All the components in swing like JButton, JComboBox,


JList, JLabel are inherited from the JComponent class which can be
added to the container classes. Containers are the windows like frame and
dialog boxes. Basic swing components are the building blocks of any GUI
application. Methods like setLayout override the default layout in each
container. Containers like JFrame and JDialog can only add a component
to itself. Following are a few components with examples to understand how
we can use them.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are
given below.

Method Description

public void add(Component c) add a component on


another component.

public void setSize(int width,int height) sets size of the


component.

public void setLayout(LayoutManager m) sets the layout


manager for the
component.

public void setVisible(boolean b) sets the visibility of the


component. It is by
default false.

SCP-PF103 | 137
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Some basic Swing components

JTextField Class. It inherits the JTextComponent class and it is used to


allow editing of single line text.
JButton Class. It is used to create a labelled button. Using the
ActionListener it will result in some action when the button is pushed. It
inherits the AbstractButton class and is platform independent.
JLabel Class. It is used for placing text in a container. It also inherits
JComponent class.

There are two ways to create a frame:


o By creating the object of Frame class (association)
o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other
method. For this tutorial, let’s create first a Window through a JFrame.
Our goal is to display an output like below.

Opps! Wait. Kindly prepare ¼ sheet of paper this time and then follow
the steps below:
STEP 1: Create a class MyFirstJFrame

Is this look familiar to you? javax.swing.JFrame;. Write this at import


statement.

SCP-PF103 | 138
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

- Line 1 means that we are trying to access the package javax.swing


and use the JFrame class. A great way of writing it is javax.swing.*; if
you plan to use all its swing components without defining them one by
one.

STEP 2 : Extending the JFrame class.

To make a frame, our class has to extend JFrame, which also allows us
to manipulate the frame. (You can actually instantiate a JFrame, say
JFrame myFrame=new JFrame(); if you wish too).

When we create a frame, we


have to specify a few things:

ü Title
ü Dimensions
ü Visibility
ü Default close operation,

Look at the code below. Type these codes and run.

This is the
display output.

- Line 3 means Inheritance OOP concept it is applied.


- Line 4 infers that the class creates constructor.
- Line 5 through Line 8 are JFrame’s methods. This signifies that when you
extends JFrame, any class can own all the public properties of it. Thus, creates
parent and child relationships.
SCP-PF103 | 139
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

- Line 5 is a method that displays the title of the JFrame. Look at above display
output. Try to change its argument of anything you like. Then run. You will notice it
should change its title.
- Line 6 means that it is a method where you set your JFrame size’s width x
height. Changing its value would resize your JFrame.
- Line 7 indicates that you want your JFrame to be seen on the screen. Just like
above display. Setting it to false would not show the JFrame or the window. See it for
yourself, try this setVisible(false).

NOTE : This is the most common to Programmers tend to forget. So, I bet you’re
not one of them. J

- Line 8 basically, it just defines how the window reacts when the user presses the
big 'x' button. It is a bit outside the scope of this tutorial, so we'll just keep it simple
and leave it set to EXIT_ON_CLOSE. Actually, you will wonder since the parameter of
it says that it is an int value. See below:

NOTE : Use only 1, 2, 3 as parameter value. 0 means it does nothing, hence it


will not close the JFrame. Above 3 such as 4 will produce an exception error.
You may try it. You will write ‘thing’ word at the center in your ¼ sheet of
paper when you read this.

The value passed in as parameter will determine what happens when


the window is closed. There are several other options in addition to
JFrame.EXIT_ON_CLOSE. These are the following:

JFrame.DISPOSE_ON_CLOSE, JFrame.HIDE_ON_CLOSE,
JFrame.DO_NOTHING_ON_CLOSE

Their names reflect on their actions. These constants are declared in


WindowConstants, which is an interface declared in javax.swing that is
implemented by JFrame. (You will know it some other time during our
advanced discussions).

- Line 11 is calling its MyFirstFrame constructor. This is very obvious that all the
codes you wrote in the constructor will be executed automatically without creating
an instance of a class or object. Place it in the main method since main method is
called first among all others. Try to remove it and run the program, you will see no
JFrame or window on your screen.

NOTE: Almost all of the codes for this project will be placed in the class'
constructor. Very little code will actually go into the main method.

How was it? Was it easy? For me I guess it was. Indeed, that was the very
basic way of creating Windows through a JFrame class. Was it
challenging? Well, it’s okay right now if you feel it that way. A lot of things
SCP-PF103 | 140
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

you will learn and would excite you the most along the way in creating
Visual Interface in Java. Especially if you want your program to be great
and interactive. All right! Rock N’ Roll to the world by writing ‘our’ before
the first word you wrote in your ¼.

Now that you know how to create Window in Java using JFrame class.
Then I guess you are ready for our next tutorial. So let's get started. But,
first let’s define and familiarize the following terms:

ü The Frame. The frame is the border of the window that will "hold" all
your components - your text fields, labels, radio buttons, etc.. Every
window must have a frame to place components, just as every book must
have a cover to hold pages.

ü Content Pane. The content pane is where all components will be


placed. You could think of it as the background. Every GUI must have a
content pane, just as books must have pages.

ü Layout Manager. The layout manager places the components in the


pane in a certain configuration, depending on which layout manager you
specify. If you set it to "null" as I often do, you must specify the exact
coordinates (in pixels) for each component. Layout managers can be nice,
but they can also cause lots of headaches.

ü Coordinates. Coordinates are specified rather intuitively in Java. If


you remember your high school algebra - or at least how to plot points
on an x-y graph - you'll be fine. Java's coordinate system uses standard
(x, y) coordinates, but they're plotted like this: A point (x, y) is located x
pixels to the right and y pixels down from the top-left corner of the pane.

So, Programmers are you ready? Then, let’s go get through this.
• How to make a frame?
• Get a hold of the content panel
• Make our components
• Add our components to the GUI
• Set up event handlers

Three basic things you have to know first in creating GUI:

1. Making-up a JFrame or Window. The Window is where you draw


your UI.
2. Design User Interface (UI). Draw the UI by visualizing or providing
prototype so you will know what components you will use.
a. Adding controls or components. Normally it is done by drag and
drop mechanism. But, for this tutorial I’ll teach you how to add and draw
UI by writing codes to appreciate OOP concepts thoroughly.

SCP-PF103 | 141
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

b. Name your controls. Proper naming is a must. Follow the standard


naming conventions. See below:
3. Setting up an event to controls. Attach code to specific controls
make your program interactive and responsive.

And, yes finally we are here. let's make a really simple application that
adds two numbers.

1 First number : 5 4

Second number : 8
5
2

OK EXIT
The sum is : 13
Figure 1 : Prototype
6 1 7
3

So, what are we up to this time? As you notice above there are new swing
components we used. Let me give you an idea what are these. Recall that
our JFrame is where we draw our user interface. Hence, all other swing
components must be placed over the JFrame component. Let’s put it this
way, you have a new bought house. And it’s dull and boring. If you want
your house to look great you will put some designs in it like curtains,
sofa, dining table, and the likes. Basically, your JFrame is your house
and all other swing components are your things or objects you put to
make your house look beautifully. Just like a normal house JFrame can
be so boring without its components. Below are the components of swing
we used in the above prototype:

JLabel - is used to display information or an idea of what we want to


imply. Simply, a caption. 1, 2, and 3 are JLabels.
JTextField – is used to accept data or information from the user. It takes
data as an input. 4 and 5 are JTextFields
JButton – is used to invoke a command or an instruction. Normally, by
clicking or double-clicking. 6 and 7 are all JButtons.

I think that’s it. Familiarize when to use them and we don’t have problem
all throughout this tutorial. Okay, let’s get this started by going to
activities in the next page.

SCP-PF103 | 142
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SELF-SUPPORT: You can click the URL Search Indicator below to help you further understand the
lessons.

Search Indicator

https://www.programiz.com/java-programming/
https://www.guru99.com/java-swing-gui.html
https://www.javatpoint.com/java-swing

LET’S INITIATE!

Activity 1. As you were writing your first GUI earlier using JFrame swing
component, I want you to reverse-engineer the JFrame as a class. Your task
is to create a version of JFrame’s UML based on the methods shown from
Line 5 to 8.

Task 1: UML Task 2. OOP Review. Supply


an answer based on the
following:

How do you understand each


concept after the above
discussion? Be short, direct and
concise.
1. Class

2. Child

3. Parent

4. extends

5. Constructor

2. Setter

3. Getter

SCP-PF103 | 143
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Activity 2. Now, go back to Figure 1 : Prototype 1, I want you to write


what component beside each item number. This is to invoke familiarization.

Recall that there are 3 ways on how to create GUI in java. Below are as
follows:

1. Making-up a JFrame or Window


2. Design User Interface (UI).
3. Setting up an event to controls.

STEP 1: MAKING-UP A FRAME OR WINDOW

- Create a class GUISum. Debug the following by writing the right program in the
next column.
Import java.Swing.uti.JFrame;

public Class JFrames extends GUISum {


public JFrame() {

}
public static void main(String[]
arguments) {

}
}

- Write your complete codes in the next column based on the display output below:

STEP 2 : DESIGNING UI

1 First number : 5 4

Second number : 8 5
2

OK EXIT
The sum is : 13
6 7
3

Figure 2: Prototype 2

SCP-PF103 | 144
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

In this tutorial you will be introduced to three components: JLabel, JTextField,


JButton. Keep in mind that there are tons of other types of components, but these
are three of the most basic, and are therefore good for learning.

JLabel
Prefix lbl
Example: lblNum1, lblSalary,
lblDisplay, etc.
Import statement import javax.swing.JLabel;
Declaration JLabel lblNum1;
Instantiation lblNum1=new JLabel(); or JLabel
lblNum1=new JLabel();
Constructors

Example:

Methods

TASKS
1. C
reate UML for JLabel based on the above
examples.

2. I
n the above figure (Figure 2), how many
JLabel you should declare?

3. W
rite your declaration and instantiation
of JLabel in the next column.

JTextField
Prefix txt
Example: txtNum1, txtSalary,
txtDisplay, etc.
Import statement import javax.swing.JTextField;
Declaration JTextField txtNum1;

SCP-PF103 | 145
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Instantiation txtNum1=new JTextField(); or


JTextField txtNum1=new
JTextField();
Constructors

Example:

Methods

TASKS
1. 1. Object : W
rite the word or concept that best
described for each item on the next
column. 2. Constructor :

3. Setter :

4. Getter :
2. I
n the above figure (Figure 2), how many
JTextField you will declare?
3. W
rite your declaration and instantiation of
JTextField in the next column.

JButton
Prefix btn or cmd
Example: btnOk, btnCancel,
cmdExit, etc.
Import statement import javax.swing.JButton;
Declaration JButton btnOk;
Instantiation btnOk=new JButton(); or JButton
btnOk=new JButton();
Constructors

Example:

SCP-PF103 | 146
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Methods

TASKS
1. 1. Object : W
rite the word or concept that best described 2. Constructor :
for each item on the next column.
3. Setter :
4. Getter :
2. I
n the above figure (Figure 2), how many
JButton you will declare?
3. W
rite your declaration and instantiation of
JButton in the next column.
4. D
o the following as prescribed:
§ Instantiate a JButton which is named
‘btnClick’ and its caption is “Click”.
§ Try this method in your button
setToolTipText(String). This should be the value
“Click this to win!”. You can run your program to
see the change of your GUI. Write in the next
column your code.
Here’s the complete code of the above scenarios:

NOTE TO PROGRAMMERS: We declare the components outside the class' constructor,


but we instantiate them inside the constructor - like other instance variables. J

- Line 1 through 5.
Observe that they all have common package, the javax.swing. As you see, they were
declared individually. If you don’t like that way, you may do this way javax.swing.*;
for multiple declaration just like the normal importing of package.
- Line 5 was
imported because its class was used in Line 26, SwingConstants.CENTER. You may
SCP-PF103 | 147
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

use it to other swing components also like in JButton, JTextField and others. A
bunch of settings you can use such as WEST, NORTH_EAST, and etc.
- For Line 6, see
Line 16. As you noticed its package is java.awt. awt (Abstract Window Toolkit) is the
previous GUI components of java which are now obsolete because of the advent of
javax.swing components. But, still available for every Programmer to use. This time,
I want you to write ‘PISOT’ in your ¼ 3 rows/block before the last two words you’ve
written.

Activity 3. Now, based on the above prototype let us start designing our UI
following the specifications given. So, come on let’s dig in.
Name : txtNum1
Name : lblNum1 Text :0
Text : First number:
1 5 4
First number :
Name : lblNum2 Second number : 8 5
Name : txtNum2
2 Text :0
Text : Second number:
The sum is : 13ADD EXIT
6
Name : lblResult 7
Text : The sum is : 3 Name : btnExit
Name : btnAdd Text : EXIT
Text : ADD

Figure 3 : Defining prototype

Here’s the code:


Supply (Explanation) answer for
the following Lines:
Line 1.
Line 3.
Line 4.
Line 5.
Line 8.
Line 9.
Line 10.
Line 11.
Line 13.
Line 14.
Line 16.
Line 17.
Line 19.
Line 20.
Line 21.
Line 22.
Line 25.

- Type and run the


program above. You will notice that no swing components are being shown in the
JFrame. In fact, only the JFrame is shown.
- Insert this code in
Line 18. Run your program.

Container pane=getContentPane(); //Package : import java.awt.Container;


pane.add(lblNum1);
ü We use a Container
object to manipulate the content pane (CP) along with a nifty statement:
getContentPane(). The class Container only has two methods that we need to mess
with: add and setLayout. Let's save both of them for later.

SCP-PF103 | 148
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

ü pane.add(lblNum1
); means that you draw (put) lblNum1 in the JFrame.

- Eye on Line 9, I
want you to change it to this lblNum1=new JLabel("First number: ",
SwingConstants.CENTER); .Run your program and observe what happen. You may
of course try a couple of values for SwingConstants values.
- Now, you write this
statement pane.add(lblNum2); after pane.add(lblNum1);.
- If you noticed there
was only one component shown. The recent line the compiler reads is the component
that should display. In this case, you noticed that “Second number:” was displayed
as an output.
- If you ever wonder,
you should try this to your JLabels:

lblNum1=new JLabel("First number: ", SwingConstants.CENTER);


lblNum2=new JLabel("Second number: ", SwingConstants.RIGHT);

The display output was just the same, but “Second number:” moved to the right
portion of the JFrame. Actually, here’s how it goes. No matter how many times you
will add components to your JFrame, all it does is it always displays the recent
component added to the pane and overlap the others. Hence, “First number: ” is
actually at the back of “Second number: ” . You can actually try the pane to add
other components, the last or recent added component will always display over the
other.

So, how do we resolve it? Is it possible?

Well you can try setBounds(int arg0, int arg1, int arg2, int arg3).

lblNum1.setBounds(1, 5, 100, 20);

But, you have to know better of the coordinates and width and height. We will try to
make up this. As of this time, I’ll teach you a little bit easier. Hence, we will use set
the layout (manager) to a simple grid layout with 4 rows and 2 columns.

Container pane = getContentPane();


pane.setLayout(new GridLayout (4, 2));

NOTE: We will discuss further about Layout Managers in the next chapters. For
now, let us have the basic.

GridLayout – Contains two parameters; rows and columns. If you have


GridLayout(4,2). 4 is the row, 2 is column. Hence, it will actually create the table
shown below:

0,0 0,1
1,0 1,1
2,0 2,1
3,0 3,1

Package: import
java.awt.GridLayout;

SCP-PF103 | 149
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Two methods of GridLayout Manager:


1. public void
add(Object obj) - Method to add an object to the pane
2. public void
setLayout(Object obj) - Method to set the layout of the pane

Figure 3. The GridLayout Manager

Check the codes below:

- Line 9 and 10 uses


SwingConstants.RIGHT as the second argument. This will move the JLabel text to the
RIGHT before the object. Look at the figure above.
- Line 11 set the
location at the center of the JFrame because of SwingConstants.CENTER.
- Line 13 and 14
means that JTextField(“0”,10) constructor takes two arguments; the first is the initial
value, the second is to set the column size of the JTexfield. However, you will not notice it
since we are using GridLayout Layout Manager which defeat its purpose because
GridLayout will divide all the parts equally.
- Line 19 is calling
Container class at package java.awt; (look at Line 1). It is said to be the inner area of GUI
window (below title bar, inside border). To access content pane, you may call directly the
method getContentPane of class JFrame. Or create an object of Container, then use the
add() method of JFrame to hold the pane object. Observe the codes below:

- For Line 20 to 27
look at the Figure 3. The GridLayout Manager.
ü Line 21 means that
it should be placed at the first row and first column of the pane, say pane(0,0).

SCP-PF103 | 150
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

ü Line 22 will follow


and be placed at first row and second column, say pane (0,1).
ü Line 23 and 24 is at
pane(1,0) and pane (1,1) respectively.
ü Hence, Line 25 and
26 should follow the same. As well as Line 27, however there is no object at pane(3,1) since
there are only 7 objects or components we have used. Hence, the last portion is left blank.
ü You can actually add
new object to it by instantiating it above and add it to pane after pane.add(lblResult). The
object will then be shown next to “The sum is: ”. Let us try if you get it. At this point, I want
you to add into your existing codes based on the picture shown below:
Write the additional codes right here where component is JTextField
and name is “txtResult”.

NOTE: Make sure to follow naming rules and conventions. J

ü You should try


reshuffling them to see for yourself a various result.
NOTE: Line 21 through Line 27 infers that all the objects we have used are all
added to the pane container using pane.add(). Then, it will be held by the
JFrame using getContentPane() method.

Ok. All our components are ready; steps 1 & 2 are done. What's left? Well, right now
those buttons won't do a thing - we haven't told them what to do when they're pressed.
Before it, I want you to write the word that best describes as to what you are doing at
this moment. It starts with letter P and ends with letter ‘g’. And it has 11 letters all in
all. You should write the after beside the word PISOT or in the next row after it.

LET’S INQUIRE!

STEP 3: SETTING-UP AN EVENT

When something happens in a GUI window, it's called an event. If we want to be able
to react to events (like button clicks), we have to register an action listener that waits
& listens for something to happen. When it "hears" something, it executes the code
we put in the abstract method actionPerformed, which is where we'll be putting our
area formula and output statements. For us, each button will have a different
"handler" that handles each button's function using (implementing) the
ActionListener. Notice that the handler we specified is the argument used when
adding the ActionListener.

- Type import
java.awt.event.*; at the import statement.
- Now, I want you
insert the codes highlighted. See below:

SCP-PF103 | 151
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

T
H
I
S

- As you see in the


figure above, we used the “btnOK” object of JButton. At this point, it tells the
compiler that this object implements ActionListener using the method
addActionListener() of JButton (Line 35).
- Next is declare
these double variables: num1, num2, and sum. Make sure to write at Line 37.

Special NOTE to Programmers: Always remember that all java swing components
treat all input values as String object or an Object itself.

- Now, recall that


previously most of our created classes have setters and getters. You should have
observed that most of the swing components in java have setters and getters too like
setText() and/or getText(). Remember this keyword, “roar raor”.

Try these:

txtResult.setText(“Orayt! Raken Roll”);


txtResult.getText();

- Here’s how it is, the


moment you run your program you are actually asked to input values (usually at
JTextField right) for txtNum1 and txtNum2. Thus, when you input numbers to
respective JTextFields it takes a String input –setText() is assumedly called.
- Now, let us proceed
to the main dish of the program. Recall that you have declared three double
variables. What are they up to? Truly, I want you to fill-in the blanks:

Write your answer based on where did the value be


taken from? Like, you should write the
object/component and its preferred method.

num1=______________________________.
num2=______________________________.

However, the problem there is that even if you found out the answer it might
produce an error. How do we resolve it?

What is the datatype of num1, num2, and sum? __________________________.


What did I tell you in the special NOTE (Read again “Special NOTE to
Programmers” above.). What mostly a swing components usually take or treat as a
value? ________________________________. Very good, now are num1, num2, and sum
are compatible with your swing components used in the program in taking input as
a value? YES or NO? (underline). So, I know what you have in mind now, write it
down here:

SCP-PF103 | 152
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

num1=___________________________________________________________________.
num2=___________________________________________________________________.

- Now, add the two


numbers and assign it to sum. What is the code?
__________________________________________.
- Afterwards, where
do you want the result to display?
___________________________________________________.
- What method will
you use in your text field to display the result of the added two numbers?
___________________________________.
- Add this
txtResult.setEditable(false); to your program above btnOk=new JButton("OK");.
Run your program, observe what happens.
- Note that you can
also use JOptionPane to display output. You should try.
- Finally, I want you
to write your code here for ‘CANCEL’ button. Just type “System.exit(0)” inside the
block.

Wow you are so impressive. You just made your Cancel button works for you. Up to
this point, I still have one more question. What is this bisaya word of a number which
is also an animal notable for its horn. An English term of this animal may sound like
an endearment of a couple. Or it can be a famous country. So, what is this? ______.
Now, your answer is probably written on the black provided. But, I want you to think
of something like ‘since there is no such thing as ‘US’ because you are dedicated to
learning programming, you don’t have time to find couple or use this endearment or
belong in an ‘US’. So, you use the other form of the word in singular like referring to
yourself only. Actually, you just simply change the first letter of the word as to what
best describe a person who is alone. Another hint is this is one of the vowels in the
English alphabet. Got it? So you should then remove the last letter of the word
because there is no Actually an us. So, what is now the word? Write it in your ¼ after
the recent word you wrote.

Admittedly, this isn't exactly the most exciting or flashy GUI you'll ever see. However,
it accomplishes a task: to introduce broad concepts. Hopefully, from here, you will go
on to expand your knowledge, building on the foundation we've established here. (At
this juncture, whatever you have written in your ¼ sheet of paper should be used as
the subject upon submission of this document). As far as resources go, there is no
shortage of them - go look for some basic Java GUI books at the library, or free e-
books online, and - as always - be sure to check for other tutorials, code snippets,
and more resources than you'll know what to do with.

SCP-PF103 | 153
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INFER!

FINAL TASK Tasks Code Listing


Import
Complete the statements
arithmetic operation. Creation of a
Use the design below class with
as your guide. inheritance
Instantiation
of every
object inside
of a
constructor
Instantiation
of your
Container
with Layout
Manager
Adding each
component
to Container
pane

Setting up
your Window

Your main
Class

SCP-PF103 | 154
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubric

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 155
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 11 Java Layout Managers


Lesson Title Layout Managers
Learning Discuss the different ways and techniques of
Outcome(s) designing UI through layout managers.
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

A layout manager is an object that implements the LayoutManager


interface* and determines the size and position of the components within
a container. Although components can provide size and alignment hints,
a container's layout manager has the final say on the size and position of
the components within the container.

The borderlayout arranges the components to fit in the five regions: east,
west, north, south and center.

The CardLayout object treats each component in the container as a card.


Only one card is visible at a time.

The FlowLayout is the default layout. It layouts the components in a


directional flow.

The GridLayout manages the components in form of a rectangular grid.

GridBagLayout. This is the most flexible layout manager class. The


object of GridBagLayout aligns the component vertically,horizontally or
along their baseline without requiring the components of same size.

SCP-PF103 | 156
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

Now that you know the basics of creating GUI in java using swing
components, I guess that is enough for you to move on your own. Keep
forward and continue learning of this concept further. Hence, it feels
great knowing that. However, it’s not enough to simply just draw your UI
using JFrame and a Container. You don’t settle on that. You should NOT!
Well, in our previous tutorial we use null or no layout manager to arrange
and organize our swing components in a way we want to simply make
our GUI looks amazing. No layout manager means we arrange our UI
components using coordinates (x,y), width, and height. Yet, at some point
you maybe need more because you want another layout to satisfy your
designing taste. Good thing because it is NOT the only thing in this world
we can use to organize our components in a container or in a JFrame.
Take a look at the following tutorial.

The Swing layout management

The Java Swing toolkit has two kind of components: containers and
children. The containers group children into suitable layouts. To create
layouts, we use layout managers. Layout managers are one of the most
difficult parts of modern GUI programming. Many beginning
programmers have too much respect for layout managers. Mainly
because they are usually poorly documented.

Types of Layout Managers:


1. FlowLayout
2. GridLayout
3. BorderLayout
4. CardLayout
5. GridBagLayout
6. BoxLayout
7. GroupLayout
8. ScrollPaneLayout
9. SpringLayout, etc
FlowLayout

The FlowLayout is used to arrange the components in a line, one after


another (in a flow). It is the default layout of applet or panel.

Data Fields

ü public static final int LEFT


ü public static final int RIGHT
ü public static final int CENTER
ü public static final int LEADING
ü public static final int TRAILING

SCP-PF103 | 157
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Constructors

FlowLayout(): creates a flow layout with centered alignment and a


default 5 unit horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.

Sample:

Output:

SCP-PF103 | 158
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

GridLayout

The GridLayout is used to arrange the components in rectangular grid.


One component is displayed in each rectangle.

Constructors

GridLayout(): creates a grid layout with one column per component in a


row.
GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.

Sample:

Output:

SCP-PF103 | 159
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

BorderLayout

The BorderLayout is used to arrange the components in five regions:


north, south, east, west and center. Each region (area) may contain one
component only. It is the default layout of frame or window. The
BorderLayout provides five constants for each region:

ü public static final int NORTH


ü public static final int SOUTH
ü public static final int EAST
ü public static final int WEST
ü public static final int CENTER

Constructors

BorderLayout(): creates a border layout but with no gaps between the


components.
JBorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.

Sample

Output:

SCP-PF103 | 160
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

BoxLayout

The BoxLayout is used to arrange the components either vertically or


horizontally. For this purpose, BoxLayout provides four constants. They
are as follows:

Note: BoxLayout class is found in javax.swing package.

Data Fields

ü public static final int X_AXIS


ü public static final int Y_AXIS
ü public static final int LINE_AXIS
ü public static final int PAGE_AXIS
Constructor

BoxLayout(Container c, int axis): creates a box layout that arranges


the components with the given axis.

Sample:

Output:

SCP-PF103 | 161
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Sample:

Output:

CardLayout

SCP-PF103 | 162
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

The CardLayout class manages the components in such a manner that


only one component is visible at a time. It treats each component as a
card that is why it is known as CardLayout.

Constructors

CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.

Commonly used methods:

public void next(Container parent): is used to flip to the next card of


the given container.
public void previous(Container parent): is used to flip to the previous
card of the given container.
public void first(Container parent): is used to flip to the first card of the
given container.
public void last(Container parent): is used to flip to the last card of the
given container.
public void show(Container parent, String name): is used to flip to the
specified card with the given name.
Sample:

Output: (click the button)

SCP-PF103 | 163
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

GridBagLayout

The Java GridBagLayout class is used to align components vertically,


horizontally or along their baseline.

The components may not be of same size. Each GridBagLayout object


maintains a dynamic, rectangular grid of cells. Each component occupies
one or more cells known as its display area. Each component associates
an instance of GridBagConstraints. With the help of constraints object
we arrange component's display area on the grid. The GridBagLayout
manages each component's minimum and preferred sizes in order to
determine component's size.

Data Fields

Modifier and Type Field Description


double[] columnWeights It is used to hold the
overrides to the column
weights.
int[] columnWidths It is used to hold the
overrides to the column
minimum width.
protected Hashtable comptable It is used to maintains
<Component,GridBagConstraints> the association between
a component and its
gridbag constraints.
protected GridBagConstraints defaultConstraints It is used to hold a
gridbag constraints
instance containing the
default values.
protected GridBagLayoutInfo layoutInfo It is used to hold the
layout information for
the gridbag.
protected static int MAXGRIDSIZE No longer in use just for
backward compatibility
protected static int MINSIZE It is smallest grid that
can be laid out by the
grid bag layout.
protected static int PREFERREDSIZE It is preferred grid size
that can be laid out by
the grid bag layout.
int[] rowHeights It is used to hold the
overrides to the row
minimum heights.
double[] rowWeights It is used to hold the
overrides to the row
weights.

SCP-PF103 | 164
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Useful Methods
Modifier and Type Method Description
void addLayoutComponent It adds specified component to the
(Component comp, layout, using the specified
Object constraints) constraints object.
void addLayoutComponent It has no effect, since this layout
(String name, manager does not use a per-
Component comp) component string.
protected void adjustForGravity It adjusts the x, y, width, and
(GridBagConstraints height fields to the correct values
constraints, Rectangle depending on the constraint
r) geometry and pads.
protected void AdjustForGravity This method is for backwards
(GridBagConstraints compatibility only
constraints, Rectangle
r)
protected void arrangeGrid(Container Lays out the grid.
parent)
protected void ArrangeGrid(Container This method is obsolete and
parent) supplied for backwards
compatibility
GridBagConstraints getConstraints It is for getting the constraints for
(Component comp) the specified component.
float getLayoutAlignmentX It returns the alignment along the
(Container parent) x axis.
float getLayoutAlignmentY It returns the alignment along the
(Container parent) y axis.
int[][] getLayoutDimensions() It determines column widths and
row heights for the layout grid.
protected getLayoutInfo This method is obsolete and
GridBagLayoutInfo (Container parent, int supplied for backwards
sizeflag) compatibility.
protected GetLayoutInfo This method is obsolete and
GridBagLayoutInfo (Container parent, int supplied for backwards
sizeflag) compatibility.
Point getLayoutOrigin() It determines the origin of the
layout area, in the graphics
coordinate space of the target
container.
double[][] getLayoutWeights() It determines the weights of the
layout grid's columns and rows.
protected getMinSize(Container It figures out the minimum size of
Dimension parent, the master based on the
GridBagLayoutInfo information from getLayoutInfo.
info)
protected GetMinSize(Container This method is obsolete and
Dimension parent, supplied for backwards
GridBagLayoutInfo compatibility only
info)

Sample:

SCP-PF103 | 165
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

GroupLayout

GroupLayout groups its components and places them in a Container


hierarchically. The grouping is done by instances of the Group class.

Group is an abstract class and two concrete classes which implement


this Group class are SequentialGroup and ParallelGroup.

SCP-PF103 | 166
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SequentialGroup positions its child sequentially one after another where


as ParallelGroup aligns its child on top of each other.

The GroupLayout class provides methods such as createParallelGroup()


and createSequentialGroup() to create groups.

GroupLayout treats each axis independently. That is, there is a group


representing the horizontal axis, and a group representing the vertical axis.
Each component must exists in both a horizontal and vertical group, otherwise
an IllegalStateException is thrown during layout, or when the minimum,
preferred or maximum size is requested.

Nested Classes
Modifier Class Description
and Type
static GroupLayout.Alignment Enumeration of the possible ways
class ParallelGroup can align its children.
class GroupLayout.Group Group provides the basis for the two types
of operations supported by GroupLayout:
laying out components one after another
(SequentialGroup) or aligned
(ParallelGroup).
class GroupLayout.ParallelGroup It is a Group that aligns and sizes it's
children.
class GroupLayout.SequentialGr It is a Group that positions and sizes its
oup elements sequentially, one after another.

Data Fields
Modifier Field Description
and
Type
static DEFAULT_SIZE It indicates the size from the component or gap
int should be used for a particular range value.
static PREFERRED_SIZE It indicates the preferred size from the
int component or gap should be used for a particular
range value.
Constructors
GroupLayout(Container It creates a GroupLayout for the specified
host) Container.
Useful Methods
Modifier and Type Field Description
void addLayoutComponent It notify that a Component
(Component component, has been added to the
Object constraints) parent container.
void addLayoutComponent It notify that a Component
(String name, has been added to the
Component component) parent container.
GroupLayout. createBaselineGroup It creates and returns a
ParallelGroup (boolean resizable, ParallelGroup that aligns
boolean anchorBaselineToTop) it's elements along the
baseline.
GroupLayout. createParallelGroup() It creates and returns a
ParallelGroup ParallelGroup with an
alignment of
Alignment.LEADING
GroupLayout. createParallelGroup It creates and returns a
ParallelGroup (GroupLayout.Alignment ParallelGroup with the
alignment) specified alignment.

SCP-PF103 | 167
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

GroupLayout. createParallelGroup It creates and returns a


ParallelGroup (GroupLayout.Alignment ParallelGroup with the
alignment, specified alignment and
boolean resizable) resize behavior.
GroupLayout. createSequentialGroup() It creates and returns a
SequentialGroup SequentialGroup.
boolean getAutoCreateContainerGaps() It returns true if gaps
between the container and
components that border
the container are
automatically created.
boolean getAutoCreateGaps() It returns true if gaps
between components are
automatically created.
boolean getHonorsVisibility() It returns whether
component visiblity is
considered when sizing
and positioning
components.
float getLayoutAlignmentX It returns the alignment
(Container parent) along the x axis.
float getLayoutAlignmentY It returns the alignment
(Container parent) along the y axis.
Dimension maximumLayoutSize It returns the maximum
(Container parent) size for the specified
container.

Sample:

Output:

SCP-PF103 | 168
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Sample:

Output:

SpringLayout

A SpringLayout arranges the children of its associated container


according to a set of constraints.Constraints are nothing but horizontal
and vertical distance between two component edges. Every constrains are
represented by a SpringLayout.Constraint object.

Each child of a SpringLayout container, as well as the container itself,


has exactly one set of constraints associated with them.

Each edge position is dependent on the position of the other edge. If a


constraint is added to create new edge than the previous binding is
discarded. SpringLayout doesn't automatically set the location of the
components it manages.

Nested Classes
Modifier Class Description
and Type
static SpringLayout.Constraints It is a Constraints object helps to govern
class component's size and position change in a
container that is controlled by SpringLayout

SCP-PF103 | 169
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Data Fields
Modifier Field Description
and Type
static BASELINE It specifies the baseline of a component.
String
static EAST It specifies the right edge of a component's bounding
String rectangle.
static HEIGHT It specifies the height of a component's bounding
String rectangle.
static HORIZON It specifies the horizontal center of a component's
String TAL_CENT bounding rectangle.
ER
static NORTH It specifies the top edge of a component's bounding
String rectangle.
static SOUTH It specifies the bottom edge of a component's bounding
String rectangle.
static VERTICAL It specifies the vertical center of a component's
String _CENTER bounding rectangle.
static WEST It specifies the left edge of a component's bounding
String rectangle.
static WIDTH It specifies the width of a component's bounding
String rectangle.
Useful Methos
Modifier and Type Method Description
void addLayoutComponent If constraints is an instance
(Component of SpringLayout. Constraints,
component, associates the constraints
Object constraints) with the specified
component.
void addLayoutComponent Has no effect, since this
(String name, layout manager does not use
Component c) a per-component string.
Spring getConstraint(String It returns the spring
edgeName, controlling the distance
Component c) between the specified edge
of the component and the top
or left edge of its parent.
SpringLayout.Constraints getConstraints It returns the constraints for
(Component c) the specified component.
float getLayoutAlignmentX It returns 0.5f (centered).
(Container p)
float getLayoutAlignmentY It returns 0.5f (centered).
(Container p)
void invalidateLayout It Invalidates the layout,
(Container p) indicating that if the layout
manager has cached
information it should be
discarded.
void layoutContainer It lays out the specified
(Container parent) container.
Dimension maximumLayoutSize It is used to calculates the
(Container parent) maximum size dimensions
for the specified container,
given the components it
contains.
Dimension minimumLayoutSize It is used to calculates the
(Container parent) minimum size dimensions for
the specified container, given
the components it contains.
Dimension preferredLayoutSize It is used to calculates the
(Container parent) preferred size dimensions for
the specified container, given
the components it contains.

SCP-PF103 | 170
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Sample:

Output:

ScrollPaneLayout

The layout manager used by JScrollPane. JScrollPaneLayout is


responsible for nine components: a viewport, two scrollbars, a row
header, a column header, and four "corner" components.

Nested Class
Modifier Class Description
and Type
static ScrollPaneLayout.UIResource It is UI resource version of
class ScrollPaneLayout.

Data Fields
Modifier and Type Field Description
protected JViewport colHead It is column header child.
protected hsb It is scrollpane's horizontal scrollbar child.
JScrollBar
protected int hsbPolicy It displays policy for the horizontal scrollbar.
protected lowerLeft This displays the lower left corner.
Component
protected lowerRight This displays in the lower right corner.
Component
protected JViewport rowHead It is row header child.

SCP-PF103 | 171
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

protected upperLeft This component displays in the upper left


Component corner.
protected upperRight This component displays in the upper right
Component corner.
protected JViewport viewport It is scrollpane's viewport child.
protected vsb It is scrollpane's vertical scrollbar child.
JScrollBar
protected int vsbPolicy It is the display policy for the vertical scrollbar.

Useful Methods
Modifier Method Description
and Type
void addLayoutComponent It adds the specified component to
(String s, Component c) the layout.
protected addSingletonComponent It removes an existing component.
Component (Component oldC,
Component newC)
JViewport getColumnHeader() It returns the JViewport object that
is the column header.
Component getCorner(String key) It returns the Component at the
specified corner.
JScrollBar getHorizontalScrollBar() It returns the JScrollBar object that
handles horizontal scrolling.
int getHorizontalScrollBarPolicy() It returns the horizontal scrollbar-
display policy.
JViewport getRowHeader() It returns the JViewport object that
is the row header.
JScrollBar getVerticalScrollBar() It returns the JScrollBar object that
handles vertical scrolling.
int getVerticalScrollBarPolicy() It returns the vertical scrollbar-
display policy.
JViewport getViewport() It returns the JViewport object that
displays the scrollable contents.

Sample:

Output:

SCP-PF103 | 172
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Search Indicator

SELF-SUPPORT: You can click the URL Search Indicator below to help you further
understand the lessons.

1. https://www.tutorialspoint.com/java/java_stack_class.htm
2. https://www.callicoder.com/java-stack/
3. https://www.geeksforgeeks.org/stack-class-in-java/
4. https://www.cse.unr.edu/~sushil/class/cs202/notes/stacks/sta
cks.html
5. https://medium.com/@stevenpcurtis.sc/infix-postfix-prefix-and-
reverse-polish-notation-299affa57acf
6. Goodrich, M., Tamassia, R. (2011). Data Structures and Algorithms
in Java. 5th Edition, John & Wiley Sons Pte. Ltd.
7. https://www.onlinegdb.com/online_java_compiler

General Instructions:
4. Answer the activities in the succeeding pages.
5. Submit it in a .PDF format with a filename convention <SURNAME>_<WEEK#> such
that BASTE_WEEK11.
6. The deadline for submission will be five days after it was discussed.

Learning Resources and Tools

6. Laboratory Manual or SCP


7. Ballpen
8. PC/Laptop
9. Internet
10. IDE (Eclipse, Netbeans, ect)

LET’S INITIATE!
Activity. Answer the following questions.

1. Why would you need to learn different layout managers upon learning
OOP?

2. If you are going to design a GUI concept for recording information of Pet
adoption system, what layout you choose and why?
SCP-PF103 | 173
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

3. In the GUI perspective below, what do you think is the layout manager
should be use best?

LET’S INQUIRE!
Program Tracing. Print the output of the following programs:

Output:

SCP-PF103 | 174
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

SCP-PF103 | 175
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INFER!
GUI Design. Design the prototype as shown below:

Write Your codes here:

SCP-PF103 | 176
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubric

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 177
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SCP -TOPICS: FINAL PERIOD TOPICS

Week 13 Java Swing Components


Lesson Title Other swing GUI components
Learning Discuss the various GUI swing components.
Outcome(s)
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

JPanel is Swing's version of AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent.
JFrame is Swing's version of Frame and is descended directly
from Frame class. The component which is added to the Frame, is
referred as its Content.
JWindow. This is Swing's version of Window and has descended directly
from Window class. Like Window it uses BorderLayout by default.
JLabel has descended from JComponent, and is used to create text
labels.
JButton class provides the functioning of push button. JButton allows
an icon, string or both associated with a button.
JTextField allow editing of a single line of text.

SCP-PF103 | 178
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Essential Content

Java Swing

Java Swing is a GUI Framework that contains a set of classes to provide


more powerful and flexible GUI components than AWT. Swing provides
the look and feel of modern Java GUI. Swing library is an official Java
GUI tool kit released by Sun Microsystems. It is used to create graphical
user interface with Java. Swing classes are defined
in javax.swing package and its sub-packages.

Features of Swing

1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel

Swing and JFC


JFC is an abbreviation for Java Foundation classes which encompass a
group of features for building Graphical User Interfaces(GUI) and adding
rich graphical functionalities and interactivity to Java applications. Java
Swing is a part of Java Foundation Classes (JFC).

Features of JFC

• Swing GUI components.


• Look and Feel support.
• Java 2D.

SCP-PF103 | 179
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

AWT and Swing Hierarchy

Introduction to Swing Classes


JPanel is Swing's version of AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent.
JFrame is Swing's version of Frame and is descended directly
from Frame class. The component which is added to the Frame, is
referred as its Content.
JWindow is Swing's version of Window and has descended directly
from Window class. Like Window it uses BorderLayout by default.
JLabel has descended from JComponent, and is used to create text
labels.
JButton class provides the functioning of push button. JButton allows
an icon, string or both associated with a button.
JTextField allow editing of a single line of text.

Creating a JFrame. There are two ways to create a JFrame Window.

1. By instantiating JFrame class.


2. By extending JFrame class.

SCP-PF103 | 180
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Creating JFrame window by Instantiating JFrame class

Creating JFrame window by extending JFrame class

Output:

SCP-PF103 | 181
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Points To Remember

1. Import the javax.swing and java.awt package to use the classes and
methods of Swing.
2. While creating a frame (either by instantiating or extending Frame
class), following two attributes are must for visibility of the frame:

setSize(int width, int height);


setVisible(true);

3. When you create objects of other components like Buttons, TextFields,


etc. Then you need to add it to the frame by using the method
- add(Component's Object);
4. You can add the following method also for resizing the frame
- setResizable(true);

Java Swing Components and Containers

A component is an independent visual control and Java Swing


Framework contains a large set of these components which provide rich
functionalities and allow high level of customization. They all are derived
from JComponent class. All these components are lightweight
components. This class provides some common functionality like
pluggable look and feel, support for accessibility, drag and drop, layout,
etc.
A container holds a group of components. It provides a space where a
component can be managed and displayed. Containers are of two types:

1. Top level Containers


o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel

SCP-PF103 | 182
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JButton

JButton class provides functionality of a button. It is used to create


button component. JButton class has three constructors.

Example:
In this example, we are creating two buttons using JButton class and
adding them into JFrame container.

JTextField
JTextField is used for taking input of single line of text. It is most widely
used text component. It has three constructors,
SCP-PF103 | 183
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.

Example:
In this example, we are creating text field using JTextField class and
adding into the JFrame container.

JPasswordField
In Java, Swing toolkit contains a JPasswordField Class. It is under
package javax.swing.JPasswordField class. It is specifically used for
password and it can be edited.

Declaration
public class JPasswordField extends JTextField

The JPasswordFieldContains 4 constructors. They are as follows:


1. JPasswordField()
2. JPasswordField(int columns)
3. JPasswordField(String text)
4. JPasswordField(String text, int columns)

SCP-PF103 | 184
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Example:
To generate a password component, swing provides JPasswordField that
takes user input in encrypted format.

JTextArea
In Java, Swing toolkit contains a JTextArea Class. It is under package
javax.swing.JTextArea class. It is used for displaying multiple-line text.

Declaration
public class JTextArea extends JTextComponent

The JTextArea Contains 4 constructors. Below are the following:


1. JTextArea()
2. JTextArea(String s)
3. JTextArea(int row, int column)
4. JTextArea(String s, int row, int column)

SCP-PF103 | 185
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Example:
Lets take an example to create text area in swing. We are using JTextArea
class to create text area and adding to JFrame container.

JCheckBox
The JCheckBox class is used to create chekbox in swing framework. In
this example, we are creating three checkboxes to get user response.

JCheckBox(String str)
Example:

SCP-PF103 | 186
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JRadioButton
Radio button is a group of related button in which only one can be
selected. JRadioButton class is used to create a radio button in Frames.
Following is the constructor for JRadioButton,
JRadioButton(String str)

Example
To create radio button in swing, we used jradiobutton class. It is used to
get single user response at a time.

SCP-PF103 | 187
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JComboBox
JComboBox is a combination of text fields and drop-down
list.JComboBox component is used to create a combo box in Swing.
Following is the constructor for JComboBox,
JComboBox(String arr[])

Example
Lets create an example to add JComboBox to the JFrame . It is used to
create a drop-down menu. See the below example.

SCP-PF103 | 188
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

A program to change background color of a frame (Using Action


Event)

SCP-PF103 | 189
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

SCP-PF103 | 190
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JList
In Java, Swing toolkit contains a JList Class. It is under package
javax.swing.JList class. It is used to represent a list of items together.
One or more than one item can be selected from the list.

Declaration

public class JList extends JComponent implements Scrollable,


Accessible

The JListContains 3 constructors. They are as follows:


1. JList()
2. JList(ary[] listData)
3. JList(ListModel<ary> dataModel)

Example:
In this example, we are creating a list of items using JList class. This list
is used to show the items in a list format and get user input from the list
of items. See the below example.

SCP-PF103 | 191
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Search Indicator

SELF-SUPPORT: You can click the URL Search Indicator below to help you further
understand the lessons.

1. https://www.tutorialspoint.com/java/java_stack_class.htm
2. https://www.callicoder.com/java-stack/
3. https://www.geeksforgeeks.org/stack-class-in-java/
4. https://www.cse.unr.edu/~sushil/class/cs202/notes/stacks/stac
ks.html
5. https://medium.com/@stevenpcurtis.sc/infix-postfix-prefix-and-
reverse-polish-notation-299affa57acf
6. Goodrich, M., Tamassia, R. (2011). Data Structures and Algorithms
in Java. 5th Edition, John & Wiley Sons Pte. Ltd.
7. https://www.onlinegdb.com/online_java_compiler

SCP-PF103 | 192
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

General Instructions:
1. Answer the activities in the succeeding pages.
2. Submit it in a .PDF format with a filename convention <SURNAME>_<WEEK#> such
that BASTE_WEEK11.
3. The deadline for submission will be five days after it was discussed.

Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

LET’S INITIATE!
Activity. Answer the following questions.

1. Why would an IT students would need to know how to create GUI


components in Java from scratch or in hard way manner?

2. What is the main difference between JComboBox and JListBox?

3. What are the two ways to create a JFrame Window?

LET’S INQUIRE!
1. GUI Modification. Go back to JComboBox particularly in the sample
program on page 19 (A program to change background color of a
frame (Using Action Event). Modify the program in which the
background of the JFrame changes its color as you choose or click the
item in the JComboBox even if without clicking the “click” button.
SCP-PF103 | 193
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Your codes here…

2. Create a simple login form that prompt a message “Login


successful” if the entered username is “user” and password is
“user1234”. Display or prompt “Login failed” if it did NOT match or
incorrect. Below is a sample design perspective:

Your codes here…

LET’S INFER!
GUI Design. Create a simple student registration form. Below is a
sample design perspective:

Write Your codes here


SCP-PF103 | 194
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubric

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 195
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 13 Advanced GUI Programing


Lesson Title Advanced Swing components
Learning Discuss the advanced swing components
Outcome(s)
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

Essential Content

JTable

In Java, Swing toolkit contains a JTable Class. It is under package


javax.swing.JTable class. It used to draw a table to display data.

The JTableContains 2 constructors. They are as following:

1. JTable()
2. JTable(Object[][] rows, Object[] columns)

Example:

We are creating an example to create a table using Jtable class and then
add it to the Jframe container.

Import javax.swing.*;
public class StableDemo1
{
Jframe table_f;
StableDemo1(){
table_f=new Jframe();
String table_data[][]={ {“1001”,”Cherry”}, {“1002”,”Candy”},
{“1003”,”Coco”}};
String table_column[]={“SID”,”SNAME”};
Jtable table_jt=new Jtable(table_data,table_column);
table_jt.setBounds(30,40,200,300);
JscrollPane table_sp=new JscrollPane(table_jt);
table_f.add(table_sp);
table_f.setSize(300,400);
table_f.setVisible(true);
SCP-PF103 | 196
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

}
public static void main(String[] args) {
new StableDemo1();
}
}

JscrollBar

In Java, Swing toolkit contains a JScrollBar class. It is under package


javax.swing.JScrollBar class. It is used for adding horizontal and
vertical scrollbar.

Declaration

public class JScrollBar extends JComponent implements Adjustable,


Accessible

The JScrollBarContains 3 constructors. They are as following:


1. JScrollBar()
2. JScrollBar(int orientation)
3. JScrollBar(int orientation, int value, int extent, int min_, intmax_)

SCP-PF103 | 197
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Example:

We can use swing JscrollBar class to create horizontal and vertical


scrollbar. In this example, we are creating horizontal and vertical
scrollbar.

import javax.swing.*;
class SScrollBarDemo
{
SScrollBarDemo()
{
JFrame scrollBar_f= new JFrame("studytonight ==> Scrollbar Demo");
JScrollBar scrollBar_s=new JScrollBar();
scrollBar_s.setBounds(100,100, 80,100);
scrollBar_f.add(scrollBar_s);
scrollBar_f.setSize(500,500);
scrollBar_f.setLayout(null);
scrollBar_f.setVisible(true);
}
public static void main(String args[])
{
new SScrollBarDemo();
}
}

SCP-PF103 | 198
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JMenuBar, JMenu and JMenuItem

In Java, Swing toolkit contains a JMenuBar, JMenu and JMenuItem


class. It is under package javax.swing.JMenuBar, javax.swing.JMenu
and javax.swing.JMenuItem class. The JMenuBar class is used for
displaying menubar on the frame. The JMenu Object is used for pulling
down the components of the menu bar. The JMenuItem Object is used
for adding the labelled menu item.

JMenuBar, JMenu and JMenuItem Declaration

public class JMenuBar extends JComponent implements MenuElement,


Accessible

public class JMenu extends JMenuItem implements MenuElement,


Accessible

public class JMenuItem extends AbstractButton implements Accessible,


MenuElement

Example:

Lets take an example to create menu and sub menu in the swing jframe
container. See the below example.

import javax.swing.*;
class SMenuDemo1
{
JMenu m_menu, m_submenu;
JMenuItem menu_i1, menu_i2, menu_i3, menu_i4, menu_i5;
SMenuDemo1()
{
JFrame menu_f= new JFrame("Menu and MenuItem Example");
JMenuBar menu_mb=new JMenuBar();
m_menu=new JMenu("Menu");
m_submenu=new JMenu("Sub Menu");
menu_i1=new JMenuItem("Red");
menu_i2=new JMenuItem("Pink");
menu_i3=new JMenuItem("Black");
menu_i4=new JMenuItem("Green");
menu_i5=new JMenuItem("White");
m_menu.add(menu_i1);
m_menu.add(menu_i2);
m_menu.add(menu_i3);
m_submenu.add(menu_i4);
m_submenu.add(menu_i5);
m_menu.add(m_submenu);
menu_mb.add(m_menu);
menu_f.setJMenuBar(menu_mb);
SCP-PF103 | 199
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

menu_f.setSize(500,500);
menu_f.setLayout(null);
menu_f.setVisible(true);
}
public static void main(String args[])
{
new SMenuDemo1();
}
}

JPopupMenu

In Java, Swing toolkit contains a JPopupMenu Class. It is under package


javax.swing.JPopupMenu class. It is used for creating popups
dynamically on a specified position.

Declaration

public class JPopupMenu extends JComponent implements Accessible,


MenuElement
SCP-PF103 | 200
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

The JPopupMenuContains 2 constructors. They are as following:

1. JPopupMenu()
2. JPopupMenu(String label)

Example:

import javax.swing.*;
import java.awt.event.*;
class PopupMenuDemo
{
PopupMenuDemo(){
final JFrame pop_upf= new Jframe(“studytonight èPopupMenu
Demo”);
final JpopupMenu popupmenu1 = new JpopupMenu(“Edit”);
JmenuItem pop_upcut = new JmenuItem(“Cut”);
JmenuItem pop_upcopy = new JmenuItem(“Copy”);
JmenuItem pop_uppaste = new JmenuItem(“Paste”);
popupmenu1.add(pop_upcut);
popupmenu1.add(pop_upcopy);
popupmenu1.add(pop_uppaste);
pop_upf.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent a)
{
popupmenu1.show(pop_upf ,a.getX(), a.getY());
}
});
pop_upf.add(popupmenu1);
pop_upf.setSize(300,300);
pop_upf.setLayout(null);
pop_upf.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuDemo();
}
}

SCP-PF103 | 201
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JcheckBoxMenuItem

In Java, Swing toolkit contains a JCheckBoxMenuItem Class. It is under


package javax.swing.JCheckBoxMenuItem class. It is used to create a
checkbox on a menu.

The JCheckBoxMenuItemContains 2 constructors. They are as following:

1. JCheckBoxMenuItem()
2. JCheckBoxMenuItem(Action a)
3. JCheckBoxMenuItem(Icon icon)
4. JCheckBoxMenuItem(String text)
5. JCheckBoxMenuItem(String text, boolean b)
6. JCheckBoxMenuItem(String text, Icon icon)
7. JCheckBoxMenuItem(String text, Icon icon, boolean b)

Example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class SCheckBoxDemo


{
public static void main(final String args[])
{
SCP-PF103 | 202
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JFrame checkbox_frame = new JFrame("studytonight ==>Jmenu


Example");
checkbox_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar checkbox_menuBar = new JMenuBar();
JMenu checkbox_fileMenu = new JMenu("File");
checkbox_fileMenu.setMnemonic(KeyEvent.VK_F);
checkbox_menuBar.add(checkbox_fileMenu);
JMenuItem checkbox_menuItem1 = new JMenuItem("Open",
KeyEvent.VK_N);
checkbox_fileMenu.add(checkbox_menuItem1);

JCheckBoxMenuItem checkbox_caseMenuItem = new


JCheckBoxMenuItem("Option_1");
checkbox_caseMenuItem.setMnemonic(KeyEvent.VK_C);
checkbox_fileMenu.add(checkbox_caseMenuItem);

ActionListener checkbox_aListener = new ActionListener()


{
public void actionPerformed(ActionEvent event)
{
AbstractButton checkbox_aButton = (AbstractButton)
event.getSource();
boolean checkbox_selected =
checkbox_aButton.getModel().isSelected();
String checkbox_newLabel;
Icon checkbox_newIcon;
if (checkbox_selected) {
checkbox_newLabel = "Value-1";
} else {
checkbox_newLabel = "Value-2";
}
checkbox_aButton.setText(checkbox_newLabel);
}
};

checkbox_caseMenuItem.addActionListener(checkbox_aListener);
checkbox_frame.setJMenuBar(checkbox_menuBar);
checkbox_frame.setSize(350, 250);
checkbox_frame.setVisible(true);
}
}

SCP-PF103 | 203
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JSeparator

In Java, Swing toolkit contains a JSeparator Class. It is under package


javax.swing.JSeparator class. It is used for creating a separator line
between two components.

Declaration

public class JSeparator extends JComponent implements


SwingConstants, Accessible

The JSeparatorContains 2 constructors. They are as following:

1. JSeparator()
2. JSeparator(int orientation)

Example:

import javax.swing.*;
class SeparatorDemo
{
JMenu sep_menu, sep_submenu;
JmenuItem sep_i1, sep_i2, sep_i3, sep_i4, sep_i5;
SeparatorDemo()
SCP-PF103 | 204
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

{
Jframe sep_f= new Jframe(“Separator Example”);
JmenuBar sep_mb=new JmenuBar();
sep_menu = new Jmenu(“Menu”);
sep_i1=new JmenuItem(“Black”);
sep_i2=new JmenuItem(“White”);
sep_menu.add(sep_i1);
sep_menu.addSeparator();
sep_menu.add(sep_i2);
sep_mb.add(sep_menu);
sep_f.setJMenuBar(sep_mb);
sep_f.setSize(500,500);
sep_f.setLayout(null);
sep_f.setVisible(true);
}
public static void main(String args[])
{
new SeparatorDemo();
}
}

JprogressBar

SCP-PF103 | 205
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

In Java, Swing toolkit contains a JProgressBar Class. It is under package


javax.swing.JProgressBarclass. It is used for creating a progress bar of a
task.

Declaration

public class JProgressBar extends JComponent implements


SwingConstants, Accessible

The JProgressBarContains 4 constructors. They are as following:


1. JProgressBar()
2. JProgressBar(int min, int max)
3. JProgressBar(int orient)
4. JProgressBar(int orient, int min, int max)

Example:

import javax.swing.*;
public class ProgressBarDemo extends JFrame
{
JProgressBar progBar_jb;
int progBar_i=0, progBar_num=0;
ProgressBarDemo()
{
progBar_jb=new JProgressBar(0,2000);
progBar_jb.setBounds(40,40,180,30);
progBar_jb.setValue(0);
progBar_jb.setStringPainted(true);
add(progBar_jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(progBar_i<=2000){
progBar_jb.setValue(progBar_i);
progBar_i = progBar_i + 10;
try{
Thread.sleep(150);
}
catch(Exception e){}
}
}
public static void main(String[] args) {
ProgressBarDemo obj=new ProgressBarDemo();
obj.setVisible(true);
obj.iterate();
}
}

SCP-PF103 | 206
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JTree

In Java, Swing toolkit contains a JTree Class. It is under package


javax.swing.JTreeclass. It is used for creating a tree-structured of data.
It is a very complex component.

Declaration

public class JTree extends JComponent implements Scrollable,


Accessible

The JTreeContains 3 constructors. They are as following:

1. JTree()
2. JTree(Object[] value)
3. JTree(TreeNode root)

Example:

In this example, we are creating a tree structure of a menu that shows a


directory. We used Jtree class to create tree structure. See the below
example.

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeDemo
{
JFrame tree_f;
TreeDemo()
{
tree_f=new JFrame();

SCP-PF103 | 207
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

DefaultMutableTreeNode tree_style=new
DefaultMutableTreeNode("Style");
DefaultMutableTreeNode tree_color=new
DefaultMutableTreeNode("color");
DefaultMutableTreeNode tree_font=new
DefaultMutableTreeNode("font");
tree_style.add(tree_color);
tree_style.add(tree_font);
DefaultMutableTreeNode tree_red=new
DefaultMutableTreeNode("red");
DefaultMutableTreeNode tree_blue=new
DefaultMutableTreeNode("blue");
DefaultMutableTreeNode tree_black=new
DefaultMutableTreeNode("black");
DefaultMutableTreeNode tree_green=new
DefaultMutableTreeNode("green");
tree_color.add(tree_red);
tree_color.add(tree_blue);
tree_color.add(tree_black);
tree_color.add(tree_green);
JTree tree_jt=new JTree(tree_style);
tree_f.add(tree_jt);
tree_f.setSize(200,200);
tree_f.setVisible(true);
}
public static void main(String[] args) {
new TreeDemo();
}
}

SCP-PF103 | 208
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Search Indicator

SELF-SUPPORT: You can click the URL Search Indicator below to help you further
understand the lessons.

• https://www.tutorialspoint.com/java/java_stack_class.htm
• https://www.callicoder.com/java-stack/
• https://www.geeksforgeeks.org/stack-class-in-java/
• https://www.cse.unr.edu/~sushil/class/cs202/notes/stacks/sta
cks.html
• https://medium.com/@stevenpcurtis.sc/infix-postfix-prefix-and-
reverse-polish-notation-299affa57acf
• Goodrich, M., Tamassia, R. (2011). Data Structures and Algorithms
in Java. 5th Edition, John & Wiley Sons Pte. Ltd.
• https://www.onlinegdb.com/online_java_compiler

General Instructions:
1. Answer the activities in the succeeding pages.
2. Submit it in a .PDF format with a filename convention <SURNAME>_<WEEK#> such
that BASTE_WEEK11.
3. The deadline for submission will be five days after it was discussed.

Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

LET’S INITIATE!
Activity. Answer the following questions.

4. Why would you need to learn different layout managers upon learning
OOP?

SCP-PF103 | 209
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

5. If you are going to design a GUI concept for recording information of Pet
adoption system, what layout you choose and why?

6. In the GUI perspective below, what do you think is the layout manager
should be use best?

LET’S INQUIRE!
Program Tracing. Print the output of the following programs:

Output:

SCP-PF103 | 210
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Output:

SCP-PF103 | 211
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INFER!
GUI Design. Design the prototype as shown below:

Write Your codes here:

SCP-PF103 | 212
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Grading Rubric

Specificat 50 30 15 5
ion
Accuracy The program The program The program is The program is
is 100% is 100% 100% running 100% running
running with running with with a low level of with a very poor
a high level an average Accuracy. level of
of Accuracy. level of Accuracy.
Accuracy.
User The program Program was The program was The program is
Requirem was being being fulfilled not being fulfilled not being
ents/ fulfilled and and utilized and utilized by fulfilled and
Functionali utilized through a method utilized by
ty through a method definitions. method
method. Used of Used of correct definitions.
Used of correct methods, data Used of correct
correct methods, data type and methods, data
methods, type and appropriateness type and
data type, appropriatene of naming class appropriatenes
and ss of naming is met. s of naming
appropriaten class is class is not
ess of somehow applied.
naming class met.
is highly met.
Error The program The program The program is The program is
Trapping is able to trap can trap able to trap not able to trap
possible possible possible human possible human
human error human error error or mistakes error or
or mistakes or mistakes upon data input mistakes upon
upon data upon data somehow. data input.
input fully. input.
Ability to The The The The
answer programmer’ programmer’s programmer’s programmer’s
the Query s ability to ability to ability to disability to
response respond to response respond to
confidently every query somehow every every query
every query regarding his query regarding regarding his
regarding his work. his work. work.
work.

SCP-PF103 | 213
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 14 Advanced OOP Principles


Lesson Title Abstract and Interface
Learning Discuss the advanced OOP Principles
Outcome(s)
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

ü The interface is a blueprint that can be used to implement a class


ü Abstract classes allow you to create blueprints for concrete
classes
Essential Content

Abstract Class

A class that is declared using “abstract” keyword is known as abstract


class. It can have abstract methods(methods without body) as well as
concrete methods (regular methods with body). A normal class(non-
abstract class) cannot have abstract methods. In this guide we will learn
what is a abstract class, why we use it and what are the rules that we
must remember while working with it in Java.

An abstract class can not be instantiated, which means you are not
allowed to create an object of it. Why? We will discuss that later in this
guide.

Why we need an abstract class?

Lets say we have a class Animal that has a method sound() and the
subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since the
animal sound differs from one animal to another, there is no point to
implement this method in parent class. This is because every child class
must override this method to give its own implementation details, like
Lion class will say “Roar” in this method and Dog class will say “Woof”.

So when we know that all the animal child classes will and should
override this method, then there is no point to implement this method in
parent class. Thus, making this method abstract would be the good
choice as by making this method abstract we force all the sub classes to

SCP-PF103 | 214
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

implement this method( otherwise you will get compilation error), also we
need not to give any implementation to this method in parent class.

Since the Animal class has an abstract method, you must need to declare
this class abstract.

Now each animal must have a sound, by making this method abstract we
made it compulsory to the child class to give implementation details to
this method. This way we ensures that every animal has a sound.

Abstract class Example

//abstract parent class


abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

public void sound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}
Output:

Woof

Hence for such kind of scenarios we generally declare the class as


abstract and later concrete classes extend these classes and override the
methods accordingly and can have their own methods as well.

Abstract class declaration

An abstract class outlines the methods but not necessarily implements


all the methods.
//Declaration using abstract keyword
abstract class A{
//This is abstract method
abstract void myMethod();
//This is concrete method with body
void anotherMethod(){
//Does something
}
}
SCP-PF103 | 215
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Rules

Note 1: As we seen in the above example, there are cases when it is


difficult or often unnecessary to implement all the methods in parent
class. In these cases, we can declare the parent class as abstract, which
makes it a special class which is not complete on its own.

A class derived from the abstract class must implement all those methods
that are declared as abstract in the parent class.

Note 2: Abstract class cannot be instantiated which means you cannot


create the object of it. To use this class, you need to create another class
that extends this this class and provides the implementation of abstract
methods, then you can use the object of that child class to call non-
abstract methods of parent class as well as implemented methods(those
that were abstract in parent but implemented in child class).

Note 3: If a child does not implement all the abstract methods of abstract
parent class, then the child class must need to be declared abstract as
well.

Do you know? Since abstract class allows concrete methods as well, it


does not provide 100% abstraction. You can say that it provides partial
abstraction. Abstraction is a process where you show only “relevant” data
and “hide” unnecessary details of an object from the user.

Interfaces on the other hand are used for 100% abstraction (See more
about abstraction here).
You may also want to read this: Difference between abstract class and
Interface in Java

Why can’t we create the object of an abstract class?

Because these classes are incomplete, they have abstract methods that
have no body so if java allows you to create object of this class then if
someone calls the abstract method using that object then What would
happen?There would be no actual implementation of the method to
invoke.
Also because an object is concrete. An abstract class is like a template,
so you have to extend it and build on it before you can use it.

Example to demonstrate that object creation of abstract class is not


allowed

As discussed above, we cannot instantiate an abstract class. This


program throws a compilation error.

abstract class AbstractDemo{


public void myMethod(){
SCP-PF103 | 216
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

System.out.println("Hello");
}
abstract public void anotherMethod();
}
public class Demo extends AbstractDemo{

public void anotherMethod() {


System.out.print("Abstract method");
}
public static void main(String args[])
{
//error: You can't create object of it
AbstractDemo obj = new AbstractDemo();
obj.anotherMethod();
}
}
Output:

Unresolved compilation problem: Cannot instantiate the type


AbstractDemo
Note: The class that extends the abstract class, have to implement all the
abstract methods of it, else you have to declare that class abstract as
well.

Abstract class vs Concrete class

A class which is not abstract is referred as Concrete class. In the above


example that we have seen in the beginning of this guide, Animal is a
abstract class and Cat, Dog & Lion are concrete classes.

Key Points:

An abstract class has no use until unless it is extended by some other


class.
If you declare an abstract method in a class then you must declare the
class abstract as well. you can’t have abstract method in a concrete class.
It’s vice versa is not always true: If a class is not having any abstract
method then also it can be marked as abstract.
It can have non-abstract method (concrete) as well.
I have covered the rules and examples of abstract methods in a separate
tutorial, You can find the guide here: Abstract method in Java
For now lets just see some basics and example of abstract method.
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden. An abstract class must be extended and in a
same way abstract method must be overridden.
4) A class has to be declared abstract to have abstract methods.

SCP-PF103 | 217
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Note: The class which is extending abstract class must override all the
abstract methods.

Example of Abstract class and method

abstract class MyClass{


public void disp(){
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}

class Demo extends MyClass{


/* Must Override this method while extending
* MyClas
*/
public void disp2()
{
System.out.println("overriding abstract method");
}
public static void main(String args[]){
Demo obj = new Demo();
obj.disp2();
}
}
Output:

overriding abstract method

Interface

In the last tutorial we discussed abstract class which is used for


achieving partial abstraction. Unlike abstract class an interface is used
for full abstraction. Abstraction is a process where you show only
“relevant” data and “hide” unnecessary details of an object from the
user(See: Abstraction). In this guide, we will cover what is an interface in
java, why we use it and what are rules that we must follow while using
interfaces in Java Programming.

What is an interface in Java?

Interface looks like a class but it is not a class. An interface can have
methods and variables just like the class but the methods declared in
interface are by default abstract (only method signature, no body, see:
Java abstract method). Also, the variables declared in an interface are
public, static & final by default. We will cover this in detail, later in this
guide.

SCP-PF103 | 218
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

What is the use of interface in Java?

As mentioned above they are used for full abstraction. Since methods in
interfaces do not have body, they have to be implemented by the class
before you can access them. The class that implements interface must
implement all the methods of that interface. Also, java programming
language does not allow you to extend more than one class, However you
can implement more than one interfaces in your class.

Syntax:

Interfaces are declared by specifying a keyword “interface”. E.g.:

interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
Example of an Interface in Java

This is how a class implements an interface. It has to provide the body of


all the methods that are declared in interface or in other words you can
say that class has to implement all the methods of interface.

Do you know? class implements interface but an interface extends


another interface.

interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
SCP-PF103 | 219
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Output:

implementation of method1
You may also like to read: Difference between abstract class and interface

Interface and Inheritance

As discussed above, an interface can not implement another interface. It


has to extend the other interface. See the below example where we have
two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class implements the
Inf2 it has to provide implementation of all the methods of interfaces Inf2
as well as Inf1.

Learn more about inheritance here: Java Inheritance

interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}
In this program, the class Demo only implements interface Inf2, however
it has to provide the implementation of all the methods of interface Inf1
as well, because interface Inf2 extends Inf1.
SCP-PF103 | 220
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Tag or Marker interface in Java

An empty interface is known as tag or marker interface. For example


Serializable, EventListener, Remote(java.rmi.Remote) are tag interfaces.
These interfaces do not have any field and methods in it. Read more about
it here.

Nested interfaces

An interface which is declared inside another interface or class is called


nested interface. They are also known as inner interface. For example
Entry interface in collections framework is declared inside Map
interface, that’s why we don’ use it directly, rather we use it like this:
Map.Entry.

Key points: Here are the key points to remember about interfaces:
1) We can’t instantiate an interface in java. That means we cannot
create the object of an interface

2) Interface provides full abstraction as none of its methods have body.


On the other hand abstract class provides partial abstraction as it can
have abstract and concrete(methods with body) methods both.

3) implements keyword is used by classes to implement an interface.

4) While providing implementation in class of any method of an


interface, it needs to be mentioned as public.

5) Class that implements any interface must implement all the methods
of that interface, else the class should be declared abstract.

6) Interface cannot be declared as private, protected or transient.

7) All the interface methods are by default abstract and public.

8) Variables declared in interface are public, static and final by default.

interface Try
{
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}
All of the above statements are identical.

9) Interface variables must be initialized at the time of declaration


otherwise compiler will throw an error.
SCP-PF103 | 221
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x
is not initialized at the time of declaration.

10) Inside any implementation class, you cannot change the variables
declared in interface because by default, they are public, static and final.
Here we are implementing the interface “Try” which has a variable x.
When we tried to set the value for variable x we got compilation error as
the variable x is public static final by default and final variables can not
be re-initialized.

class Sample implements Try


{
public static void main(String args[])
{
x=20; //compile time error
}
}
11) An interface can extend any interface but cannot implement it. Class
implements interface and interface extends interface.

12) A class can implement any number of interfaces.

13) If there are two or more same methods in two interfaces and a class
implements both interfaces, implementation of the method once is
enough.

interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
SCP-PF103 | 222
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

14) A class cannot implement two interfaces that have methods with
same name but different return type.

interface A
{
public void aaa();
}
interface B
{
public int aaa();
}

class Central implements A,B


{

public void aaa() // error


{
}
public int aaa() // error
{
}
public static void main(String args[])
{

}
}
15) Variable names conflicts can be resolved by interface name.

interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
/* reference to x is ambiguous both variables are x
* so we are using interface name to resolve the
* variable
*/
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
SCP-PF103 | 223
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Advantages of interface in java:

Advantages of using interfaces are as follows:

Without bothering about the implementation part, we can achieve the


security of implementation
In java, multiple inheritance is not allowed, however you can use
interface to make use of it as you can implement more than one interface.

Difference Between Abstract Class and Interface in Java

https://beginnersbook.com/2013/05/abstract-class-vs-interface-in-
java/

Search Indicator

SELF-SUPPORT: You can click the URL Search Indicator below to help you
further understand the lessons.

§ Goodrich, M., Tamassia, R. (2011). OOP Pronciples in Java. 5th


Edition, John & Wiley Sons Pte. Ltd.
§ https://www.tutorialspoint.com/java/java_stack_class.htm
§ https://www.callicoder.com/java-stack/
§ https://www.geeksforgeeks.org/stack-class-in-java/
§ https://www.cse.unr.edu/~sushil/class/cs202/notes/stacks/sta
cks.html
§ https://medium.com/@stevenpcurtis.sc/infix-postfix-prefix-and-
reverse-polish-notation-299affa57acf
§ https://www.onlinegdb.com/online_java_compiler

General Instructions:

1. Answer the activities in the succeeding pages.


2. Submit it in a .PDF format with a filename convention
<SURNAME>_<WEEK#> such that BASTE_WEEK14.
3. The deadline for submission will be five days after it was
discussed.

SCP-PF103 | 224
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

LET’S INITIATE!
Activity. Answer the following questions.

1. Define Abstract class in your own words?


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.
2. Define Interface in your own words?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.
3. Give atleast 5 differences of Abstract and Interface?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

SCP-PF103 | 225
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INQUIRE!
Activity. Answer the following questions.

1. Describe how Interface is important in OOP principle?


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

2. What is the difference between abstract methods and concrete methods?


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

LET’S INFER!
Activity. List atleast 5 Interface you know in Java whether you used it before
or not.

SCP-PF103 | 226
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 15
Lesson Title Exception Handling Techniques
Learning Discuss the different exception handling
Outcome(s) techniques
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

ü Exception Handling is a mechanism to handle runtime errors


ü Checked Exception. The classes which directly inherit
Throwable class except RuntimeException and Error are known
as checked exceptions
ü Unchecked Exception. The classes which inherit
RuntimeException are known as unchecked
ü Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Essential Content

The Exception Handling in Java is one of the powerful mechanism to


handle the runtime errors so that normal flow of the application can be
maintained.

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime.

What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException,
RemoteException, etc

SCP-PF103 | 227
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow


of the application. An exception normally disrupts the normal flow of the
application that is why we use exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in your program and there occurs an


exception at statement 5, the rest of the code will not be executed i.e.
statement 6 to 10 will not be executed. If we perform exception handling,
the rest of the statement will be executed. That is why we use exception
handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception


hierarchy which is inherited by two subclasses: Exception and Error. A
hierarchy of Java Exception classes are given below:

SCP-PF103 | 228
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here,
an error is considered as the unchecked exception. According to Oracle,
there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except


RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked


exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.

SCP-PF103 | 229
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we


should place exception code. The try block must be
followed by either catch or finally. It means, we can't use
try block alone.

catch The "catch" block is used to handle the exception. It must


be preceded by try block which means we can't use catch
block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of


the program. It is executed whether an exception is
handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling where we using a try-catch
statement to handle the exception.

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
SCP-PF103 | 230
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

In the above example, 100/0 raises an ArithmeticException which is


handled by a try-catch block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur.
They are as follows:

1) A scenario where ArithmeticException occurs If we divide any number


by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs If we have a null value


in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs The wrong


formatting of any value may occur NumberFormatException. Suppose
I have a string variable that has characters, converting this variable
into digit will occur NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs If you are


inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Search Indicator

SELF-SUPPORT: You can click the URL Search Indicator below to help you
further understand the lessons.

§ Goodrich, M., Tamassia, R. (2011). OOP Pronciples in Java. 5th


Edition, John & Wiley Sons Pte. Ltd.
§ https://www.tutorialspoint.com/java/java_stack_class.htm
§ https://www.callicoder.com/java-stack/
§ https://www.geeksforgeeks.org/stack-class-in-java/
SCP-PF103 | 231
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

§ https://www.cse.unr.edu/~sushil/class/cs202/notes/stacks/sta
cks.html
§ https://medium.com/@stevenpcurtis.sc/infix-postfix-prefix-and-
reverse-polish-notation-299affa57acf
§ https://www.onlinegdb.com/online_java_compiler

General Instructions:

1. Answer the activities in the succeeding pages.


2. Submit it in a .PDF format with a filename convention
<SURNAME>_<WEEK#> such that BASTE_WEEK14.
3. The deadline for submission will be five days after it was
discussed.
Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

LET’S INITIATE!
Activity. Answer the following questions.

1. What is the importance of Handling Exceptions in Programming?


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.
2. What is the difference between checked and unchecked exceptions?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

SCP-PF103 | 232
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

3. Define what is an error in a program?


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

LET’S INQUIRE!
Activity. Answer the following questions.

1. Give atleast 3 example of checked Exception.


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

2. Give atleast 3 example of unchecked Exception.


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

LET’S INFER!
Activity. Explain the scenario where an error occurred in your program; a
program with no exception compare to a program with a defined exception.

SCP-PF103 | 233
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 16 JDBC
Lesson Title Basic Database in Java
Learning Discuss the JDBC database in Java isng
Outcome(s) SQLite
Time Frame

At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder

ü JDBC - Java Database Connectivity. It provides API or Protocol to


interact with different databases.
ü The JDBC API - it provides various methods and interfaces for
easy communication with database.
ü The JDBC DriverManager - it loads database specific drivers in
an application to establish connection with database.
ü The JDBC test suite - it will be used to test an operation being
performed by JDBC drivers.
ü The JDBC-ODBC bridge - it connects database drivers to the
database.

Essential Content

JDBC - Java Database Connectivity. It provides API or Protocol to interact


with different databases. With the help of JDBC driver we can connect
with different types of databases. Driver is must needed for connection
establishment with any database.
A driver works as an interface between the client and a database server.

JDBC have so many classes and interfaces that allow a java application
to send request made by user to any specific DBMS(Data Base
Management System).

SCP-PF103 | 234
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

JDBC supports a wide level of portability. It provides interfaces that are


compatible with java application

- See more at:

http://www.java2all.com/1/4/18/97/Technology/JDBC/Introduction-
to-JDBC/introduction#sthash.3FPR1OC3.dpuf

Components of JDBC

JDBC has four main components as under and with the help of these
components java application can connect with database.

1. The JDBC API - it provides various methods and interfaces for easy
communication with database.
2. The JDBC DriverManager - it loads database specific drivers in an
application to establish connection with database.
3. The JDBC test suite - it will be used to test an operation being
performed by JDBC drivers.
4. The JDBC-ODBC bridge - it connects database drivers to the
database.

In this section we make a connection using JDBC to a Microsoft Access


database. This connection is made with the help of a JdbcOdbc driver.
You need to use the following steps for making the connection to the
database.

Creating a Database

Opps…Before you proceed launch your IDE (Eclipse, Netbeans, etc.).


Then create a project. Name your project as “My Pet Database”. After you
create a project, go to the project file in your workspace, then create a
folder and name it as “Database”. It should look like below:

SCP-PF103 | 235
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Step 1 : Open Microsoft Access and select Blank database option and
give the database name as File name option. Name your database as
“Pet_DB.accdb”

Step 2 : Create a table and insert your data into the table. Name your
table, “tbl_Pet”.

Step 3 : Save the table with the desired name; in this article we save the
following records with the table name tbl_Pet.

Note: Now this time, close the MS Access application. Then locate now your
database “Pet.accdb”. Normally, it will be saved at My Documents folder.
If you find it, copy and then paste it to your Project source file where
“Database” folder is located. In our case we have “My Pet Database”. This
makes your program collate all the necessary files so that there will be no
issues in the latter compilation and deployment of your Project.

Now Creating DSN of your database

Step 4 : Open your Control Panel and then select Administrative


Tools.
Step 5 : Click on Data Source(ODBC)-->System DSN.

SCP-PF103 | 236
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Step 6 : Now click on add option for making a new DSN.


Select Microsoft Access Driver (*.mdb. *.accdb) and then click
on Finish.

Step 7 : Make your desired Data Source Name and then click on
the Select option, for example in this article we use the
name pet_dbms_dsn.

SCP-PF103 | 237
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Step 8 : Now click select and choose your data source file (Look for your
Java project---“My Pet Database”).
Step 9 : Choose Database folder, then select “Pet_DB.accdb” as
Database Name. Click ok and then Finish.

Step 10: Let’s get started. Go Back to your IDE (Eclipse, Netbeans, etc.)
Step 11: Create a class “DBConnection” in your project.

Background:

Jdbc-Odbc bridge driver create connection between java application and


'MS Access database'. Connection using JDBC-ODBC bridge driver.

What we need?
• Connection
• DriverManager
• Statement
• ResultSet

Now Type this above to your class


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

or simply,

import java.sql.*;

Step 11: Next, make these declarations inside your main method:

String driverName="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:pet_dbms_dsn";
Connection dbConn;
Statement st;
SCP-PF103 | 238
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

ResultSet rs;
String strQuery="select *from tbl_Pet";

try {
Class.forName(driverName);
dbConn=DriverManager.getConnection(url);
st=dbConn.createStatement();
rs=st.executeQuery(strQuery);
int id;
JOptionPane.showMessageDialog(null,"Connected" );
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null,e.getMessage());
// System.out.println("Error: Class not found");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e.getMessage());
//System.out.println("SQL code does not execute.");
} catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage());
//System.out.println("Error:connection not created");
}

Description of Program

In the above program, Jdbc-Odbc bridge driver create connection


between java application and 'MSAccess database'. After creating
connection it also execute query.

Code Description

• import java.sql -- Since 'java.sql' class support all the methods


needed to create connection. We need to import it first.
• Connection dbConn;-- Creation of "connection" class object ,which
is used to represent connection and also used to create "statement"
class object for executing query.
• Class.forName(driverName); --In this program "forName()"
function is used to load the JDBC-ODBC bridge driver. It takes
driver name as an argument (String
driverName="sun.jdbc.odbc.JdbcOdbcDriver";) and load it by
checking its availability.
• dbConn=DriverManager.getConnection(url); --In the above code,
connection class object 'dbConn' is used by DriverManager
to connect to database using "getConnection()"
."getConnection()" takes url (String url="jdbc:odbc:mydsn";) of
database and datasource name to create connection.
o dbConn=DriverManager.getConnection(url,username,pass
word) – You make take these arguments.

SCP-PF103 | 239
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

• Statement st = con.createStatement(); --In this code line ,we


create 'Statement' class object using 'con' object of connection. The
Statement object is used to fetch result set by executing query.
• ResultSet rs = st.executeQuery(strQuery);--In this snippet,
statement class object "st" executes query (String strQuery="Select
* from tbl_Pet") and store result in "ResultSet" class object "rs".
• dbConn.close();-- It is used to close the connection open by con
object. Closing an open connection makes the data becomes safe.
• Catch Blocks are of course understandable. They are used to
handle exceptions such as ClassNotFoundException,
SQLException, and the rest of the Exceptions.

Step 12: Run your application and you should see the prompt message
that you are get “Connected”. Now, put these line of codes before
dbConn.close().
System.out.println("Pet ID\tName\t\tGender\tAge\tColor");
while(rs.next()){
System.out.print(rs.getInt("Pet_ID")+"\t");
System.out.print(rs.getString("Pet_Name")+"\t\t");
System.out.print(rs.getString("Pet_Gender")+"\t");
System.out.print(rs.getInt("Pet_Age")+"\t");
System.out.print(rs.getString("Pet_Color")+"\t");
System.out.println();
}

Code Description:

Execute a SQL statement on a valid Statement object

Remember that we have this: strQuery="Select * from tbl_Pet";

Call st.execute("SQL statement") when you require to execute a


SQL query st.Excecute(strQuery). It returns the number of rows
effected by the query. If the last query holds a ResultSet to be
returned which generally occurs with SELECT...type queries, then
call rs.getResultSet() or better rs.next() which returns the ResultSet
object. The above code shows how to use a SELECT query and
display the value contained in the all of the columns of the table.

Note that if your datatype in your database is of int or number, you


must use the rs.getInt(int arg) or rs.getInt(String arg). The
methods are overloaded, it takes int argument like rs.getInt(1)
returns the values of the first column in the table as index, so next
column takes index 2,next is 3, and so on. I would recommend you
use this other method rs.getInt(“Pet_Name”) which takes the String
argument means that you are explicitly call a column name rather
than its index.
Try this for JOptionPane…JTable, and other components you know
to call the data from your database.
SCP-PF103 | 240
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

NOTE: Cleanup after finishing the job

To clean up after we are done with the SQL query, we call st.close()
to dispose the object Statement. Then, before we end our program or
after the point where we decide that the database is not required any
more, we close the database with a call to dbConn.close(). The
following code does the cleanup after we are done:

st.Close();
//rs.close(); Not recommended if your rs is not null or contains no
records
dbConn.Close();

Step 13: Inserting record to database (Don’t forget to comment


st.Close(), rs.close() and dbConn.Close() as of the moment.)
int P_id=4;
String P_name="Ilahra Koh";
String P_Gender="Female";
int P_Age=3;
String P_Color="Sky Green";
strQuery="insert into tbl_Pet values ("+ P_id
+",'"+P_name+"','"+P_Gender+"',"+P_Age+",'"+P_Color+"')";
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null,"Records successfully
added");

Code Description:

Ofcourse the first five statements are known to you. Let us get the
next alien statement,

strQuery="insert into tbl_Pet values ("+ P_id


+",'"+P_name+"','"+P_Gender+"',"+P_Age+",'"+P_Color+"')";

• strQuery="insert into tbl_Pet values ()”. You may find this


difficult to understand, but what it did was everytime you
want to insert new records to your database table use the
INSERT SQL statement. This is part of the DML or Data
Manipulation Language offered by a database such as MS
Access MSSQL server. This means that you are inserting these
values to your table Pet “tbl_Pet”.

Syntax for SQL INSERT:

INSERT INTO TABLE_NAME [(col1, col2, col3,...colN)]VALUES


(value1, value2, value3,...valueN);
col1, col2,...colN -- the names of the columns in the table
into which you want to insert data.
SCP-PF103 | 241
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

While inserting a row, if you are adding value for all the
columns of the table you need not specify the column(s)
name in the sql query. But you need to make sure the order
of the values is in the same order as the columns in the
table. The sql insert query will be as follows.

INSERT INTO TABLE_NAME VALUES (value1, value2,


value3,...valueN);

For Example: If you want to insert a row to the


employee table, the query would be like,

INSERT INTO employee (id, name, dept, age, salary


location) VALUES (105, 'Srinath', 'Aeronautics', 27,
33000);

NOTE:When adding a row, only the characters or date


values should be enclosed with single quotes. If you are
inserting data to all the columns, the column names
can be omitted. The above insert statement can also be
written as,

INSERT INTO employee VALUES (105, 'Srinath',


'Aeronautics', 27, 33000);

§ ("+ P_id
+",'"+P_name+"','"+P_Gender+"',"+P_Age+",'"+P_Color+"')"; .
These arguments instruct our application to insert the values
to our database tbl_Pet table. Here’s how it is:
• + is a delimiter that separate the String values into
pieces of records so that our database table would
recognize it and store to respective column on the
tbl_Pet. Respectively, P_id for Pet_ID, P_name for
Pet_Name, and so on.
• Remember that when you store int type or non-string
type, you should follow this syntax : “+ P_is +” .
• While, if record is string take this : ‘”+ P_name +”’. See
the difference? “+ for int or non-string type and ‘”+ for
String type.
• st.executeUpdate(strQuery); - Method call to execute an
Insert SQL.

Step 14: Updating (Modifying) existing records

P_id=2;
strQuery="update tbl_Pet set Pet_name='Lee Tsu Nun',
Pet_Gender='Male',Pet_Age=90,Pet_Color='Fuscia' where Pet_Id="+
P_id +"";
SCP-PF103 | 242
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null,"Records successfully
updated");

Code Description:
§ P_Id = 2 means that we are changing records of Pet whose
id is 2
§ strQuery="update tbl_Pet set Pet_name='Lee Tsu
Nun',Pet_Gender='Male',Pet_Age=90,Pet_Color='Fuscia'
where Pet_Id="+ P_id +"";

o The UPDATE Statement is used to modify the existing


rows in a table.

SQL UPDATE Statement Syntax:

UPDATE table_name SET column_name1 = value1,


column_name2 = value2, ...[WHERE condition]
o table_name - the table name which has to be
updated.
o column_name1, column_name2.. - the columns
that gets changed.
o value1, value2... - are the new values.
• NOTE:In the Update statement, WHERE clause
identifies the rows that get affected. If you do not
include the WHERE clause, column values for all the
rows get affected.

For Example: To update the location of an employee,


the sql update query would be like,

UPDATE employee SET location ='Mysore' WHERE id =


101;

To change the salaries of all the employees, the query


would be,

UPDATE employee SET salary = salary + (salary * 0.2);

§ Don’t forget the where clause for it will change all the
records to your table. Update SQL statements seeks for an
existing records through a unique id, in our case its Pet_ID
where value is taken from P_Id variable. Don’t forget also
the set keyword. And all the rests are logically clear.
§ st.executeUpdate(strQuery); - Method call to execute an
Update SQL.

Step 15: Deleting (Removing) records from a database

SCP-PF103 | 243
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

P_id=3;
strQuery="Delete from tbl_Pet where Pet_Id="+ P_id+"";
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null,"Records successfully
deleted");

Code Description:

§ P_Id = 3 means that we are deleting records of Pet whose


id is 3
§ strQuery="Delete from tbl_Pet where Pet_Id="+ P_id+"";

• SQL Delete Statement


The DELETE Statement is used to delete rows from a
table. The Syntax of a SQL DELETE statement is:
DELETE

FROM table_name [WHERE condition];


o table_name -- the table name which has to be
updated.

§ NOTE: The WHERE clause in the sql delete command is


optional and it identifies the rows in the column that gets
deleted. If you do not include the WHERE clause all the rows
in the table is deleted, so be careful while writing a DELETE
query without WHERE clause.

For Example: To delete an employee with id 100 from the


employee table, the sql delete query would be like,

DELETE FROM employee WHERE id = 100;

To delete all the rows from the employee table, the query
would be like,

DELETE FROM employee;


§ st.executeUpdate(strQuery); - Method call to execute a Delete
SQL.

Step 16: Searching for an existing Records


P_id=3;
strQuery="Select *from tbl_Pet where Pet_Id="+ P_id+"";
rs=st.executeQuery(strQuery);
rs=st.executeQuery(strQuery);
while(rs.next()){
System.out.print(rs.getInt("Pet_ID")+"\t");
System.out.print(rs.getString("Pet_Name")+"\t\t");
System.out.print(rs.getString("Pet_Gender")+"\t");
System.out.print(rs.getInt("Pet_Age")+"\t");
SCP-PF103 | 244
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

System.out.print(rs.getString("Pet_Color")+"\t");
System.out.println();
}
Step 17: Congratulations! You made it right Programmers.

NOW HERE ARE AGAIN THE STEPS: Steps to connect JDBC-ODBC


bridge driver with database
Step1:-First, create a database using "MS Access", which must have
the same name ,which you use for query and column name must be
same as you use for retrieving values from database.
Step2:-Go to Start >control panel >Administrative tool > Data source
(ODBC).
Step3:-Double click on Data source (ODBC),click on "Add" button,
Select MS Access driver...click on "Finish" button.
Step4:-Give name to "Data source name". Click on "Select" button and
browse your MS access file of ".mbd" and “.accdb” extension .Click
"OK".
Step5:-Now your database is ready to connect using JDBC-ODBC
bridge driver. For this you have to mention Data source name in your
application

CHALLENGE YOURSELF. Create a new class. Name it


“PetMainClass.java”. The codes are below:

import java.sql.SQLException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class PetMainClass {
public static void main(String[] args) throws SQLException {
Pet_DBMS pet=new Pet_DBMS();
String strQuery="select *from tbl_pet";
int p_id;
String p_name="",p_gender="",p_color="";
int p_age=12;
int ch;
String menu="1-Add\n2-Edit\n3-Delete\n4-View Records\n5-Exit";
do{
System.out.println(menu+"\nPlease Select: ");
ch=new Scanner(System.in).nextInt();
switch (ch) {
case 1://Insert new records
System.out.println("Please input data for Pet: ");
System.out.println("ID: ");
p_id =new Scanner(System.in).nextInt();
System.out.println("Name: ");
p_name =new Scanner(System.in).nextLine();
System.out.println("Gender: ");
p_gender =new Scanner(System.in).nextLine();
SCP-PF103 | 245
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

System.out.println("Age: ");
p_age =new Scanner(System.in).nextInt();
System.out.println("Color: ");
p_color =new Scanner(System.in).nextLine();
strQuery="insert into tbl_pet values("+ p_id +",'"+ p_name +"','"
+ p_gender +"',"+ p_age +",'"+ p_color +"')";
pet.insertRecord(strQuery);
JOptionPane.showMessageDialog(null,"Records
successfully Added");
break;
case 2://Updating existing records
System.out.println("Input ID:");
p_id=new Scanner(System.in).nextInt();
System.out.println("Please input new data for Pet: " +p_id);
System.out.println("ID: ");
p_id =new Scanner(System.in).nextInt();
System.out.println("Name: ");
p_name =new Scanner(System.in).nextLine();
System.out.println("Gender: ");
p_gender =new Scanner(System.in).nextLine();
System.out.println("Age: ");
p_age =new Scanner(System.in).nextInt();
System.out.println("Color: ");
p_color =new Scanner(System.in).nextLine();
strQuery="update tbl_pet set Pet_name='"+ p_name
+"',Pet_gender='"+ p_gender +"',Pet_age="+ p_age
+",Pet_color='"+ p_color +"' where Pet_id ="+ p_id +"";
pet.updateRecord(strQuery);
JOptionPane.showMessageDialog(null,"Records
successfully Updated");
break;
case 3://Deleting existing records
System.out.println("Input ID:");
p_id=new Scanner(System.in).nextInt();
pet.deleteRecord("delete from tbl_pet where pet_id="+ p_id
+"");
JOptionPane.showMessageDialog(null,"Records
successfully Deleted");
pet.deleteRecord(strQuery);
break;
case 4: //Show all records
strQuery="select *from tbl_Pet";
System.out.println("Pet
ID\tName\t\tGender\tAge\tColor");
pet.showRecords(strQuery);
break;
case 6: //search specific records
System.out.println("Input ID:");
p_id=new Scanner(System.in).nextInt();
SCP-PF103 | 246
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

strQuery="select *from tbl_Pet where Pet_id="+ p_id +"";


System.out.println("Pet
ID\tName\t\tGender\tAge\tColor");
pet.searchRecords(strQuery);
break;
case 5:
System.exit(0);
break;
default:
break;
}
}while(ch!=5);
}
}

1. And, here is your “PetDBMS.java” class.

import java.sql.*;
import javax.swing.JOptionPane;

public class Pet_DBMS{


Connection dbConn;
Statement st=null;
ResultSet rs=null;
String driverName="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:myPetDBMS";
String strQuery="";
Pet_DBMS(){
dbConnection();
}
void dbConnection(){
try {
Class.forName(driverName);
dbConn=DriverManager.getConnection(url);
st=dbConn.createStatement();
JOptionPane.showMessageDialog(null,"Connected");
//st.close();
//dbConn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
void showRecords(String SQLStatement) throws SQLException{
rs=st.executeQuery(SQLStatement);
System.out.println("ID\tName\tGender\tAge\tColor");
while(rs.next()){
System.out.print(rs.getInt("Pet_id")+"\t");
SCP-PF103 | 247
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

System.out.print(rs.getString("Pet_name")+"\t");
System.out.print(rs.getString("Pet_gender")+"\t");
System.out.print(rs.getInt("Pet_age")+"\t");
System.out.print(rs.getString("Pet_color"));
System.out.println();
}
}

void insertRecord(String SQLStatement)throws SQLException{


st.executeUpdate(SQLStatement);
}
void updateRecord(String SQLStatement) throws SQLException{
st.executeUpdate(SQLStatement);
}
void deleteRecord(String SQLStatement) throws SQLException{
st.executeUpdate(SQLStatement);
}
void searchRecords(String SQLStatement) throws SQLException{
st.executeQuery(SQLStatement);
showRecords(SQLStatement);
}
}
2. Try the following queries:
§ Display gender who are Male? Female?
§ Display all age greater than 17?
§ Display only columns (Pet Name, Pet Gender)
§ Display dominant colors.
3. Try adding another table. Say “tbl_Owner”.

GUI Example:

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.w3c.dom.events.MouseEvent;
import net.proteanit.sql.DbUtils;

public class PET_DBMS_GUI2 extends JFrame implements


ActionListener,KeyListener,MouseListener{
JLabel lblId,lblName,lblAge,lblGender,lblColor;
JTextField txtId,txtName,txtAge,txtColor,txtSearch;
JComboBox cboGender;
JButton btnSave,btnUpdate,btnDelete,btnClose,btnSearch;
JPanel panelPet,panelPetTable;
JTable petTable;
JScrollPane petScrollPane;
String gender[]={"Male","Female"};
SCP-PF103 | 248
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

String strQuery="";
Connection dbConn;
Statement st=null;
ResultSet rs=null;
String driverName="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:myPetDBMS";

PET_DBMS_GUI2() throws SQLException{


lblId=new JLabel("ID: ");
lblName=new JLabel("Name: ");
lblAge=new JLabel("Age: ");
lblGender=new JLabel("Gender: ");
lblColor=new JLabel("Color: ");
txtId=new JTextField(10);
txtName=new JTextField(10);
txtAge=new JTextField(10);
txtColor=new JTextField(10);
cboGender=new JComboBox(gender);
txtSearch=new JTextField(20);
txtSearch.addKeyListener(this);

btnSave=new JButton("SAVE");
btnSave.addActionListener(this);
btnUpdate=new JButton("UPDATE");
btnUpdate.addActionListener(this);
btnDelete=new JButton("DELETE");
btnDelete.addActionListener(this);
btnClose=new JButton("CLOSE");
btnClose.addActionListener(this);
btnSearch=new JButton("Search");
btnSearch.addActionListener(this);
panelPet=new JPanel();
panelPet.setLayout(new GridLayout(8,2));
panelPet.setBorder(BorderFactory.createTitledBorder("Pet
Information"));
panelPet.add(lblId);
panelPet.add(txtId);
panelPet.add(lblName);
panelPet.add(txtName);
panelPet.add(lblGender);
panelPet.add(cboGender);
panelPet.add(lblAge);
panelPet.add(txtAge);
panelPet.add(lblColor);
panelPet.add(txtColor);
panelPet.add(btnSave);
panelPet.add(btnUpdate);
panelPet.add(btnDelete);
panelPet.add(btnClose);
SCP-PF103 | 249
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

panelPetTable=new JPanel();
panelPetTable.setLayout(null);

panelPetTable.setBorder(BorderFactory.createTitledBorder("Search
Pet"));

setLayout(new GridLayout(1,1));

petTable=new JTable();
petScrollPane=new JScrollPane(petTable);
panelPetTable.add(petScrollPane).setBounds(10, 50, 500, 500);
panelPetTable.add(txtSearch).setBounds(10, 20, 80, 20);
panelPetTable.add(btnSearch).setBounds(90,20,80,20);
petTable.addMouseListener(this);

add(panelPet);
add(panelPetTable);

dbConnect();

setTitle("Pet Information Management System");


pack();
setSize(900, 400);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
void dbConnect(){
try {
Class.forName(driverName);
dbConn=DriverManager.getConnection(url);
st=dbConn.createStatement();
JOptionPane.showMessageDialog(null,"Connected to
Database");
strQuery="select *from tbl_pet";
rs=st.executeQuery(strQuery);
//viewRecords(strQuery);
setNewRecordAndRefreshTable();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
}
void viewRecords(String SQLStatement) throws SQLException{
/**This method populate records to JTable automatically. With
the use of
* rs2xml.jar (java archive), it lessens and shortens the code
for doing so. You
SCP-PF103 | 250
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

* don't need vectors and loops to get columns and row.


* HOW?
* First, download the rs2xml.jar file.
* After having it downloaded, right click on your project.
* Then choose Build path > Add External Archives...
* find the rs2xml.jar file which you have just downloaded.
* Then, the code below...
*/
rs=st.executeQuery(SQLStatement);
petTable.setModel(DbUtils.resultSetToTableModel(rs));
}
void setNewRecordAndRefreshTable() throws SQLException{
/**This method will refresh table records once you insert new, update,
and delete.
* Furthermore,this will set ID fields automatically counts the records
from the
* database and increment by 1 to avoid duplication of ID value
since it is primarykey.
* Lastly, it will clear the fields and set for new value inputs once insert
new, * update, and delete is excuted. */
DefaultTableModel table=(DefaultTableModel)
petTable.getModel();
table.setRowCount(0);
viewRecords("select *from tbl_pet");
//If you want to auto generate the id use this. If not then comment the
next two statements
txtId.setEnabled(false);
txtId.setText((petTable.getModel().getRowCount()+1)+"");
txtName.setText("");
txtColor.setText("");
txtAge.setText("");
}
public static void main(String[] args) throws SQLException {
new PET_DBMS_GUI2();
}

public void actionPerformed(ActionEvent arg0) {


if(arg0.getSource().equals(btnSave)){
strQuery="insert into tbl_pet values("+ txtId.getText() +",'"+
txtName.getText() +"', '"+ cboGender.getSelectedItem() +"',"+
txtAge.getText() +",'"+ txtColor.getText() +"')";
//JOptionPane.showMessageDialog(null, strQuery);

try {
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null, "Records
Successfully Added");
setNewRecordAndRefreshTable();
} catch (SQLException e) {
SCP-PF103 | 251
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

e.printStackTrace();
}
}
else if(arg0.getSource().equals(btnUpdate)){
strQuery="update tbl_pet set pet_name='"+ txtName.getText() +"',
pet_gender='"+ cboGender.getSelectedItem() +"',pet_age="+
txtAge.getText() +",pet_color='"+ txtColor.getText() +"' where pet_id="+
txtId.getText() +"";
try {
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null, "Records
Successfullu Updated");
setNewRecordAndRefreshTable();
} catch (SQLException e) {
e.printStackTrace();
}
}
else if(arg0.getSource().equals(btnDelete)){
strQuery="delete *from tbl_pet where pet_id="+
txtId.getText() +"";
try {
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null, "Records
Successfully Deleted");
setNewRecordAndRefreshTable();
} catch (SQLException e) {
e.printStackTrace();
}
}
else if (arg0.getSource().equals(btnSearch)){
strQuery="select *from tbl_pet where pet_id="+
txtSearch.getText() +"";
try {
rs=st.executeQuery(strQuery);
while(rs.next()){
txtId.setText(rs.getInt("pet_id")+"");
txtName.setText(rs.getString("pet_name"));
txtAge.setText(rs.getString("pet_age"));

cboGender.setSelectedItem(rs.getString("pet_gender"));
txtColor.setText(rs.getString("pet_color"));
}
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null,
e1.getMessage());
}
}
else if(arg0.getSource().equals(btnClose)){ System.exit(0); }
}
SCP-PF103 | 252
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

void forSearchInTable(){
try {
strQuery="select *from tbl_pet where pet_id like '%"+
txtSearch.getText() +"%'";
rs=st.executeQuery(strQuery);
viewRecords(strQuery);
}catch (SQLException e1) {
}
}
public void keyPressed(KeyEvent arg0) {}
public void keyReleased(KeyEvent arg0) { forSearchInTable(); }
public void keyTyped(KeyEvent arg0) {}
public void mouseClicked(java.awt.event.MouseEvent arg0) {
int i=petTable.getSelectedRow();
txtId.setText(petTable.getModel().getValueAt(i, 0)+"");
txtName.setText(petTable.getModel().getValueAt(i, 1)+"");
cboGender.setSelectedItem(petTable.getModel().getValueAt(i,
2)+"");
txtAge.setText(petTable.getModel().getValueAt(i, 3)+"");
txtColor.setText(petTable.getModel().getValueAt(i, 4)+"");
}
public void mouseEntered(java.awt.event.MouseEvent arg0) {}
public void mouseExited(java.awt.event.MouseEvent arg0) {}
public void mousePressed(java.awt.event.MouseEvent arg0) {}
public void mouseReleased(java.awt.event.MouseEvent arg0) {}
}

NOTE : I recommend you to separate the Connection class to your Main


class.

The method below is equivalent of rs2xml.jar:

void showRecords(String SQLStatement) throws SQLException{


Vector petColumnNames=new Vector();
Vector data=new Vector();
Vector row=new Vector();
SQLStatement="select *from tbl_Pet";
rs=st.executeQuery(SQLStatement);
ResultSetMetaData md=rs.getMetaData();
int columns=md.getColumnCount();
for (int i = 1; i <= columns; i++) {
petColumnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
SCP-PF103 | 253
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

petTable=new JTable(data, petColumnNames);


petTable=new JTable();

}
rs.close();
st.close(); }

Ff

Search Indicator

SELF-SUPPORT: You can click the URL Search Indicator below to help you
further understand the lessons.

§ Goodrich, M., Tamassia, R. (2011). OOP Pronciples in Java. 5th


Edition, John & Wiley Sons Pte. Ltd.
§ https://www.tutorialspoint.com/java/java_stack_class.htm
§ https://www.callicoder.com/java-stack/
§ https://www.geeksforgeeks.org/stack-class-in-java/
§ https://www.cse.unr.edu/~sushil/class/cs202/notes/stacks/sta
cks.html
§ https://medium.com/@stevenpcurtis.sc/infix-postfix-prefix-and-
reverse-polish-notation-299affa57acf
§ https://www.onlinegdb.com/online_java_compiler

General Instructions:

1. Answer the activities in the succeeding pages.


2. Submit it in a .PDF format with a filename convention
<SURNAME>_<WEEK#> such that BASTE_WEEK16.
3. The deadline for submission will be five days after it was
discussed.
Learning Resources and Tools

1. Laboratory Manual or SCP


2. Ballpen
3. PC/Laptop
4. Internet
5. IDE (Eclipse, Netbeans, ect)

SCP-PF103 | 254
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

LET’S INITIATE!
Activity. Answer the following questions.

1. What is JDBC?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.
2. Why do you need to learn JDBC or database programming?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.
3. Why database programming is important in software development?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

LET’S INQUIRE!
Activity. Answer the following questions.

1. What is ODBC?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.

2. Give atleast 3 database servers you know?


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

SCP-PF103 | 255
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

___________________________________________________________________
_____________________.

LET’S INFER!
Activity. List down the components of JDBC and explain each.

SCP-PF103 | 256
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Week 17 Project making/Presentation


Lesson Title
Learning Presentation of projects created by the
Outcome(s) students as a final requirement
Time Frame

*** COURSE INFORMATION ***


1. Course Number : PF103
1. Course Name : OOP
2. Course Description : This course provides in-depth coverage of
object-oriented programming principles and techniques. Topics include
classes, abstraction data types, encapsulation, inheritance,
polymorphism, simple data and file structures, and program
development in a modular, object-oriented manner. Focus is on the
Object-Oriented language features, including data hiding and exception
handling.

_______________________________________________________________________
PROGRAM TITLE

Objectives:
ü To be able to apply the knowledge and skills in JAVA language
through a project-based program.
ü Be able to present new ideas, researches, and innovations regarding
the course subject.
ü To form a new challenges amongst student making them become more
aggressive in research and software development
ü Be able to improve self-confidence to the student through
presentation on the study conducted and being developed.
ü To be able to formulate new algorithm as a solution to a newly known
and identified problem.

Specification:

ü The student must design and create a simple system application of


TPS- transaction processing system and/or any system-based
development using the JAVA language.
o Transaction Processing System – Grading System, Airline
Reservation, Billing System, Hotel Reservation, Employee
Monitoring, Students Monitoring, Employee Attendance
Monitoring, Reservation System, Cashiering System, Order
Management System, Payroll System, Enrolment System, Sales
System, Inventory System, etc.

SCP-PF103 | 257
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

ü The project presentation will 1week before the Final Examination.


ü If a student will not be able to present during his schedule, then he
will not be accommodated until all proponents are done.
ü During the presentation, he/she must prepare/obtain the following:
o Hardcopy of documentation of the proposed study which
comprises with the following document structures in sequence:
§ Title and Cover page
§ Introduction
• Project Description
• Project Goals and Objectives
• List of Transactions
§ UML Design
§ Prototype
§ Curriculum Vitae
§ List of References {Books, websites, or a person}
o Documentation Format
§ Font (Arial, 12, 1.5 spacing)
§ Margin (1.5 left, 1 all the rests)
o Submit all necessary softcopy documents to your instructor with
a folder named after your Fullname (e.g. BASTE, MARTZEL).
o Actual program application of the designed project.

SCP-PF103 | 258
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

TECHNICAL WRITING EVALUATION FORM

Directions: Review the contents of your “Technical Writing Document” with the following requirements
specifications (NOTE: Rating on a scale of 2–5 where)

2 indicates Poor (PR)


3 indicates Fair (FR)
4 indicates Good(GD)
5 indicates Excellent (EXC)

BENCHMARKS PR FR GD EXC
2 3 4 5
1. Meets the intended purpose
2. is complete and meets all the requirements
3. is well organized
4. demonstrates concerted effort
5. illustrates appropriate level of quality
6. goes beyond minimum expectations
7. shows improvement
8. Follows the format for documentation(formatting and styles, spacing, margins, etc.)
9. Mastery. Able to explain about the study (like what is written in the document)
10. Ability to answer questions about the document
TOTAL
Comments and Suggestions:

SCP-PF103 | 259
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

UML EVALUATION FORM

Directions: Review the contents of your “UML” with the following requirements specifications (NOTE:
Rating on a scale of 2–5, where )

2 indicates Poor (PR)


3 indicates Fair (FR)
4 indicates Good(GD)
5 indicates Excellent (EXC)

BENCHMARKS PR FR GD EXC
2 3 4 5
APPROPRIATENESS. The UML class structure and design are appropriate for the project.
TRANSITION/CORRECTNESS. The UML class is easy to follow by clearly showing and
depicting correct symbols of classes and its relationships.
QUALITY AND ACCURACY OF INFORMATION. Attributes are very specific to process
and accurate which explicitly shows public and private members of the class.
NEATNESS. Excellent use of UML Class diagram format which are probable in a real-world
setting; not at all confusing.
COMPLETION. The UML Class diagram is complete.
TOTAL
Comments and Suggestions:

SCP-PF103 | 260
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

SOFTWARE SOLUTION RUBRICS

QUALITY / EXCEPTIONAL COMPETENT DEVELOPING (Needs BEGINNING


FEATURES (Exemplary) (Satisfactory) Improvement) (Fails to meet)
5 4 3 2
PRINCIPLES OF The student acquires The student acquires The student acquires The student is able to
excellent knowledge in the sufficient knowledge in the knowledge average in the describe the meanings of
OBJECT- principles of object- principles of object- principles of object- data encapsulation,
ORIENTED oriented languages, oriented languages, oriented languages, inheritance, and
PROGRAMMING namely, data namely, data namely, data polymorphism, and to
encapsulation, encapsulation, encapsulation, give simple examples on
inheritance, and inheritance, and inheritance, and them.
polymorphism. polymorphism. polymorphism.
The student is able to The student is able to The student is able to The student can apply
APPLYING extensively apply object- sufficiently apply object- apply object-oriented some object-oriented
OBJECT- oriented techniques to oriented techniques to techniques in some key techniques to write
ORIENTED write software applications write software applications elements of software software applications
TECHNIQUES TO with multiple classes, e.g., with multiple classes, e.g., applications with multiple with multiple classes,
SOFTWARE enforcing data hiding as enforcing data hiding via classes, e.g., enforcing e.g., enforcing data
PACKAGES much as possible via class class privacy. data hiding via class hiding via class privacy
privacy. privacy.
GRAPHICAL The student demonstrates The student demonstrates The student demonstrates The student
USER excellent know-how in considerable know-how in average know-how in demonstrates some
INTERFACES writing programs with writing programs with writing programs with know-how in writing
graphical user interfaces. graphical user interfaces. graphical user interfaces. programs with graphical
user interfaces.
EXCEPTION The student correctly The student correctly The student correctly The student correctly
HANDLING writes object-oriented writes object-oriented writes object-oriented writes object-oriented
programs with programs with programs with an average programs with some
complicated exception considerable exception amount of exception exception handling
handling facilities. handling facilities. handling facilities. facilities
FILE HANDLING File handling techniques File handling techniques File handling techniques File handling techniques
IMPLEMENTATIO are correctly implemented are appropriate for desired are appropriate for desired are not appropriate for
N aid to support operations and is operations but contains desired operations and
transactional queries such syntactically correct. some syntax errors. contains some syntax
as adding, updating, errors.
modifying and searching
of records.
DELIVERY The program was The program was The code was within 2 The code was more than
delivered on time. delivered within a week of weeks of the due date. 2 weeks overdue.
the due date.
ABILITY TO The proponent was able to The proponent was able to The proponent was able to The proponent was NOT
ANSWER QUERY answer quickly all queries answer quickly most answer quickly some able to answer quickly all
or questions towards the queries or questions queries or questions queries or questions
source code used in a towards the source code towards the source code towards the source code
program used in a program. used in a program. used in a program
Comments and Suggestions:

VERDICT:
[ ] ACCEPTED without Revision
[ ] ACCEPTED with Revision(s)
[ ] REDEFENSE, program/software output lacks the necessary features

SCP-PF103 | 261
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

STUDENT’S SPECIFIC SKILL EVALUATION CHECKLIST

BENCHMARKS/TARGET

GENERAL PROGRAM CHECKLIST YES NO


1. Utilized the use of comments for readability purposes
2. Follows naming convention in defining variables, methods, objects and classes
3. The codes are easy to debug, read and understand.
4. Able to identify the proper classes, methods and attributes to solve a particular problem (implementation level)
5. Able to create constructors as necessary for a class
6. Able to define accessor and mutator methods (getter & setter methods) as necessary for a class
7. Able to send an appropriate message/method call to an object based on the type of that object and the interface of
the corresponding method
8. Able to manipulate heterogeneous container of objects by sending appropriate polymorphic messages to each
of them
9. Able to pass correctly an object as a parameter in a message
10. Able to identify the proper level of access control (e.g private, public, protected) for the characteristics and
behaviors of a class.
11. Able to identify “is-a” relationships between several related classes and implement inheritance between these classes
correctly; these include super and sub-class, constructors, methods that should be inherited and their access
control.
12. Able to call a method inherited from the ancestors of the class in which the call is made
13. Able to appropriately define multiple related classes as opposed to defining a single class in solving the problem in
hand
14. Able to create aggregation relationships between related classes to correctly indicate whole-part relationship
between the concepts/entities represented by the classes.
15. Able to identify appropriately situations in which polymorphism can be applied
16. Able to set up correctly a group of objects which work together among themselves in carrying out a certain task (vs.
one object doing everything itself).
17. Can give reasons for the tools and techniques used in the production of an object oriented application
18. Can use terminology accurately in new contexts and able to express ideas in his own words
19. Can create and understand designs that differ from provided examples and apply a variety of design techniques
to his/her solution
20. proficient in the application of OO libraries, and application of error handling
EXAMINE BASIC PROGRAMMING CONSTRUCTS NYC CMP

21. Has deep understanding of datatypes and variables


22. Able to discriminate primitive and reference datatype
23. Knows and explain the rules in naming identifiers, variables (initialization and instantiation)
24. Distinguish between relational/equality and logical expressions
25. Knows the importance of conditions, relational and logical expressions in Programming
26. Has thorough understanding of if-else, switch, and looping constructs
27. Compare and contrast the different conditional constructs {one-way, two-way, multiple, nested}
28. Able to analyze which iteration technique is used in a certain program
29. Describe the importance of method in writing programs
30. Discriminate the difference between predefined and user-defined methods
31. Differentiate actual and formal parameters
32. Able to define and expound different constructs or kinds of methods {void and return-type methods}
33. Has exceptional understanding of the importance of an Array to its declaration and initialization
34. Has explicit knowledge of storing, manipulating, processing, and removing data/values through array
implementation.
35. Describe how an array differs to Vector, ArrayList, and other list techniques
CLASS DESIGN AND IMPLEMENTATION NYC CMP

36. Knows how to design UML diagram and able to explain its importance in program development
37. Discriminate user-defined and pre-defined classes
38. Can name powerful built-in or predefined class
39. Can define class and its two basic important components : fields and methods
40. Has a clear understanding of local and global variables, class and object implementations
DATA ABSTRACTION (ADTs) NYC CMP

41. Explain the importance of creating and implementing ADT(Abstract Datatype)


42. Demonstrate understanding of 4 ADT operations: Creators, Observers, Transformers, Input/Output
43. Has an adequate learning of how Encapsulation and ADT differ each other
44. Has a distinct knowledge of how an Array and Class, ADT create powerful program technique
45. Knows how to implement a class using an Array object
ENCAPSULATION NYC CMP

46. Can define and explain the importance of Encapsulation


47. Able to describe each component of a class Encapsulated (property and behavior)
48. Evaluate the difference between private, public, and protected modifiers of a class
49. Able to recommend the use of static and non-static field members of a class
50. Has sufficient understanding of the importance of a constructor
51. Able to name different types of constructors and explain each
52. Explain the idea of mutators(setters) and accessors (getters) of a certain class
53. Able to create single or multiple instance of an encapsulated class
54. Knows how to call or access the property and behavior of a class using an Object and a Class itself
55. Has deeper understanding of how instance variables and class variables are created

SCP-PF103 | 262
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

56. Has explicit understanding about the concept of code-reuse and code-recycle through derivation
57. Able to describe how an is-A relationship works and purpose of extends keyword in such concept
58. Has sufficient knowledge of the underlying terms which are superclass and subclass {Parent and child, based and derived
class}
59. Able to describe each of the Inheritance type and its hierarchy (i.e. single, hierarchical, multiple, etc.)
60. Knowledgeable in extending other user-defined and built-in classes
POLYMORPHISM

61. Has explicit knowledge in Polymorphism as an OOP concept


62. Can explain the difference between method overriding and method overloading
63. Able to expound the ideas of the important terms as follows: Static Binding versus Dynamic Binding, Compile time versus Runtime Polymorphism
64. Able to explain the key terms extends and super, and instanceOf
65. Knows the idea of typecasting : upcasting and down casting an instance of a class
COMPOSITION and other RELATIONSHIP (has-A and etc)

66. Able to name other relationship types {Association,Generalization,Realization,Dependency,Aggregation,Composition}


67. Can explain and able to write how multiple classes defined in a program and create relationships with each other
68. Able to expound the difference of composition from inheritance
69. How “is-a” and “has-a” relationship differ from each other
70. Evaluate as to how and when Inheritance and Composition should be used necessary to a certain program
WINDOWS PROGRAMMING AND EVENT HANDLING

71. Can name different components containing in java swing components


72. Able to apply swing components , lay-outing in designing the application properly
73. Knowledgeable in applying how OOP underlying concepts successfully applied to each of these swing component
74. Able to create and implement an event to a certain swing component
75. Has sufficient knowledge in designing GUI through a wide and healthy collections of Objects in java
HANDLING EXCEPTION TECHNIQUES

76. Can define and explain the importance of handling exception in java
77. Apply different exception-handling techniques : terminate the program, fix error and continue, log error and continue
78. Can name a few of java exception classes and its functions and purpose
79. Know the difference between throw and throws
80. Has capability of creating own exception-handling technique and able to apply it in the project
FILE HANDLING TECHNIQUES

81. The use of file or database is fully implemented in maintaining the data
82. Able to create multiple text files for data organization and record keeping
83. Has exceptional knowledge regarding how to properly handle files to keep all the records secure, stable, consistent, and well-
managed
84. Knows when to use File, FileReader, and FileWriter classes in the program
85. Create multiple file structure which are logically related to enforce data integrity and security of the data

NOTE : Student is given up to 3 attempts ONLY to accomplish the said Skill Sets. Student
is deducted 10points starting/during 2nd attempt and another 10points during 3rd attempt.

DATE OF ATTEMPTS REMARKS


ASSESSMENT SUMMARY {Mark how many competent per attempt} {CHECK IF COMPLETED}
1ST 2ND 3RD
GENERAL PROGRAM 20
CHECKLIST
EXAMINE BASIC 15
PROGRAMMING CONSTRUCTS
CLASS DESIGN AND 5
IMPLEMENTATION
DATA ABSTRACTION (ADTs) 5
ENCAPSULATION 10
INHERITANCE : is-A 5
POLYMORPHISM 5
COMPOSITION and other 5
RELATIONSHIP (has-A and etc)
WINDOWS PROGRAMMING 5
AND EVENT HANDLING
HANDLING EXCEPTION 5
TECHNIQUES
FILE HANDLING TECHNIQUES 5
TOTAL 85

SCP-PF103 | 263
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

CODE WRITING
Description Source Code
Create a class with name
‘Employee’

private field members : emp_id,


name, birthdate, age, position,
ratePerHour,hoursWorked,
GrossPay,NetPay.

Create default constructor and


initialize each field member.

Create parameterized
constructor with emp_id and
hoursWorked as arguments or
parameters. Then, write a
statement it sets the value.

Create setters and getters for


each member except grossPay
and netPay.

Create a method ‘calculateWage’


which takes one argument
hoursWorked and then calculate
GrossPay and NetPay.

Create getter for GrossPay and


NetPay.

Create an overloaded method for


calculatePay with two
arguments; emp_id,
hoursWorked. Do the same
calculation.

Create another class with main


method and implement an
instantiation of the Employee
class.

Set employee information:

name, position, rateperhour.

Call the method which calculates


the wages of certain employee
based on id.

Create a class ‘Parttime’ and


inherits the Employee class.

SCP-PF103 | 264
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

“Automated DTR with Payroll System for Penong’s Barbecue


Seafood’s and Grill Restaurant”

In Partial fulfilment of the requirements in


PF103: Object Oriented Programming

Presented by:

MARTZEL P. BASTE, BSCS 2nd

Presented to:
PROF. ALBERT EINSTEIN

September, 2021

SCP-PF103 | 265
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

INTRODUCTION

Background of the Study

Payroll is one of the most sensitive functions of the accounting and


human resource departments. While other software systems affect only the
group involve in that function, payroll directly affects the lives of all
employees of the entire organization. Almost a mission-critical application
enable Payroll assures management of a more accurate and timely delivery
of information while changes mandated by government and business
peculiarities are easily implemented.
Globally, in UK particularly in Kentucky Fried Chicken(KFC) began
deploying Optimii in March 2008, with the aim of rolling the solution out
across 120 head office users as well as 30 area managers and four regional.
Moving to Optimii means saying goodbye to an Access database designed
in the late 1990’s. “If the general ledger or cost centre codes changed, it was
a major headache”, explains Paul Grant, Project Manager in KFC’s IT team.
Normal operation of the old system was also cumbersome, slow and risk-
laden. Now the whole process is electronic from end to end. Submitted
expenses are flagged for approvers’ attention the following day. On
approval, the submissions flow to the payroll team who perform receipt
reconciliation, apply the company’s business rules for payment and check
the VAT (Value added tax) elements. Payments are currently made on a
fortnightly basis, though Optimii allows a full flexibility over payment
scheduling. (http://www.outerin.com)
Locally, in Davao City, specifically in Penong’s Barbecue Seafoods and
Grill Restaurant located in Illustre St. as their main branch, is using a
Bundy clock for their Daily Time Record. But in terms of calculating
deductions down to the process of generating employees’ salary, they are
using manual procedures. To mention a few, in counting the days of work
of an employee through their attendance sheet they will transfer it manually
through Microsoft Excel Application for accomplishing necessary
calculations. Hence, it takes a lot of time and effort before a specific
transaction is completed, and it is affecting other proceeding transactions
SCP-PF103 | 266
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

which causes delay in generating pertinent reports. Furthermore, records


management are less secured since it is kept in the filing cabinets where
anyone can possibly access and may alter records which can be
troublesome for the company.
Therefore, because of these predicaments and discernible problems,
the researcher decided to make a proposal entitled Automated Daily Time
Record and Payroll System for Penong’s Barbecue Seafoods and Grill
Restaurant in order to overcome the problems experienced in the said
restaurant.
Statement of Goals and Objectives
This project is entitled Automated DTR with Payroll System for
Penong’s Barbecue Seafood’s and Grill Restaurant. The said project is
a stand-alone desktop application which will be created with the help of
JAVA language and more secured database through the advantage of file
management. This provides an environment which help to computerize the
data processing and management of time-keeping and payroll transactions.
Further, the proposed system is developed using the tools, which are most
suited for development of the Application Package. These tools are as
follows:
1. JAVA –JRE 1.7 - is the java language package
2. Eclipse IDE - an environment to run java language
3. Text File - a database management system to securely
keep and maintain the records.

The study specifically aims to:

Ø Create an Automated Daily Time Record is one of the goals that the
researcher should provide to the company as a solution to avoid the
overlapping of records. In this case, there will be no more unclear
records to be output because with just an ID number to be encoded
in the computerized DTR form and a click of a button, an employee
will automatically log-in or log-out based on the current date and time.

SCP-PF103 | 267
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

Ø Provide an automated Payroll system capable of securing employees’


record through a username and a password. No more one-fourth-sized
attendance sheet that may accidentally lost since all the information
are securely stored in the system. Further, only the Administrator can
access the system in order to avoid change in the transaction.

Ø Create an automated Daily Time Record which is connected to the


Payroll system. So every time a particular employee logs-in and logs-
out, the record will directly reflect to the database which includes
records of deductions, allowances and charges making it easy to the
part of the Accounting clerk to compute employees’ salary with just
one click of a button.

UML Class Diagram


The diagram below shows how each of the class in the proposed study
create logical relationship with each other. (sample only)

SCP-PF103 | 268
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

System Prototyping

This project includes the following modules for development of the

project. These are as follows: -

Show and discuss the form. Its functions and other controls
used in the form

1. SPLASH CLASS.

This is a first form that displays the welcome screen for the user
and also shows the information of developer or version etc.
2. LOGIN CLASS

This form shows the Login name and password when user enter a
valid user name and password then he/she can operate the
application.

3. MAIN CLASS

This form is a menu-based form that displays the menu for


operation of the application. It includes various options for staff,
student, fees and report related option.
4. STUDENT CLASS

This form provides the option to add, modify, delete or find the
information of a student who seeks the admission in the school.
5. STAFF CLASS

This forms provides the option to add, delete, search and delete the
information of staff (either teaching or non-teaching) that is
working in the school.
6. FEE CLASS

This form provides the option to the user of the system to add,
delete, modify and search the information of the fee deposited by
the student.
SCP-PF103 | 269
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

7. RESULT CLASS
This form displays the options for the user to add, delete and modify
the details of student related to the marks.
8. REPORT CLASS

With the help of this option from menu user of the system can see
or take the print out of various reports provided by the system.
9. GOODBYE CLASS

This form is activating when user select the exit option from menu
or close the application. This form shows the good-bye message to
the user and also say thanks to the user for using this application

SCP-PF103 | 270
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

CURRICULUM VITAE (Sample only)

SCP-PF103 | 271
ST. JOHN PAUL II COLLEGE OF DAVAO

COLLEGE OF INFORMATION AND


COMMUNICATION TECHNOLOGY
Physically Detached Yet Academically Attached

REFERENCES

SCP-PF103 | 272

You might also like