CIT 207 MODULE v2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Module in CIT 207:

Object Oriented Programming


Notes to the Students
This module is a part of the series of Modules for flexible learning spearheaded by
the Office of the Director of Instruction and the Center for Teaching Excellence, West
Visayas State University.
This is meant for the course CIT 207 - Object Oriented Programming.
Computer Programming is a creative process with no complete set of rules for
creating a program. It can develop a persons creativity and problem solving skills.
This module have the following set of lessons or topics:
Unit 1: Review of Basic Concepts of Java
Unit 2: Classes, Objects and Methods
Unit 3: Graphical User Interface
Unit 4: Object-Oriented Programming
Unit 5: Exception Handling

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.

The lesson will unfold in the following sequence:

How much do you know? This is a pre-test to check your knowledge on


this subject.

Acquire New Knowledge. This is where lesson is presented. It may have


several topics as stipulated in the specific objectives.

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

a) Variables and Data types


b) Java Operators
c) Conditional Statements and Looping Statements
d) Java Program Structure

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?

1. What is the size of a byte variable?


a) 8 bit
b) 16 bit
c) 32 bit
d) 64 bit
2. Which of the following is a primitive data type?
a) bool
b) int
c) String
d) void
3. Which of the following is NOT a primitive data type?
a) float
b) double
c) String
d) int
4. Which is a proper syntax in declaring and initializing a variable?
a) char value;
b) Char value = ‘a’;
c) char value = aaa;
d) char value = ‘G’;
5. What would be the output of the following code?

Declare and initialize a variable with the following value (observe proper syntax):
34.56 _____________________________________________
OOP _____________________________________________
-12 _____________________________________________
B _____________________________________________
Hello _____________________________________________
921718486500 _____________________________________________
Acquire new knowledge
Lesson Proper

Variable and Data Types


Variable designates a location in the memory for storing data and computational
results in the program. A variable has a name that can be used to access the memory
location. Think of a variable as a labeled basket. One basket is labeled “Apple”,
another basket is labeled “Orange” and a basket labeled “Banana”. By standards you
should put apples, oranges and bananas to there respective baskets. You can’t put
banana in a basket labeled Apple.

APPLE BANANA ORANGE

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.

How to declare and initialize a variable?


Before using a variable, all variable have to be declared first. Declaring a variable
means defining its data type , and optionally, setting an initial value.
Initializing a value means assigning a value to your variable. Variable do not have
to be initialized when they are declared, but it is often useful.

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 Data Types

Java has 8 primitive data types: byte, short, int, long, char, float, double and
boolean. A data type should start with a LOWERCASE letter.

byte - smallest integer value. Value ranges from -128 to 128.


Ex. byte age = 23;

short - range from -32,768 to 32,767


Ex. short no_of_students = 8500;

int - commonly used integer type, range from


-2,147,483,648 to 2,147,483,647 The example gives an error message :
Uncompilable source code -
Ex. int incompatible types: possible lossy
conversion from int to short.
long - this is useful for occasion where an int type is Since you cannot assign a value larger than
not large enough to hold the desired value. Range from 32,767 to short data type.
-9,223,372,036,854,775,8080 to
9,223,372,036,854,775,8080.
Ex. long lightSpeed = 16070400000000;

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

+ can perform basic


addition for integers.
But as shown in line
21, we add the value
of x (thank) to y
(you), this value are
Strings, and if +
operator is used with
Strings it
*, / and % operator

The code in line 16


shows another
example of
concatenation. We
concatenate the “a *
b” to the arithmetic
operation a * b by
using the + operator.

The next image shows


the output of the
code.
++ and -- operators

The increment (++)


operator increases the value
of its operand by one. The
decrement (--) decreases the
value by 1.

Assignment Operators: “=” - assignment operator is used to assign value to any


variable. General format or syntax is: variable = value;
In many cases assignment operator can be combined with other operators to build
a shorter version of statement called Compound Statement. For example, instead
of a=a+5, you can write a+=5.
You can also do this for other arithmetic operators, -=, *=, /= and %=.

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.

Ternary Operator - this is a shorthand version of if-else statement (which will be


discussed in the next unit). it has 3 operands, hence the name ternary.
Syntax: condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute
the statements after the ‘?’ else executes the statements after the ‘:’.

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

The If-Then statement


The if-then statement is the most basic of all the control flow statements. It
enables your program to execute a certain section of code depending on the state of
variables, or values returned from methods.
Syntax:
The statement could be a single line of code or a block of
if(condition){
Statement; codes enclosed in curly braces. The condition is any
} expression that returns a boolean values (true/false).
The ‘if statement’ works like this: if the condition is TRUE
then the statement will be executed. But if the condition is false, the statement will
NOT be executed.

In the example, the condition


10>5 is TRUE so the line “10 is
greater than 5” will be displayed
in the output window.

In this example, the condition 10<5


is FALSE so nothing will be displayed on
the output window.

The If-Then-Else statement


The if-then-else statement provides an alternate path when an ‘if’ clause
evaluates false.
Syntax:
if(condition){ The ‘if-then-else statement’ works like this: if the condition
Statement1;
is TRUE then the statement1 will be executed but if the
}
condition is false the statement2 will be executed.
else{
Statement2;
}

In this example, the condition a>b


is FALSE so it would skip the first
statement and would execute the
statement in the else block.
Chaining If statements
You can ‘chain’ if-else statements, and create a decision tree sort of thing.
Syntax:

if(condition){
Statement1;
}
else if(condition{
Statement2;
}
else{
Statement3;
}

You can have as many else if


conditions as necessary.

Using Logical Operators in If-else Condition

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

In the sample code we used the


LOGICAL AND (&&) Operator to
compare the values of the variable
average.
By using Logical && the result would be TRUE if BOTH of the condition is TRUE.
The block else if(average>=90 && average<=94){
is TRUE System.out.println("Your grade is B");
since the value of }
average (90) is equal
to 90 AND less than 94

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

In this example we use the


LOGICAL OR (||) since a specific
season can be on different months.
And we put the statement

System.out.println(season);
After the if-else code since we want to determine first the value of season before we
print it.

In the output the user input the number 5 (May),


and based on our condition the statement
month==3 || month==4 || month==5 is TRUE
since month==5 condition is TRUE.

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.

In this example, the


statement a==30 is
FALSE so it proceeds
to the else
statement and
display the output:

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.

Let’s take a look at another example, this


is the switch statement version of the
if-then-else statement earlier.
The value of the variable vehicle is “Car”.
The line switch(vehicle) evaluates the
value of the variable and compare it to the case
statements. Since the value matches the 2nd
case which is the code case “Car”: it would
execute the code after it and ignore the rest of
the code.
So the output of the following code is, I’m
a CAR

Note: When trying this code, you can


change the value of the variables to see what would happen.
String values are very case-sensitive so the value Car is different from CAR or car.

Break statement is also necessary in switch statement. Because without it your


switch statement would fall through. Let’s take a look at this example.`
The sample switch statement
does not have a break
statement so instead of just
executing the line
System.out.println("You
are one year old");
the output would be:

The default statement is optional. If no case


matches and no default is present, then no further action is taken.
Sample Problem 1:
Using a switch statement,
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

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.

The output of the


example would be:

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:

The condition can be any Boolean expression. The


while(condition){
loop body loop body will be executed as long as the condition is
} TRUE. When the condition becomes false, the control
passes to the next line of code after the loop.

Example:

output

The statement System.out.println(n); will execute as long as the condition


n>0 is TRUE. The statement n-- decrease the value of n by 1 during each loop.

While Loop Sample Problem

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);

The first sample code would display the


number from 1-10.
The second sample would only display the
number 10 since the condition n<0 is FALSE.

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.

Java Program Structure


Documentation
Section

Package Statement

Import Statement

Class Definition

Main method Class


 Documentation Section - you can write a comment in this section. Comments
are beneficial for the programmer because they help them understand the code.
These are optional though.
 Package Statement - a package is a group of classes that are defined by a
name. If you want to declare many classes within one element, then you can
declare it within a package. In NetBeans, once you create a project, NetBeans
would automatically create a package for you, with a class and main method.
 Import Statements - you can have one or more import statement in your
package. If you want to use a class from another package, then you can do this by
importing it directly into your program. In the sample code, used the import
javax.swing.JOptionPane; to import the JOptionPane class from the javax
package.
 Class definition - a java program may contain several class definition. Classes
are the main and essential elements of any Java program.
 Main method class - every java program requires the main method as the
starting point of the program. This is an essential part of the program. There may
be many classes in a Java program but only one class defines the main
method. Method contains data type declaration and executable statement. In the
sample code, the code: JOptionPane.showMessageDialog(null, "Hello
World!"); is written inside the main method block.

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.

 public class JavaApplication53 - this creates a class called


“JavaApplication53”. All class names should start with a CAPITAL letter. The
public word means that it is accessible to other classes.
 /** Comment block */ - the compiler ignores comment blocks on your code.
 { Braces } - the braces are used to group codes or commands.
 public static void main - when the main method is declared public, it means
that it can be used also by code of its class. The word static is used when we
want to access a main method without creating its object, as we call the main
method, before creating any class objects. The word void indicates that a method
does not return a value. (Classes and methods are discussed in Unit 3). main is a
method and the starting point of a Java program.
 (String[] args) - this statement is enclosed in a parenthesis which indicates that
this is the parameter of the main method. The parameter name is “args” and it is
an array where each element of it is a String.
 JOptionPane.showMessageDialog(null, "Hello World!"); - is a Java
statement that displays “Hello World!” in a dialog box.
Apply your knowledge. In this part, you will practice what you have
learned.

Write a code to display the following:

1. Multiplication Table: Allow the user to input a number


and display the multiplication table of the given number
(from 1-10), as shown in the image.

2. A company decided to give bonus of 5% to employee if his/her year of service is


more than 5 years. Ask user for their salary and year of service and print the net bonus
amount.
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.

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

a) Predefined Methods and Programmer Defined Methods


b) Local Variable and Overloading Methods
c) Defining Classes and Creating Objects
d) Using Classes from the Java Library

Objectives:
At the end of the unit, the student must have:

a. defined and used classes, objects and methods;


b. designed and developed a program using methods;
c. used Java library classes.
How much do you know?

1. What is a class in Java?


a) A class is a blue print from which individual objects are create. A class can
contain fields and methods to describe the behavior of an object.
b) A class is a special data type.
c) Class is used to allocate memory to a data type
d) None of the above.

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

3. Which of the following is a method?


a) Scanner
b) println()
c) Math
d) System.in

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

Predefined Methods and Programmer Defined


Methods
Predefined method or built-in methods are the methods or statements that are
included in the compiler and performs certain tasks. Some examples of this are
print(), println(), nextInt(), max() and a lot more. We will learn about other
predefined methods as we go along in this programming subject.
Programmer defined methods are methods created by the programmer
themselves which can also be used or called multiple times.

A Java method is a collection of statements that are grouped together to perform


an operation. It is a block of code which only runs when it is called. When you call the
System.out.println() method, the system actually executes several statements in
order to display a message on the console.
println() is an example of a
predefined method. Another example is
the main() method.
All Java program must have an entry
point, which is always the main() method.
The main() method is the key to making a
Java program executable.

Creating Method

 public static - modifier public static int methodName(int a, int b){


 int - return type //body
 methodName - name of the }
method
 a,b - formal parameters modifier returnType methodName(parameter){
 Int a, int b - list of parameter //method body
}
The syntax shown includes:
 Modifier - it defines the access type of the method and it is optional to use.
 returnType - method may return a value.
 methodName - this is the name of your method.
 Parameter List - it is consists of the type, order, and number of parameters of
a method. These are optional, method may contain zero parameters.
 Method body - the method body defines what the method does with the
statements.

The sample code returns the


minimum between two numbers.
Method Calling
The example above shows how to create a method but for using a method, it
should be called. There are two ways in which a method is called i.e., method return a
value or returns nothing (void or no return value).
When a program invokes a method, the program control gets transferred to the
called method. This called method then returns control to the caller in two conditions,
when the return statement is executed or it reaches the method ending
closing brace.

The following example demonstrates how to define a method and how to call it.

Sample 1: With return value using


a programmer defined method.
The sample code will produce the
following result:

In line 18 we called the method named


minFunction with parameters a and b
so the program control would jump to
the minFunction method on line 22.
n1 is equal to the
value of a, and n2 is
minFunction method has a return equal to the value of b
value as specified in line 31: return
min.

After executing the whole method body


the program control returns to line 19 to
execute the code:
System.out.println("Minimum Value = " + c);

Sample 2: NO return value (void)


using a programmer defined
method.

The void keyword allows us to


create methods which do not return a
value. In the following example we’re
considering a void method
methodRank. This method is a void
method, which does not return any
value. Call to a void method must be a
statement i.e. methodRank(255.7);
it is a Java statement which ends with
a semicolon.
Sample 3: Changing void method to value-returning method using a
programmer defined method.

The printGrade method


is another example of void
method. Again a call to a void
method must be a statement
as in line 17.
To see the difference
between a void and
value-returning method, let’s
redesign the printGrade
method to value-returning
method. We’ll name this one as
getGrade.

As shown in the example the getGrade


method has a return value of type char and
we declare a return statement in line 37. We
also assigned a variable for the value of
getGrade method in line 16.

Sample 4: Example of some predefined methods.

The example shows


some predefined
methods like max and
sqrt by using the Math
Class.
Passing parameters by values
The power of a method is its ability to work with parameters. You can use println
to print any string and max to find the maximum between any two int values. When
calling a method, you need to provide arguments, which must be given in the same
order as their respective parameters in the method signature. This is known as
parameter order association.

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.

Local Variables and Overloading Methods


A local variable in Java is a variable that’s declared within the body of a method.
Then you can use the variable within that method. Other methods in the class aren’t
even aware that the variable exists.
This could also means that you can
use the same variable name in a
different method without it overlapping
each other.
You can also declare local variables within blocks of code marked by curly braces
as shown in the code below.

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.

Defining Classes and Creating Objects


Object-Oriented Programming (OOP) involves programming using objects. An
object represents an entity in the real world that can be distinctly identified. For
example, a student, a desk, a circle, a button and even a loan can all be viewed as an
object. An object has a unique identity, state, or behavior.
 The state (also known as properties or attributes) of an object is
represented by data fields with their current values. A circle object, for example, has a
data field radius, which is a property that characterizes a circle. A rectangle object has
data field width and height, which are the properties that characterizes a rectangle.
 The behavior (also known as actions) of an object is defined by methods.
To invoke a method on an object is to ask an object to perform an action. For example,
you may define a method name getArea() for circle objects. A circle object may
invoke getArea() to return its area. (This will be shown in the example later)
Objects of the same type are defined using a common class. A class is a template,
blueprint, or contract that defines what an objects data fields and methods will be. An
object is an instance of a class and creating an instance is referred to as instantiation.
The terms objects and instance are often interchangeable. The relationship between
classes and object is analogous to that between an apple-pie recipes and apple pies.
You can make as many apple pies as you want from a single apple-pie recipe same
way as you can instantiate as many objects as you want within a class.

Class name: Circle


A class template
Data Fields: radius
is ______

Methods: getArea

Circle Object 1 Circle Object 1 Circle Object 1 3 Objects of the


Circle Class
Data Fields: radius Data Fields: radius Data Fields: radius
is 0. is 25. is 125.

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.

circle1.radius - by using the name of


your object you can now call the radius
variable. Since new Circle() does not
have a parameter, our first code would
access the constructor that don’t have a
value.

The next block of code Circle circle2 =


new Circle(25), we assigned a value to
the parameter (25) so our code would
access the constructor that has a value.

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.

Things to note (or notice) in using constructor. Constructor

 A constructor must have the same name as the class


itself.
 Constructor do not have a return type - not even void.
public void Circle(){
}

In this case, Circle() is a method not a constructor since we declared a return


type (void).
 Constructor are invoked using the new operator when an object is created.
new ClassName(arguments)

For example, new Circle() creates


an object of the Circle class using the
first constructor using defined in the
Circle class, and new Circle(25)
creates an object using the second
constructor defined in the Circle class.

Using Classes from the Java Library


The Date Class
Java provides a system-independent encapsulation of data and time in the
java.util.Date class. You can use the no-arg constructor in the Date class to create an
instance for the current date and time, its getTime() method to return the elapsed time
since January 1, 1970, GMT and its toString method to return the data and time as a
string.
Displays the output:

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.

The Random Class


To generate random numbers we have to use or import the java.util.Random
class which can generate a random int, long, double, float, and boolean value.
Notice that the java.util.Random package has been imported into the code.

This sample code would generate


an integer from 0 to 5.

Aside from nextInt, you can also


use nextDouble, nextFloat,
nextLong, nextBoolean
Although the nextDouble and
nextFloat methods will give you
the value between 0.0 and 1.0
only.
Apply your knowledge. In this part, you will practice what you have
learned.

1. Use the Random Class to generate a number from 1-100.

2. Write a Java method to compute the average of three numbers.


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.

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

2. What would be the output of the following?


Unit 3: Graphical User Interface
(GUI pronounced as Goo-wi)
a) Introduction to GUI
b) JFrames
c) JButtons, Check Boxes, Radio Buttons
d) Labels, Text Fields and Text Areas
e) Combo Boxes, Lists
f) Creating Multiple Windows

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?

1. Why is GUI important in Software Development?

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________
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:

1. On the Projects Window,


right-click on your package
folder and click New > Frame
Form

2. A new window will


appear that allows you to
change the Class Name
(name of your JFrame). I
changed my Class name to
MainForm. Then click
Finish. Make sure that your
class name don’t have any
spaces
3. A new Java File
would be added on your
Package.

This is where we will


put all of our UI
components. You can
add as many JFrames
as necessary for your
project.

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.

Now that we’ve created a JFrame, we


also need to learn how to display the
JFrame once we’ve run the program. If
we look at our Main class (JavaGUI.java),
our main method does not contain any
statements. So if we run the program it
will not display anything.
To display our JFrame we need to call
the Jframe name and set it to visible.

Syntax: new JFrameName().setVisible(booleanExpression);

The MainForm() is the


name of the JFrame we
wanted to display.
setVisible() is a Java
pre-defined method with
a boolean parameter.
We use the value true if
want to display our component.

Once we run our code, we will see a blank


JFrame as shown in the image, we can change a
little in its property to add a title to our JFrame.
If you click on your JFrame, you will see the
Palette and Properties Panel on the right side of
your IDE. (If you can’t see either of the two, first
make sure you CLICKED THE FRAME or on the
upper part of your IDE go to Windows >IDE
Tools and click the panel that you need)
By default, this is blank but
you can assign a title to
your JFrame.
Titles can have spaces on it.

After adding a title, once you run your


program you can now see the title on top of your
JFrame.

Now that we’ve created a JFrame and


display it, it’s time to add some UI components
into our frame.

JButtons, Check Boxes and Radio Buttons


A button is a component that triggers an action event when clicked. Java provides
regular button, toggle buttons, check box buttons, and radio buttons. The common
features of these buttons are defined in javax.swing.AbstractButton.
In the Properties panel, you can change the properties of the component that you
clicked. In this example you
can see the [JFrame] -
Properties, which means
you can see or change the
properties of your JFrame.
In the Palette panel you
can see the other
components, we will not be
able to discuss all of it, but
we will discuss the
commonly used
components. Under the
Swing Controls, you can
see the Button. Click on the
Button and drag it to your
JFrame.
Once you drag it, you will see the Button in your
JFrame. You can also resize your button. By
default, you can see the jButton1 text on it. You
can change the button text by going to the
properties panel, under the Properties > text.
Since this is just the text written on you button
you can include spaces on it.

If you take a look at other properties, you


can see that you can also change the font by
clicking on the … symbol.

Note: you can check out the other


properties and play around with it if you want.
You can run (f6) your code to see the output.

Now that we’ve added a button to our JFrame


another important task it to assign a variable name
to our component. To do this, on the Properties Panel,
go to Code > Variable Name and assign a new
Variable Name, by default the Variable Name is
jButton1 but I’ll rename this as btnClickThis.
Again, variable name should be UNIQUE, DON’T
HAVE SPACES, CLEAR and EASY TO REMEMBER since
you will be referring to it a lot n your code.
We will leave the Variable Modifiers to its
default value which is private.
We are now all set up with our button, but this
doesn’t perform any actions yet. We need to add
additional codes for it to do what we want.
Example 1: We create a button, and once clicked we want it to display a message in
a Message Dialog Box. To add a code in our button, we can either right-click on
your jButton go to Events > Action > actionPerformed or you can
double-clicked on your jButton. Both of this actions will route you into the Source Code
page and you should be able to see the following:

You can see the variable name of your button on btnClickThisActionPerformed.


This is the benefit of using an IDE like NetBeans since codes like this will automatically
be generated by the IDE itself.
But to display a message we need to add a few more codes to it. Make sure you
put your code inside the { curly braces } as shown in the next image.

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.

Check Boxes and Radio Buttons


The GUI components contain three types of state buttons (JToggleButton,
JCheckBox and JRadioButton) that have on/off or true/false values. JToggleButton
are frequently used with toolbars. JCheckbox and JRadioButtons are subclasses of
JToggleButton. A JRadioButton is different from a JCheckBox in that there are
normally several JRadioButton that are grouped together and ONLY ONE of the
JRadioButtons in the group can be selected (true) at any time.

As shown in the image, when


using Check Box you can
choose one or more items in the
selection. But when using a
Radio Button, you can choose
ONLY ONE item from the
selection. This is the norm in
any software or GUI design.
Setting up your Checkbox
Just like in JButtons, in JCheckbox you can change the text by going to
Properties > text. Also, make sure that you change the Variable Name for each of
your check box by going to Code > Variable Name in the Properties Panel.
In the example shown below, we will allow the user to choose multiple items from
the selection and once the jButton (Display Fruit) has been clicked, we will display
the Selected fruit in the Message Dialog Box.

This code was added to the


jButton.
isSelected() - check if the
checkbox is checked.
getText() - get the value
or text of the checkbox.

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.

If you can’t see the


Navigator Panel, go to
Window > Reset Windows

Just like any other components, you can


change the Variable Name of the Button Group
by going to the Code > Variable Name in the
Properties Panel. In this example, I named the
button group to bgCourse.
Once you have your Button Group, assign each of
the Radio Button to your Button Group. To do this, click
your Radio Button, go to the Properties Panel, under the
Property > buttonGroup. You should see a drop
down list of all your Button Groups. Choose the
appropriate Button Group for you Radio Button.
Do this to ALL of your Radio Buttons.

Once you do this, you should be able to choose only


ONE option out of all your Radio Buttons within the same
Group.

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.

Color can be changed in the


Properties > foreground.
Font Style can be changed in
Properties > font.
Alignment can be changed in
the Properties >
horizontalAlignment.

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

jTextField: allows the user


to enter a text

Uneditable or disabled jTextField: wont


allow the user to enter anything.
You can disable a jTextField by
removing the check on Properties >
editable

Again, double click on your jButton to go to the Source Code.


As you can see in the code, we declare a variable since we need a container to put
the value of the txtName text field. getText() method will get the value of our
component and setText() method will assign a value to our component. You can
use this method in pretty much every components (i.e. text field, label, button, etc)

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.

Output of the code:

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.

In this example, we used a jCheckBox to display the value of a password. To add


a code in a jCheckBox, right click on the checkbox and go to Events > Action >
actionPerformed or double click on you checkbox.
cbShowPassword - variable name of the jCheckbox
txtPassword - variable name of jPasswordField
isSelected() - method used to check if checkbox is checked.
setEchoChar - allows you to set a character that would appear whenever a user type
in the password. By default a jPassword Field displays a bullet symbol.
setEchoChar((char)0) - Setting a value of 0 indicates that you wish to see the text as
it is typed, similar to the behavior of a standard jTextField
setEchoChar('\u2022') - \u2022 is the Unicode value of the bullet symbol.

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.

If you take a look at the Navigator Panel, you


would see that the jTextArea is inside a
jScrollPane, NetBeans made it like this so a
scroll bar would be automatically added on
your jTextArea.

Combo Boxes and Lists


Combo Box
A combo box, also know as choice list or drop-down list,
contains a list of items from which the user can choose. It is
useful in limiting the user’s range of choices and avoids
cumbersome validation of data input.

By default, once you add a combo box on your jFrame, it


would show you the following options. To change the
contents of the option, click your combo box and go to
Properties > model, then click on the 3-dot symbol. A
new window would appear that would allow you to add
your options.
Add options on your combo box

Example 1: Allow the user to choose a course, and


display the chosen course in a jTextField.

In this example, we want the course to be displayed in


the jTextField the moment the value of the combo box
changed when the user clicked on the chosen course.
To do that, we can add an itemStateChanged
event.

Add an itemStateChanged Event


Right-click on you combo box, go to Events > Item > itemStateChanged.
Once you clicked on the itemStateChanged, you will be routed to the Source Code
cmbCourse = Variable Name of the Combo Box
txtCourse = Variable Name of jTextField
To get the current selected item from jComboBox menu, you can use the
getSelectedItem().

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.

The jList has 3 selectionMode, the SINGLE selection


allows only one item to be selected.
SINGLE-INTERVAL selection allows multiple
selections, but the selected items must be
continuous. MULTIPLE-INTERVAL selection allows
selections of multiple items to be selected without
any restrictions, as shown in the figure below.

SINGLE SELECTION SINGLE-INTERVAL MULTIPLE-INTERVAL


SELECTION SELECTION
getSelectedValue() - returns the
selected value when only a SINGLE item is
selected in the list.

getSelectedValuesList() - Returns a list of ALL the selected items.

Also notice that in getSelectedValue()


we declare the variable as String, but
on getSelectedValuesList() we declare
the variable as List<String> since
the getSelectedValuesList() holds an
array of String values.
Creating Multiple Windows
You can also create multiple windows or frame in your package and you can just
use the setVisible() method to open another jFrame as shown in the images.

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.

1. Name all of the GUI components used on this example.


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.

1. What is the purpose of the isSelected() method?

2. What method should you use to get the value of a jTextField?

3. What method should you use to assign a new value to a jLabel or jTextField?

4. Can you change the Background color of a jButton?

5. What is the difference between getSelectedValue() and getSelectedValuesList()?

6. What method should you use to get the value of a Combo Box?

7. What are the three Selection Mode of a jLists?

8. What is the purpose of setVisible()?

9. How do you close a jFrame without terminating the whole program?

10. A method that will allow you to set a value to your jPassword?
References.

Java Program Structure. (n.d.). Retrieved from https://www.w3schools.in/


java-tutorial/ program-structure/

Liang, Daniel Y, 2007. Introduction to Java Programming, Eighth Edition

Schildt, Herbert, 2011. Java: The complete reference, Seventh Edition


Answer Key.
UNIT 1:
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:

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

2. What would be the output of the following?

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()

You might also like