Professional Documents
Culture Documents
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.
Course Map
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)
Week 4 Methods and Linear Searching Week 10 Intro to GUI Components Week 16 JDBC: Basic Database in Java
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
• Primitive Datatypes – are the basic types of data: byte , short , int
, long , float , double , boolean , char. It stores the actual values.
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:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Variable Types
SCP-PF103 | 3
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
Arithmetic Operators
Logical Operators
Relational Operators
SCP-PF103 | 5
ST. JOHN PAUL II COLLEGE OF DAVAO
The if statement
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
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
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
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
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."
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
int time =20;
if (time <
18){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
To
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
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)
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 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
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:
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
SCP-PF103 | 10
ST. JOHN PAUL II COLLEGE OF DAVAO
Your Output:
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.
Your Output:
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
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
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
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 Output:
SCP-PF103 | 13
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
I
LEARNING NTENT!
Terms to Ponder
SCP-PF103 | 15
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
SCP-PF103 | 16
ST. JOHN PAUL II COLLEGE OF DAVAO
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
SCP-PF103 | 17
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
while(boolean condition) {
//statements;
}
If you are still confused about the working flow of the while loop, refer
to the flowchart below.
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
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
Syntax
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
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.
SCP-PF103 | 21
ST. JOHN PAUL II COLLEGE OF DAVAO
know your own IDE’s shortcut to stop live execution of a program incase
you have the unfortunate incident of java infinite loop.
Example
This example jumps out of the loop when i is equal to 4:
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
General Instructions:
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 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
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 Output:
SCP-PF103 | 24
ST. JOHN PAUL II COLLEGE OF DAVAO
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 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
Your Output:
Expected Output:
Your Output:
SCP-PF103 | 26
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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.
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.
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.
SCP-PF103 | 28
ST. JOHN PAUL II COLLEGE OF DAVAO
Essential Content
Types of Array
ü One-dimensional
ü Multidimensional
ü Ragged Array
1D Array: Initialization
SCP-PF103 | 29
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
records from it. That is one of the advantage of an array from other simple
variables which are discussed previously.
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.
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
2D Array : Declaration
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.
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.
SCP-PF103 | 32
ST. JOHN PAUL II COLLEGE OF DAVAO
Output:
Ragged Arrays
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:
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
the information of all the students, the program has to display the list of
GPAs.
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:
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
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.
Your output:
Next, is identify the lowest and highest value amongst all integers entered.
Assume that you have this input/output:
The lowest is 2
The highest is 69
SCP-PF103 | 36
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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":
SCP-PF103 | 37
ST. JOHN PAUL II COLLEGE OF DAVAO
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 output:
And this is how many they sold in 5 days. And this is how they
recorded it:
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 output:
SCP-PF103 | 39
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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.
Parameter is any argument inside a method heading and during a method call.
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-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
Essential Content
Types of Method
Syntax:
Example:
SCP-PF103 | 42
ST. JOHN PAUL II COLLEGE OF DAVAO
Output:
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
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
Output:
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.
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
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 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
Output:
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
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:
• 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
Output:
Output:
SCP-PF103 | 49
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
SCP-PF103 | 50
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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 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
Your output:
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
Your output:
Your output:
SCP-PF103 | 54
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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.
Constructors of ArrayList
Constructor Description
SCP-PF103 | 56
ST. JOHN PAUL II COLLEGE OF DAVAO
SN Constructor Description
Essential Content
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
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:
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.
SCP-PF103 | 58
ST. JOHN PAUL II COLLEGE OF DAVAO
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”);.
- Explain how you perceive the above codes from Line 9 through Line
19.
SCP-PF103 | 59
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
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?
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)?
petList.add("Toothless");
petList.add(3,"Jerry");
JOptionPane.showMessageDialog(null, petList);
Observation 6:
Explain how do you understand
petList.add("Toothless"); ?
JOptionPane.showMessageDialog(null,petList);
What is the display?
SCP-PF103 | 61
ST. JOHN PAUL II COLLEGE OF DAVAO
8. If you add this petList.add(0, "Tom");after Line 23. What is the new
sequence of elements in the petList?
Observation 7:
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
11. So that is how it should be. I wish you all the best in coding.
Here’s the complete program for this activity.
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.
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
LET’S INITIATE!
Activity 1. Answer the following questions.
2. List down here your observations about the major differences of ArrayList
and Vector?
ArrayList Vector
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.
SCP-PF103 | 65
ST. JOHN PAUL II COLLEGE OF DAVAO
Output:
SCP-PF103 | 66
ST. JOHN PAUL II COLLEGE OF DAVAO
Output:
Output:
SCP-PF103 | 67
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INFER!
NOTE: Include your name in all of your outputs.
Note that the program should not terminate while T is not chosen.
Your output
SCP-PF103 | 68
ST. JOHN PAUL II COLLEGE OF DAVAO
Your output
SCP-PF103 | 69
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
SCP-PF103 | 71
ST. JOHN PAUL II COLLEGE OF DAVAO
Essential Content
Advantages of OOP
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.
SCP-PF103 | 72
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
• 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.
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
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.
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
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.
All created classes in java has inherited the Object superclass by default.
SCP-PF103 | 75
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
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
SCP-PF103 | 77
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
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
SCP-PF103 | 79
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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:
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
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
For example, we are hiding the name and dob attributes of person class
in the below code snippet.
SCP-PF103 | 82
ST. JOHN PAUL II COLLEGE OF DAVAO
SCP-PF103 | 83
ST. JOHN PAUL II COLLEGE OF DAVAO
Project Scope/Specifications
SCP-PF103 | 84
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
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
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
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
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
UML:
SCP-PF103 | 89
ST. JOHN PAUL II COLLEGE OF DAVAO
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
SCP-PF103 | 90
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
SCP-PF103 | 92
ST. JOHN PAUL II COLLEGE OF DAVAO
Essential Content
SCP-PF103 | 93
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
SCP-PF103 | 95
ST. JOHN PAUL II COLLEGE OF DAVAO
NOTE: In java, is a good practice to name a method for setter and getter
with set and get prefixes respectively.
• 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.
SCP-PF103 | 97
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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:
Similarly, Anna’s average was NOT calculated too because we did not call
the setAverage method. Unless you will write it after Line 19.
SCP-PF103 | 99
ST. JOHN PAUL II COLLEGE OF DAVAO
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");
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
Output:
SCP-PF103 | 101
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
}
//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; }
//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
int i=0;
String name, course;
int id;
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
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"));
}
}
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.
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
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
Definition:
UML (Class) Implementation. Out of the UML provide above this is the
Encapsulated class for WaterTank.
SCP-PF103 | 106
ST. JOHN PAUL II COLLEGE OF DAVAO
SCP-PF103 | 107
ST. JOHN PAUL II COLLEGE OF DAVAO
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
Encapsulated Class
Tester Class
Tester Class
SCP-PF103 | 109
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
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
Essential Content
Class Animal
{
// eat() method
// sleep() method
}
class Dog extends Animal
{
// bark() method
}
is-a relationship
Inheritance is an is-a relationship. We use inheritance only if an is-
a relationship is present between the two classes.
class Animal {
}
}
class Main {
public static void main(String[] args) {
dog1.eat();
dog1.sleep();
dog1.bark();
}
}
Output
I can eat
I can sleep
I can bark
protected Keyword
We learned about private and public access modifiers in previous
tutorials.
You can also assign methods and fields protected. Protected members
are accessible.
class Animal {
protected String type;
private String color;
class Main {
public static void main(String[] args) {
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).
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,
class Animal {
protected String type = "animal";
@Override
public void eat() {
System.out.println("I eat dog food");
}
class Main {
public static void main(String[] args) {
Output
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.
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
class Animal {
public Animal() {
System.out.println("I am an Animal");
}
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
SCP-PF103 | 117
ST. JOHN PAUL II COLLEGE OF DAVAO
Note the difference in the use of super while calling constructor and
method.
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{}
HAS-A Relationship:
SCP-PF103 | 118
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
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
Java Polymorphism
That is, the same entity (method or operator or object) can perform
different operations in different scenarios.
class Polygon {
// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}
// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}
SCP-PF103 | 121
ST. JOHN PAUL II COLLEGE OF DAVAO
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...
Why Polymorphism?
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.
1. Method Overriding
2. Method Overloading
3. Operator Overloading
SCP-PF103 | 122
ST. JOHN PAUL II COLLEGE OF DAVAO
In this case, the same method will perform one operation in the
superclass and another operation in the subclass. For example,
class Language {
public void displayInfo() {
System.out.println("Common English Language");
}
}
Output:
SCP-PF103 | 123
ST. JOHN PAUL II COLLEGE OF DAVAO
In a Java class, we can create methods with the same name if they differ
in parameters. For example,
This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.
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
Output:
**********
##########
In the above example, we have created a class named Pattern. The class
contains a method named display() that is overloaded.
SCP-PF103 | 125
ST. JOHN PAUL II COLLEGE OF DAVAO
int a = 5;
int b = 6;
// + with numbers
int sum = a + b; // Output = 11
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
pl.display();
}
}
Output:
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.
SCP-PF103 | 127
ST. JOHN PAUL II COLLEGE OF DAVAO
class Animal {
}
class Main {
public static void main(String[] args) {
Animal a1 = new Animal();
Dog d1 = (Dog)a1; // Downcasting
d1.displayInfo();
}
}
To resolve this problem we can use the instanceof operator. Here's how
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
}
}
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
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
LET’S INITIATE!
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.
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
______________________________________.
LET’S INQUIRE!
SCP-PF103 | 130
ST. JOHN PAUL II COLLEGE OF DAVAO
SCP-PF103 | 131
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INFER!
Program Design. Create a class Person and copy the codes below:
SCP-PF103 | 132
ST. JOHN PAUL II COLLEGE OF DAVAO
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:
2. Multilevel Inheritance.
3. Hierarchical Inheritance.
SCP-PF103 | 133
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
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
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.
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.
SCP-PF103 | 136
ST. JOHN PAUL II COLLEGE OF DAVAO
The methods of Component class are widely used in java swing that are
given below.
Method Description
SCP-PF103 | 137
ST. JOHN PAUL II COLLEGE OF DAVAO
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
SCP-PF103 | 138
ST. JOHN PAUL II COLLEGE OF DAVAO
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).
ü Title
ü Dimensions
ü Visibility
ü Default close operation,
This is the
display output.
- 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:
JFrame.DISPOSE_ON_CLOSE, JFrame.HIDE_ON_CLOSE,
JFrame.DO_NOTHING_ON_CLOSE
- 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
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.
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
SCP-PF103 | 141
ST. JOHN PAUL II COLLEGE OF DAVAO
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:
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
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.
2. Child
3. Parent
4. extends
5. Constructor
2. Setter
3. Getter
SCP-PF103 | 143
ST. JOHN PAUL II COLLEGE OF DAVAO
Recall that there are 3 ways on how to create GUI in java. Below are as
follows:
- Create a class GUISum. Debug the following by writing the right program in the
next column.
Import java.Swing.uti.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
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
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
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:
- 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
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
SCP-PF103 | 148
ST. JOHN PAUL II COLLEGE OF DAVAO
ü 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:
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.
Well you can try setBounds(int arg0, int arg1, int arg2, int arg3).
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.
NOTE: We will discuss further about Layout Managers in the next chapters. For
now, let us have the basic.
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
- 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
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!
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
T
H
I
S
Special NOTE to Programmers: Always remember that all java swing components
treat all input values as String object or an Object itself.
Try these:
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?
SCP-PF103 | 152
ST. JOHN PAUL II COLLEGE OF DAVAO
num1=___________________________________________________________________.
num2=___________________________________________________________________.
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
LET’S INFER!
Setting up
your Window
Your main
Class
SCP-PF103 | 154
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
The borderlayout arranges the components to fit in the five regions: east,
west, north, south and center.
SCP-PF103 | 156
ST. JOHN PAUL II COLLEGE OF DAVAO
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 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.
Data Fields
SCP-PF103 | 157
ST. JOHN PAUL II COLLEGE OF DAVAO
Constructors
Sample:
Output:
SCP-PF103 | 158
ST. JOHN PAUL II COLLEGE OF DAVAO
GridLayout
Constructors
Sample:
Output:
SCP-PF103 | 159
ST. JOHN PAUL II COLLEGE OF DAVAO
BorderLayout
Constructors
Sample
Output:
SCP-PF103 | 160
ST. JOHN PAUL II COLLEGE OF DAVAO
BoxLayout
Data Fields
Sample:
Output:
SCP-PF103 | 161
ST. JOHN PAUL II COLLEGE OF DAVAO
Sample:
Output:
CardLayout
SCP-PF103 | 162
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
SCP-PF103 | 163
ST. JOHN PAUL II COLLEGE OF DAVAO
GridBagLayout
Data Fields
SCP-PF103 | 164
ST. JOHN PAUL II COLLEGE OF DAVAO
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
Output:
GroupLayout
SCP-PF103 | 166
ST. JOHN PAUL II COLLEGE OF DAVAO
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
Sample:
Output:
SCP-PF103 | 168
ST. JOHN PAUL II COLLEGE OF DAVAO
Sample:
Output:
SpringLayout
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
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
Sample:
Output:
ScrollPaneLayout
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
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
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.
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
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
Output:
SCP-PF103 | 175
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INFER!
GUI Design. Design the prototype as shown below:
SCP-PF103 | 176
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
Essential Content
Java Swing
Features of Swing
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
Features of JFC
SCP-PF103 | 179
ST. JOHN PAUL II COLLEGE OF DAVAO
SCP-PF103 | 180
ST. JOHN PAUL II COLLEGE OF DAVAO
Output:
SCP-PF103 | 181
ST. JOHN PAUL II COLLEGE OF DAVAO
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:
SCP-PF103 | 182
ST. JOHN PAUL II COLLEGE OF DAVAO
JButton
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
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
SCP-PF103 | 184
ST. JOHN PAUL II COLLEGE OF DAVAO
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
SCP-PF103 | 185
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
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
SCP-PF103 | 189
ST. JOHN PAUL II COLLEGE OF DAVAO
Output:
SCP-PF103 | 190
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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
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
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.
LET’S INITIATE!
Activity. Answer the following questions.
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
LET’S INFER!
GUI Design. Create a simple student registration form. Below is a
sample design perspective:
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
Essential Content
JTable
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
}
public static void main(String[] args) {
new StableDemo1();
}
}
JscrollBar
Declaration
SCP-PF103 | 197
ST. JOHN PAUL II COLLEGE OF DAVAO
Example:
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
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
menu_f.setSize(500,500);
menu_f.setLayout(null);
menu_f.setVisible(true);
}
public static void main(String args[])
{
new SMenuDemo1();
}
}
JPopupMenu
Declaration
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
JcheckBoxMenuItem
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;
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
JSeparator
Declaration
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
{
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
Declaration
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
JTree
Declaration
1. JTree()
2. JTree(Object[] value)
3. JTree(TreeNode root)
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
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
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.
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
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
Output:
SCP-PF103 | 211
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INFER!
GUI Design. Design the prototype as shown below:
SCP-PF103 | 212
ST. JOHN PAUL II COLLEGE OF DAVAO
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
At SJPIICD, I Matter!
LEARNING INTENT!
Terms to Ponder
Abstract Class
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.
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
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.
Woof
Rules
A class derived from the abstract class must implement all those methods
that are declared as abstract in the parent 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.
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
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.
System.out.println("Hello");
}
abstract public void anotherMethod();
}
public class Demo extends AbstractDemo{
Key Points:
SCP-PF103 | 217
ST. JOHN PAUL II COLLEGE OF DAVAO
Note: The class which is extending abstract class must override all the
abstract methods.
Interface
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
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:
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
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
{
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 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
Nested interfaces
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
5) Class that implements any interface must implement all the methods
of that interface, else the class should be declared abstract.
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.
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.
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
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();
}
}
}
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
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.
General Instructions:
SCP-PF103 | 224
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INITIATE!
Activity. Answer the following questions.
SCP-PF103 | 225
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INQUIRE!
Activity. Answer the following questions.
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
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
Essential Content
SCP-PF103 | 227
ST. JOHN PAUL II COLLEGE OF DAVAO
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
SCP-PF103 | 228
ST. JOHN PAUL II COLLEGE OF DAVAO
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
1) Checked Exception
2) Unchecked Exception
3) Error
SCP-PF103 | 229
ST. JOHN PAUL II COLLEGE OF DAVAO
Keyword Description
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
SCP-PF103 | 230
ST. JOHN PAUL II COLLEGE OF DAVAO
There are given some scenarios where unchecked exceptions may occur.
They are as follows:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Search Indicator
SELF-SUPPORT: You can click the URL Search Indicator below to help you
further understand the lessons.
§ 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:
LET’S INITIATE!
Activity. Answer the following questions.
SCP-PF103 | 232
ST. JOHN PAUL II COLLEGE OF DAVAO
LET’S INQUIRE!
Activity. Answer the following questions.
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
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
Essential Content
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
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.
Creating a Database
SCP-PF103 | 235
ST. JOHN PAUL II COLLEGE OF DAVAO
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.
SCP-PF103 | 236
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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:
What we need?
• Connection
• DriverManager
• Statement
• ResultSet
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
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
Code Description
SCP-PF103 | 239
ST. JOHN PAUL II COLLEGE OF DAVAO
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:
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();
Code Description:
Ofcourse the first five statements are known to you. Let us get the
next alien statement,
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.
§ ("+ 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.
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
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 +"";
§ 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.
SCP-PF103 | 243
ST. JOHN PAUL II COLLEGE OF DAVAO
P_id=3;
strQuery="Delete from tbl_Pet where Pet_Id="+ P_id+"";
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null,"Records successfully
deleted");
Code Description:
To delete all the rows from the employee table, the query
would be like,
System.out.print(rs.getString("Pet_Color")+"\t");
System.out.println();
}
Step 17: Congratulations! You made it right Programmers.
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
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
import java.sql.*;
import javax.swing.JOptionPane;
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();
}
}
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;
String strQuery="";
Connection dbConn;
Statement st=null;
ResultSet rs=null;
String driverName="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:myPetDBMS";
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
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();
try {
st.executeUpdate(strQuery);
JOptionPane.showMessageDialog(null, "Records
Successfully Added");
setNewRecordAndRefreshTable();
} catch (SQLException e) {
SCP-PF103 | 251
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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) {}
}
}
rs.close();
st.close(); }
Ff
Search Indicator
SELF-SUPPORT: You can click the URL Search Indicator below to help you
further understand the lessons.
General Instructions:
SCP-PF103 | 254
ST. JOHN PAUL II COLLEGE OF DAVAO
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?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
_____________________.
SCP-PF103 | 255
ST. JOHN PAUL II COLLEGE OF DAVAO
___________________________________________________________________
_____________________.
LET’S INFER!
Activity. List down the components of JDBC and explain each.
SCP-PF103 | 256
ST. JOHN PAUL II COLLEGE OF DAVAO
_______________________________________________________________________
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:
SCP-PF103 | 257
ST. JOHN PAUL II COLLEGE OF DAVAO
SCP-PF103 | 258
ST. JOHN PAUL II COLLEGE OF DAVAO
Directions: Review the contents of your “Technical Writing Document” with the following requirements
specifications (NOTE: Rating on a scale of 2–5 where)
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
Directions: Review the contents of your “UML” with the following requirements specifications (NOTE:
Rating on a scale of 2–5, where )
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
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
BENCHMARKS/TARGET
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
SCP-PF103 | 262
ST. JOHN PAUL II COLLEGE OF DAVAO
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
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.
SCP-PF103 | 263
ST. JOHN PAUL II COLLEGE OF DAVAO
CODE WRITING
Description Source Code
Create a class with name
‘Employee’
Create parameterized
constructor with emp_id and
hoursWorked as arguments or
parameters. Then, write a
statement it sets the value.
SCP-PF103 | 264
ST. JOHN PAUL II COLLEGE OF DAVAO
Presented by:
Presented to:
PROF. ALBERT EINSTEIN
September, 2021
SCP-PF103 | 265
ST. JOHN PAUL II COLLEGE OF DAVAO
INTRODUCTION
Ø 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
SCP-PF103 | 268
ST. JOHN PAUL II COLLEGE OF DAVAO
System Prototyping
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 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
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
SCP-PF103 | 271
ST. JOHN PAUL II COLLEGE OF DAVAO
REFERENCES
SCP-PF103 | 272