CIT 207 MODULE v2
CIT 207 MODULE v2
CIT 207 MODULE v2
The learning outcomes for CIT 207, specified below are unpacked by the specific
objectives of each lessons. Generally, at the end of this module, you would have:
1. Compared and contrasted procedural/functional approach to the
object-oriented programming approach
2. Designed, implemented, tested and debugged programs using OOP concepts.
It is also part of my objectives that by the end of this semester, you will be able to
create a simple Java Application that involves different frames and a database
connection or at least be familiar with different applications that you can create using
the Java Language. Since, developing a system or software is part of your
course as an IT.
Apply your knowledge. In this part, you will practice what you have
learned.
Assess your knowledge. You will be tested here and you will be able to
know the gaps in your understanding in this lesson. If you are not satisfied
with the feedback, you may then go back to some point that you may have
missed.
References. List down the resources and links from which the content of
the lesson was based from. These may take the form of books, internet
sites, blogs, videos, photographs, animation, PowerPoint Presentations,
icons, etc.
Directions are found inside each lesson that will tell you how long you are going to
work on this module. All formative activities must be answered and counter-checked
with the feedback attached. Honesty is a school policy. Be serious about the learning
activities you are working on. It will define who you are and what you will become in
the future. Pre-test and post-test must be completed as well. At the end of the
semester or as instructed otherwise, you are to submit this module to your subject
professor. Inquiries on some points not fully understood will be made online via Google
Classroom in a scheduled encounter. This module is a self-contained learning kit with
instructions that will guide you to the end.
I will provide additional lecture notes and video tutorial which will be posted on
the Google Classroom.
The following are my personal contact information just in case you needed to
contact me immediately:
Mobile Number: 0921-718-4865
E-mail Address: [email protected]
Facebook Account: (name) Grace Lhyn Legaste |
(link) https://www.facebook.com/gracelhyn.legaste/
You are now ready to begin. Happy learning and happy coding.
Unit 1: Review of the Basic Concepts of
Java
Objectives:
At the end of the unit, the student must have:
a. discussed the objectives of Object Oriented in Programming; and
b. explain the java program structure.
How much do you know?
Declare and initialize a variable with the following value (observe proper syntax):
34.56 _____________________________________________
OOP _____________________________________________
-12 _____________________________________________
B _____________________________________________
Hello _____________________________________________
921718486500 _____________________________________________
Acquire new knowledge
Lesson Proper
With that example in mind, the label on the basket is the variable name, the type
of fruit is the data type, and the amount of fruits inside is the value. The number of
fruits in each basket can changed but you can’t change the type of fruit that you
should put in each basket.
In context, variable is a name which can be associated with a value that
can be changed.
Syntax to:
declare a variable: dataType variableName;
Initialize a variable: variableName = value;
Declare and Initialize a variable: dataType variableName = value;
Example:
declare a variable: int age;
Initialize a variable: age = 35;
Declare and Initialize a variable: int age = 35;
Things to remember in naming a variable:
Variables should ALWAYS starts with a letter, underscore or dollar sign. BUT
NOT A NUMBER. Number can only used after a character. (by java standards
it should start with a lowercase letter but if it’s composed of 2 words you can
capitalize the second word)
√ num1 or firstNumber × 1num or 1stNum
Spaces are NOT ALLOWED.
√ total area × total_area or totalArea
Java is very case-sensitive; the variable name radius is different from RADIUS
or Radius.
You cannot use keywords or reserved words as variable names
Ex. public, private, class, method, main, package (usually anything that’s in
color blue or green in your NetBeans IDE).
Java has 8 primitive data types: byte, short, int, long, char, float, double and
boolean. A data type should start with a LOWERCASE letter.
float - this are usually useful when you need a fractional component, but don’t
require a large degree of precision. For example, float can be useful when representing
monetary values (dollar, peso, cents).
Ex. float weekly_wage = 458.38;
double - when you need to maintain accuracy over many calculations, or if you
are manipulating large-valued numbers, double is the best choice.
Ex. double pi = 3.1416;
char - data type that stores single characters. Value should be enclosed in single
quotation.
Ex. char choice = ‘a’;
Char can also handle Unicode values. Unicode defines a fully international
character set that can represent all of the characters found in human languages.
Ex. char value = 88;
88 is the code for X so this would display X. When assigning a Unicode value to
char, you don’t have to enclose it in a single quote.
bool - used for logical values. It can only have true or false as its value.
Ex. bool completed = true;
String - this is not included in the 8 primitive data type since string is a CLASS.
But it usually acts as a data type and is often used as such. It stores one or more
characters unlike data type char which can only store one character.
Ex. String name = “Grace Lhyn”;
When declaring a String, make sure you use a capital letter S and the value should
be enclosed in double quotations.
Java Operators
Most of Javas operators can be divided into the following groups: arithmetic,
relational and logical.
Arithmetic Operators - they are used to perform simple arithmetic operations
on primitive data types.
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulo - divided left-hand operator to right-hand operator and returns
remainder
++ : Increment - increases the value by 1.
-- : Decrement - decreases the value by 1.
Examples:
+ and - operator
Relational Operators - these operators are used to check for relations like equality,
greater than, less than. They return boolean result (true or false) after the comparison
and are extensively used in looping statements as well as conditional if else statements
(looping and conditional statements will be discussed on the next topic).
Syntax: variable relation_operator value;
Equal to, ==
Not Equal to, !=
Less than, <
Less than or equal to, <=
Greater than, >
Greater than or equal to, >=
Logical Operators - these are used to perform “logical AND” and “logical OR”
operation.
&&, Logical AND - returns true when both or all conditions are true.
||, Logical OR - returns true if at least one condition is true.
Since the expression a!=b is TRUE , b==10 is TRUE the output of line 15 is TRUE.
But line 17 is FALSE since the expression a<20 is FALSE even though b==10 is
TRUE.
In logical OR, only ONE expression needs to be TRUE for the output to be TRUE.
So line 19 is TRUE since the expression b>a is FALSE and a>10 is TRUE and line 21 is
FALSE since both of the expressions are FALSE.
In the sample code, if the expression a > b is TRUE then the value of variable
result will be “A is greater than B” but if the expression is FALSE then the value of
variable result will be “A is less than B”.
Conditional Statements and Looping Statements
Java If Statements
if(condition){
Statement1;
}
else if(condition{
Statement2;
}
else{
Statement3;
}
Sample Problem 1:
Write a program that would
display the students Grades (A-F)
based on their average. Use the data
below as your basis.
95-100 = A
90-94 = B
85-89 = C
80-84 = D
75-79 = E
below 75 = F
Sample Problem 2:
Write a program that determines
the season based on the month
given by the user.
Dec, Jan, Feb = Winter
March, April, May = Spring
June, July, Aug = Summer
Sept, Oct, Nov = Autumn
System.out.println(season);
After the if-else code since we want to determine first the value of season before we
print it.
Nested If Statement
Nested-If works similar to normal if-else condition. The only difference is that
there will be an if condition inside another if condition.
Syntax:
if(condition){
Statement;
if(condition){
Statement 2;
}
}
else{
Statement;
}
As shown in the
example, you can
also have an if-else
statement inside the
if-statement.
The code would
display the output:
Since the condition a==30 is TRUE so it would print the line: A is equals to 30
and proceed to the next if-statement.
Switch Statement
Another way to control the flow of your programs with decision-making
statements is by a switch statement. A switch statement gives you the option to test
for range of values for your variables. If you think your if-else-if statements is long and
complex, you can use switch statement instead.
Syntax:
switch(expression){ You usually need to declare and initialize a
case value1: variable before using a switch statement,
statement 1; as shown in the example below.
break; In switch statement, the value of the
case value2: expression is compared with each of the
statement 2; values in the case statement. If a match is
break; found, the code sequence following that
default: case statement is executed. There might
default statement; be more than one case being matched but
} switch will choose the first immediate
matching case ignoring the others.
In this example, we declare
and initialize a variable name
age with the value 1. The line
switch(age) would evaluate
the value of age and compare it
to the case values.
Since the line case 1
matches the value of the
variable age, the code following
that case statement would be
executed and it would ignore
the rest of the codes. So the
output of the following code is,
You are one year old.
for loop
The java for loop repeats the execution of a set of Java statements. A for loop
executes a block of code as long as some condition is true.
Syntax:
for(initialization; condition; increment/decrement){
Loop body or java statements;
}
The initialization expression initializes the loop and is executed ONLY ONCE at
the beginning of the loop. The condition is evaluated every loop and if it evaluates to
false, the loop is terminated. And lastly the increment/decrement expression is
executed after each
iteration through the
loop.
In the sample code, the line int i=0; will be executed first.
The condition i<5; will be evaluated next if the code is true then
the loop body will be executed but if the condition is false the code will
be terminated. Since the condition i<5 is TRUE it will proceed to the
loop body and will display the output Number: 0.
After executing the loop body it will proceed to the increment i++ and will add a
value of 1 to the i variable. After adding a value, it would go back to the condition i<5
and compare the new value of i (which is 2 after the i++) to 5, if it is still true then it
will proceed to the loop body. And the same process with loop until the condition
became false.
while loop
The while statement or loop continually executes a block of statements while a
particular condition is true. The while statement continues testing the expression and
executing its block until the expression evaluates to false.
Syntax:
Example:
output
Sample Program 1:
Write a Java Program that prints the
numbers 1-10.
Sample Program 2:
Write a Java Program that print the
number 5, 10, 15, 20, 25, 30.
The while loop evaluates its conditional expression at the top of the loop, the body
of the loop will not execute even once if the condition is false to begin with.
do-while Loop
The difference between do-while and while is that do-while evaluates it expression
at the bottom of the loop instead of the top. Therefore, the statements within the do
block are always executed at least once.
Syntax:
do{
loop body
}
while (condition);
Nested loop
If a loop exists inside the body of another loop, it’s called a nested loop. You can
do this on a while loop or for loop.
Package Statement
Import Statement
Class Definition
Since we’ve learned the Java Structure, we also need to understand the class and
method structures. Although, class and method will be discussed further in this course.
1. A shop will give discount of 10% if the cost of purchased quantity is more than 1000.
ask user for quantity. Suppose, one unit will cost 100. Compute and print total cost for
user including the discount.
2. A student will not be allowed to sit in exam if his/her attendance is less than 75%.
Take following input from user
Number of classes held
Number of classes attended.
And print percentage of class attended
Is student is allowed to sit in exam or not.
Unit 2: Classes, Objects and Methods
Objectives:
At the end of the unit, the student must have:
2. The most important method since this is the first method your Java program will
execute.
a) void method
b) main method
c) public
d) Class
4. max() is a Java predefined method that returns the highest value out of the two
integers.
a) TRUE
b) FALSE
Acquire new knowledge
Lesson Proper
Creating Method
The following example demonstrates how to define a method and how to call it.
In the sample code, you can call the method printSample to print any message
for a specific number of times.
On line 17 we have a statement printSample("Hello", 3); that passes the
actual string value “Hello” to the parameter message; passes 3 to parameter n,
based on the method body this would print the word “Hello” 3 times.
In this other example, you can see that you can call the same method multiple
times and you can also change there value. But make sure that you provide the correct
value based on the data type of the parameter.
The max method that was used earlier only works with the int data type. But what
if you need to determine which of two-floating point numbers or double numbers has
the maximum value? The solution is to create another method with the same name but
different parameters, as shown in the example code:
If you call max with int parameters, the max method that expects int parameters
will be invoked; if you call max with double parameters, the max method that expects
double parameters will be invoked. This is referred to as method overloading; that
is, two methods have the same name but different parameter lists within one class.
The java compiler determines which method is used on the method signature.
Methods: getArea
Data Field
Constructors
Method
A java class uses variables to define data fields (like double radius = 1.0) and
methods to define actions ( getArea() ).
Constructors are a special type of methods which are invoked to create a new
object. A constructor can perform action, but constructors are designed to perform
initializing actions, such as initializing the data fields of the objects.
The class Circle shown above does not have a main method. If you can recall the
Java program starts to execute the program from the main method. Since the
sample code does not have a main method it cannot be run; it is merely a definition of
circle objects.
The next example will show you how to define a class and use the class to create
objects based on the table/figure shown above. The program constructs three circle
objects with radius 1.0, 25 and 125 and display the radius and area of each circle.
Code Explanation:
Circle cirle1 = new Circle();
-instantiate a new object, so we can
access the Circle class
Since we instantiate an object we can
now access the Circle class and all of its
contents.
OUTPUT:
The program contains two classes, TestCircle and Circle. The TestCircle
contains the main method which would be invoked first when you run the program.
You can put two classes in one file, but only ONE class can be a public class.
The main method creates the three objects, the new operator is used to create an
object from the constructor. new Circle() creates and object with radius 1.0, new
Circle(25) creates and object with radius 25, and new Circle(125) creates an
object with radius 125.
There 3 objects (referenced by circle1, circle2 and circle3) have different data
but the same methods. Therefore, you can compute their respective areas by using
the getArea() method. The data fields can be accessed via the reference of the
object using circle1.radius, circle2.radius, and circle.radius. The
object can invoke or call the method via the reference of the object using
circle1.getArea(), circle2.getArea(), and circle3.getArea().
You can also change the value of the object as shown in the statement
circle2.radius = 100 which changed the value of radius to 100.
Notice that we also imported a package for the Date class: import
java.util.Date;
We instantiate an object: Date date = new Date(); and through this we can
use the getTime() and toString() methods.
1. A constructor
a) Must have the same name as the class it is declared within.
b) Is used to create objects.
c) May be declared private
d) Both (a) and (b)
e) (a), (b) and (c)
f) None of the above
Objectives:
At the end of the unit, the student must have:
a) Used a JFrmae;
b) Created a graphical user interface with various user-interface
components: JButton, JCheckbox, JLabel, JTextField, JTextArea, JComboBox and
JList
c) Displayed multiple windows in an application
How much do you know?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
Acquire new knowledge
Lesson Proper
Introduction to GUI
A graphical user interface (GUI) makes a system user friendly and easy to use.
Creating a GUI requires creativity and knowledge of how GUI components work. Since
the GUI components in Java are very flexible and versatile, you can create a wide
assortment of useful user interfaces.
Many Java IDEs (like NetBeans) provide tools for visually designing and
developing GUI interfaces. This enables you to rapidly assemble the elements of a user
interface (UI) for Java application with minimum coding. But tools cannot do
everything, you have to modify the programs they produce.
So far, we’ve learned how to create a Java Project, and upon creating the project
the NetBeans IDE automatically create a class and main method where we put initial
code. But this is not enough to develop a full system, we need a GUI.
JFrames
To create a user interface, you need to create a frame to hold the user interface
components. To create a frame, we use the JFrame class. But as mentioned earlier
that NetBeans provide tools so we don’t have to do all of the UI coding from scratch.
To add a JFrame in NetBeans:
Note: When naming Classes, Methods, Objects, Variables or other components in your
software make sure you use proper names that explains/shows the purpose of your
components. Avoid using your name or the name of your crush or your pets name if it’s not
necessary.
You can remove the statement: // TODO add your handling code here: and
replace it with your code.
To check your code, you can run the program again. Once you clicked the button
it should display your Message Dialog Box.
We declared a String
fruits variable. If a
checkbox is selected then
we get the text from that
check box then store it in
the fruits variable, along
with the line character ‘\n’.
the last line of code sets the
text on our message dialog
box.
Setting up your Radio Button
Just like in JButtons and JCheckbox, again, you can change the text of your radio
buttons by going to Properties > text. Also, make sure that you change the Variable
Name for each of your radio buttons by going to Code > Variable Name in the
Properties Panel.
In the example shown below, we will allow the user to choose ONE option from
the selections and once we clicked the jButton, we will display the Selected Course in a
Message Dialog Box.
As you can see in the image, that so far the user can
select ALL of the Radio Buttons.
So, its not enough to just add our radio button, we
need to put additional components to limit the user to
select one option only.
To do this, we need to use a ButtonGroup component.
You can see the Button Group under the Swing Controls
section.
Button Groups are used to group together your Radio
Buttons, or check boxes. You can have as many Button Group as you need.
To add the Button Group, drag the Button Group from your Palette to the JFrame
where your Radio Button is located. Once you’ve add it, YOU CANNOT PHYSICALLY
SEE THE BUTTON GROUP IN YOUR JFRAME. But you can see it in the Navigator Panel,
usually located on the bottom-left side of your screen.
Now it’s time to add a code to our jButton to display the chose course.
Again, double click on your jButton to go to the Source Code. Our buttons Variable
Name is bntDisplay.
rbICt, rbIT, rbEd and rbCriminology are the variable names of our radio
buttons.
The statement rbICT.isSelected() checks if the rbICT Radio Button is
selected.
The statement JOptionPane.showMessageDialog(null, "You are a " +
course + " student."); is outside of our if-else statement since we need to
determine first the value of the variable course before we display it to the user.
Labels, Text Fields and Text Areas
Label
A label is a display area for a short
text, an image or both. It is often use to
label other components. A JLabel has a
transparent background, so it will always
match the container it is in.
The label is also located under the
category of Swing Controls.
By now, hopefully, you know the drill: you can change the text on Properties >
Text and variable name on Code > Variable Name.
Text Fields
A text field is a text control that enables the user to type a small amount of text.
The text field is usually paired up with a jButton to perform an action.
In the example shown below, we will use a regular text field and a disabled text
field. I assigned a variable name txtName and txtNameCopy respectively on the
text fields. jButton is name btnCopy. Once the user input a value on the txtName text
field and click the jButton the text will be duplicated on the txtNameCopy text field.
We can do this by using the getText() and setText() methods.
jLabel
You can also do this if you don’t want to declare a variable, but I highly
recommend declaring a variable to make your code cleaner and clearer.
JPasswordField
The JPasswordField class is a subclass of JTextField, and provides a specialized
text fields for password entry. For security reason a password field does not show the
characters that the user types. It is instead replaced by a different character like
asterisk * or period/dots.
Text Areas
Text Fields allow the user to enter one line of text, but if you want to let the user
to enter multiple lines of text, you can use JTextArea instead of using multiple
JTextFields.
Lists
A list is a component that basically performs the same function as a combo box
but enables the user to choose a single value or multiple values.
Just like combo box, you can change the selection on a jList by going to the
Properties > model.
You can use dispose() to close a specific frame without exiting the whole program.
Apply your knowledge. In this part, you will practice what you have
learned.
3. What method should you use to assign a new value to a jLabel or jTextField?
6. What method should you use to get the value of a Combo Box?
10. A method that will allow you to set a value to your jPassword?
References.
2. A student will not be allowed to sit in exam if his/her attendance is less than 75%.
Take following input from user
Number of classes held, Number of classes attended And print percentage of class
attended. Is student is allowed to sit in exam or not?
UNIT 2:
1. A constructor
a) Must have the same name as the class it is declared within.
b) Is used to create objects.
c) May be declared private
d) Both (a) and (b)
e) (a), (b) and (c)
f) None of the above
OUTPUT:
Park Seo Joon
Kim Soo Hyun
UNIT 3:
1. What is the purpose of the isSelected() method?
- to check if check box is selected or checked
2. What method should you use to get the value of a jTextField?
- getText()
3. What method should you use to assign a new value to a jLabel or jTextField?
- setText()
4. Can you change the Background color of a jButton?
yes
5. What is the difference between getSelectedValue() and getSelectedValuesList()?
- getSelectedValue get one value from the jLists, getSelectedValuesList get
multiple values
6. What method should you use to get the value of a Combo Box?
- getSelectedItem()
7. What are the three Selection Mode of a jLists?
- SINGLE, SINGLE-INTERVAL, MULTIPLE-INTERVAL
8. What is the purpose of setVisible()?
- open/show the jFrame
9. How do you close a jFrame without terminating the whole program?
dispose()
10. A method that will allow you to set a value to your jPassword?
setEchoChar()