Object Oriented Programming IM
Object Oriented Programming IM
PROGRAMMING
(JAVA LANGUAGE)
Compiled by:
Elias A. Austria
Aleta C. Fabregas
Alfred M. Pagalilawan
Rachel A. Nayre
1
TABLE OF CONTENTS
TOPIC PAGE
Lesson 1 Introduction to OOP and Basic Components of Java
Object-Oriented Programming 5
Features of OOP 5
History of Java 5
Java Platform 8
Parts of Java Language 9
Variables and Data Type 10
Operators 12
Exercises 15
Lesson 2 Input and Control Statements
Input Statements 18
Displaying Text in a Dialog Box 20
Control Flow Statements
if-else statement 23
switch statement 24
Loop statements 26
Exercises 29
Lesson 3 Arrays and Strings
Array 31
String
String Methods 32
Exercises 35
Lesson 4 Methods
Definition of Method 38
Passing Array to Method 42
Method Overloading 43
Exercises 44
Lesson 5 Classes and Objects
Class and Object Definition 47
Instance Method 48
Declaring Objects 49
Instance Object 52
Laboratory Exercises 54
Lesson 6 Overloading Constructors
Constructor Method 56
Overloading Constructors 60
Laboratory Exercises 62
Lesson 7 Prewritten Classes and Methods
Prewritten Constants and Methods 64
Prewritten Imported Methods 65
Laboratory Exercises 67
Lesson 8 Frames
GUI Components 69
Swing Overview 69
Lesson 9 Database
Database Definition 95
JDBC 95
2
Steps in Creating DB 96
SQL Syntax 96
Laboratory Exercises 96
Bibliography 110
3
Lesson 1
Introduction to OOP and
Basic Components of Java
Overview:
This lesson covers object oriented programming and its features, history of Java language and
characteristics, Java platform and basic components of Java language
Objectives:
To enumerate the features of OOP
To describe the characteristics of Java language
To understand how the Java program works
To form variable name based on the rules
To list the data types and its sizes
To understand how the Java operators work
4
Object-Oriented Programming
When you program without using OOP (Object-Oriented Programming), you are
programming procedurally. A procedural program is a step-by-step program that guides the
application through sequence of instructions. A procedural program executes each statement in
the literal order of its commands, even if those commands cause the program to branch into all
directions. C, Pascal, Qbasic and COBOL are all examples of procedural programming
languages
5
connection to the internet began. In 1995, Netscape Incorporated released its latest version of
the Netscape browser which was capable of running Java programs.
Why is it called Java? It is customary for the creator of a programming language to name the
language anything he/she chooses. The original name of this language was Oak, until it was
discovered that a programming language already existed that was named Oak. As the story
goes, after many hours of trying to come up with a new name, the development team went out
for coffee and the name Java was born.
While Java is viewed as a programming language to design applications for the Internet,
it is in reality a general all- purpose language which can be used independent of the Internet.
What is Java?
The Java programming language was developed by SUN (Stanford University Network)
Microsystems as an object-oriented language that is used both for general-purpose business
programs and interactive World Wide Web-based internet programs. Some of the advantages
that made Java programming language so popular in recent years are its security features, and
the fact that it is architecturally neutral, which means that you can use Java to write program
that will run on any platform.
Java is also unusual in that each Java program is both compiled and interpreted. With a
compiler, you translate a Java program into an intermediate language called Java
bytecodes or simply bytecode--the platform-independent codes interpreted by the Java
interpreter. With an interpreter, each Java bytecode instruction is parsed and run on the
computer. Compilation happens just once; interpretation occurs each time the program is
executed. This figure illustrates how this works.
6
You can think of Java bytecodes as the machine code instructions for the Java Virtual
Machine (Java VM). Every Java interpreter, whether it's a Java development tool or a Web
browser that can run Java applets, is an implementation of the Java VM. The Java VM can also
be implemented in hardware.
Java bytecodes help make "write once, run anywhere" possible. You can compile your
Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then
be run on any implementation of the Java VM. For example, the same Java program can run on
Windows NT, Solaris, and Macintosh
You can think of Java bytecodes as the machine code instructions for the Java Virtual
Machine (Java VM). Every Java interpreter, whether it's a Java development tool or a Web
browser that can run Java applets, is an implementation of the Java VM. The Java VM can also
be implemented in hardware.
7
The Java API is a large collection of ready-made software components that provide
many useful capabilities, such as graphical user interface (GUI) widgets. The Java API is
grouped into libraries (packages) of related components.
The following figure depicts a Java program, such as an application or applet, that's
running on the Java platform. As the figure shows, the Java API and Virtual Machine insulates
the Java program from hardware dependencies.
1 /**
2 * The HelloWorld class implements an application that
3 * simply displays "Hello Java!" to the standard output.
4 */
8
5 public class HelloWorld
6 {
7 public static void main(String args[])
8 {
9 System.out.println("Hello World!");
10 }
11 }
Programming Analysis:
Line 1 to 4: Are what we call doc comments. The program simply ignores any statements
that are inside a comments.
9
prints a line of output on the screen then positions the cursor on the next line. The dots in the
statement System.out.println are used to separate Class, object and method. Classes, objects
and methods are further discussed in the next module
Line 10: Ends method main()
Line 11: Ends class HelloWorld
Where To code your Java Programs?
You can use Notepad, Textpad or Eclipse to create java programs, be sure that the file
name is the same as the class name and the extension name should be java.
example:
HelloWorld.java
Rules Of Java Programming.
Java just like its predecessor C is case-sensitive language. Always check for the proper
casing when writing and encoding java program. Statements must terminate with ;
(integers)
-32,768 to
short 16-bit two's complement Short integer
32,767
-2,147,483,648
int 32-bit two's complement Integer to
2,147,483,647
(real numbers)
10
double 64-bit IEEE 754 Double-precision floating point
(other types)
Variable Names
A program refers to a variable's value by its name.
In Java, the following must hold true for a variable name
1. It must be a legal Java identifier comprised of a series of Unicode characters. Unicode is a
character-coding system designed to support text written in diverse human languages. It
allows for the codification of up to 65,536 characters, currently 34,168 have been
assigned. This allows you to use characters in your Java programs from various
alphabets, such as Japanese, Greek, Cyrillic, and Hebrew. This is important so that
programmers can write code that is meaningful in their native languages.
2. It must not be a keyword or a boolean literal (true or false).
3. It must not have the same name as another variable whose declaration appears in the
same scope.
Variable Initialization
Local variables and member variables can be initialized with an assignment statement
when they're declared. The data type of both sides of the assignment statement must match.
int count = 0;
The value assigned to the variable must match the variable's type.
Final Variables
You can declare a variable in any scope to be final, including parameters to methods
and constructors. The value of a final variable cannot change after it has been initialized.
To declare a final variable, use the final keyword in the variable declaration before the
type:
final int aFinalVar = 0;
The previous statement declares a final variable and initializes it, all at once.
Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if
necessary, defer initialization of a final variable. Simply declare the variable and initialize it later,
like this:
final int blankfinal;
11
...
blankfinal = 0;
A final variable that has been declared but not yet initialized is called a blank final. Again,
once a final variable has been initialized it cannot be set and any later attempts to assign a
value to blankfinal result in a compile-time error.
Operators
Arithmetic Operators
The Java language supports various arithmetic operators for all floating-point and integer
numbers. These include + (addition), - (subtraction), * (multiplication), / (division), and %
(modulo). For example, you can use this Java code to add two numbers:
addThis + toThis
Or you can use the following Java code to compute the remainder that results from
dividing divideThis by byThis:
divideThis % byThis
The + and - operators have unary versions that perform the following operations:
Operator Use Description
There also are two short cut arithmetic operators, ++ which increments its operand by 1,
and -- which decrements its operand by 1.
Operator Use Description
12
++ op++ Increments op by 1; evaluates to value before incrementing
&& op1 && op2 op1 and op2 are both true, conditionally evaluates op2
! ! op op is false
op1 and op2 are both true, always evaluates op1 and
& op1 & op2
op2
| op1 | op2 either op1 or op2 is true, always evaluates op1 and op2
In addition, Java supports one other conditional operator--the ?: operator. This operator
is a ternary operator and is basically short-hand for an if-else statement:
expression ? op1 : op2
The ?: operator evaluates expression and returns op1 if it's true and op2 if it's false.
example: int x = 5, y = 6, z = 0;
x > y ? z=x : z=y;
13
In the previous example since the expression x > y evaluates to false x++ operator is
performed.
Assignment Operators
You use the basic assignment operator, =, to assign one value to another. The
countChars method uses = to initialize count with this statement:
int count = 0;
Java also provides several short cut assignment operators that allow you to perform an
arithmetic, logical, or bitwise operation and an assignment operation all with one operator.
Suppose you wanted to add a number to a variable and assign the result back into the variable,
like this:
i = i + 2;
You can shorten this statement using the short cut operator +=.
i += 2;
The two previous lines of code are equivalent.
This table lists the shortcut assignment operators and their lengthy equivalents:
Operator Use Equivalent to
Expressions
Expressions perform the work of a Java program. Among other things, expressions are
used to compute and assign values to variables and to help control the execution flow of a
program. The job of an expression is two-fold: perform the computation indicated by the
elements of the expression and return some value that is the result of the computation.
Exercises
Write the Java statement for the following: (Statements must be properly terminated)
14
1. Declare x,y and z to be variables of type int with values 5,10 and 15 respectively
_____________________
2. Store the result of the comparison between x and y to z. Use the comparison operator >
_____________________
3. Store the sum of x and y to variable sum
_____________________
4. Display the value of x,y and z using only one print or println statement in this method :
The sum of 5 and 10 is 15
_____________________
Laboratory Exercises
1. Write, compile and test a program that displays the following patterns on the screen
a) * b) 1
*** 12
***** 123
***** 1234
*** 12345
*
2. Write a program that prints your complete name on the first line and course, year and
section on the second line using only one System.out.println statement.
4. Write a program that inputs the hourly rate and number of hours worked. Compute
and display the gross pay (hourly rate * hours worked), your withholding tax, which
is 15% of your gross pay and your net pay (gross pay – withholding tax).
Sample output : Hourly rate : 104.65
Hours worked : 22
Gross pay : 2302.3
Withholding tax : 345.345
Net pay : 1956.955
15
5. Write a program that declares a variable that represents the minutes worked on a job
and assign a value. Display the value in hours and minutes. For example 125
minutes becomes 2 hours and 5 minutes
Sample output : Given : 125 minutes
Converted hours : 2 hours and 5 minute/s
6. Write a program that displays the conversion of 1887 into 1000’s, 500’s, 100’s,50’s
20’s ,10’s, 5’s and 1’s
Sample output Cash on hand : 1887
Denominations :
1000 – 1
500 - 1
100 - 3
50 – 1
20 – 1
10 – 1
5-1
1-2
Lesson 2:
Input statements and
Control Flow Statements
16
Overview:
This lesson covers the different input statements and control flow statements.
Objectives:
To utilize the different input statements
To apply the output statement in the program
To identify the control flow statements
17
Java Input Statements
To put data into variables from the standard input device (keyboard) we can use the predefined
Java class such as BufferedReader and Scanner.
BufferedReader
A java class to read the text from an input stream by buffering characteristics that
seamlessly reads characters, arrays or lines.
Syntax:
BufferedReader buffread = new BufferedReader(new
InputStreamReader(System.in));
This statement creates the input stream object buffread (user-defined word) and
associates it with the standard input device. (Note that the BufferedReader is a
predefined Java class and the above statement creates buffread to be an object
of this class). The object buffread reads the input as follows:
a. for integer
Integer.parseInt(buffread.readLine())
c. for strings
buffread.readLine()
Example:
import java.io.*; lastname = (buffread.readLine());
class InputData1 System.out.print("Enter age: ");
{ public static void main(String[] args) age = Integer.parseInt(buffread.readLine());
throws IOException System.out.print("Enter weight: ");
{ String firstname, lastname; weight =
int age; Double.parseDouble(buffread.readLine());
double weight; System.out.println("Your Name is: " +
BufferedReader buffread = new firstname + " " + lastname);
BufferedReader(new System.out.println("Your Age is: " + age);
InputStreamReader(System.in)); System.out.println("Your Weight is: " +
System.out.print("Enter firstname: "); weight);
firstname = (buffread.readLine()); }
System.out.print("Enter lastname: "); }
Note: When using BufferedReader, import java.io.*; (java input/output package) must be
declared before the class declaration and throws IOException keywords must be
included in the main declaration.
Scanner
Used to get user input of the primitive types.
Syntax:
static Scanner console = new Scanner (System.in);
This statement creates the input stream object console and associates it with the
standard input device. (Note that the Scanner is a predefined Java class and the
18
above statement creates console to be an object of this class). The object
console reads the next input as follows:
a. for integer
console.nextInt()
c. for string
console.next()
Note: When using Scanner, import java.util.*; (java utilities package) must be
declared before the class declaration.
Note: When using parsing/parse, you must input the value/s when executing the
program. Example: InputData3 juan cruz 20 110.00.
InputDialog Box
Used to get input from the user.
Example:
19
import javax.swing.JOptionPane;
public class InputData4
{ public static void main(String args[])
{ String name;
name=JOptionPane.showInputDialog("Enter your name ");
System.exit(0);
}
}
Displaying Text in a Dialog Box
Java’s numerous predefined classes are grouped into categories of related classes called
packages. The packages are referred collectively as the Java class library, or Java applications
programming interface (API). The packages of the Java API are split into core packages and
extension packages. The names of the packages begin with either “java” (core packages) or
“javax” (extension packages). Java’s class JOptionPane provides prepackaged dialog boxes
that enable programs to display messages to users.
Example:
1 // Java extension package
2 import javax.swing.JOptionPane;
3 public class Dbox
4 {
5 public static void main (String args[ ])
6 {JOptionPane.showMessageDialog(null,“Welcome to \nJava 2 programming”);
7 System.exit(0); //terminate application
8 } //end of method main
9 } // end of class Dbox
Output:
Line 2 tells the compiler to load the JOptionPane class from javax.swing package. This
package contains many classes that help in defining graphical user interfaces (GUIs). GUI
components facilitate data entry by the user of your program and formatting or presentation of
data outputs to the user of your own program. Line 6 indicate a call to method
20
showMessageDialog of class JOptionPane. The method in line 6 contains 2 arguments. The
first argument helps the Java application determine where to position the dialog box. When the
first argument is “null”, the dialog box appears at the center of the screen. The title bar of the
dialog box contains the string Message, to indicate that the dialog box is presenting a message
to the user. The dialog box automatically contains the OK button that allows the user to dismiss
(hide) the dialog box by clicking the button. Line 7 uses a static method exit of class System to
terminate the application. The argument 0 to method exit indicates that the application has
terminated successfully. A non-zero value normally indicates that an error has occurred.
output
21
message dialog will appear at the center, the second argument is the message to display. In
this case the second argument is :
“Hello “ + name
The third and fourth arguments represent the string that should appear in the dialog box’s title
bar and dialog box type respectively. The fourth argument – JOptionPane.PLAIN_MESSAGE is
a value indicating the type of message dialog to display. This type of message does not
display an icon to the left of the message.
argument 3
argument 2
All message dialog types except PLAIN_MESSAGE display an icon indicating to the user the
type of message.
22
Adding 2 integers in a dialog box
import javax.swing.JOptionPane;
public class Sum
{ public static void main(String args[])
{ String firstnum,secondnum;
int sagot;
firstnum=JOptionPane.showInputDialog("Enter first number ");
secondnum=JOptionPane.showInputDialog("Enter second number ");
sagot = Integer.parseInt(firstnum) + Integer.parseInt(secondnum);
JOptionPane.showMessageDialog(null,"The sum is " +
sagot,"Result",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
Control flow statements determine the order in which other statements are executed.
Java language supports several control flow statements, including:
Statement Keyword
23
This is the simplest version of the if statement: the statement governed by the if
is executed if some condition is true. Generally, the simple form of if can be written like this:
if (expression)
statement to do if expression is true;
What if you wanted to perform a different set of statements if the expression is false?
Well, you can use the else statement for that.
if (expression)
statement to do if expression is true;
else
statement to do if expression is false;
What if you intend to do more than one statements if the expression is true? What about
if you intend to do more than one statements if the expression is false? Well just place them in
a block – using the open brace as the start and ending it with a close brace.
if (expression)
{
statement/s to do if expression is true;
}
if (expression)
{
statement/s to do if expression is true;
}
else
{
statement/s to do if expression is false;
}
Other format of if-else statement is the nested if-else. Consider the sample below.
Where else is followed by another if.
int testscore;
char grade;
if (testscore >= 90)
{ grade = 'A';
}
else if (testscore >= 80)
{ grade = 'B';
}
else if (testscore >= 70)
{ grade = 'C';
}
else if (testscore >= 60)
{ grade = 'D';
}
else { grade = 'F'; }
24
month based on its integer equivalent. You could use Java's switch statement to perform this
feat:
int month;
...
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
}
The switch statement evaluates its expression, in this case, the value of month, and
executes the appropriate case statement. Of course, you could implement this as an if
statement:
int month;
...
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
...
// you get the idea
...
Deciding whether to use an if statement or a switch statement is a judgment call. You can
decide which to use based on readability and other factors. Each case statement must be
unique and the value provided to each case statement must be of the same data type as the
data type returned by the expression provided to the switch statement.
Another point of interest in the switch statement are the break statements after each case.
The break statements cause control to break out of the switch and continue with the first
statement following the switch. The break statements are necessary because case statements
fall through. That is, without an explicit break control will flow sequentially through subsequent
case statements. In the previous example, you don't want control to flow from one case to the
next, so you have to put in break statements. However, there are certain scenarios when you do
want control to proceed sequentially through case statements. Like in the following Java code
that computes the number of days in a month according to the old rhyme that starts "Thirty days
hath September, April, June and November all the rest is Thirthy-one except February..":
int month;
int numDays;
...
switch (month) {
case 1:
case 3:
case 5:
case 7:
25
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year%4==0) && !(year % 100 == 0))||(year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
}
Finally, you can use the default statement at the end of the switch to handle all values that
aren't explicitly handled by one of the case statements.
int month;
...
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Hey, that's not a valid month!"); break;
}
Loop Statements
do {
statement to do until expression becomes false;
} while (expression);
while (expression) {
statement to do while expression becomes is true;
}
26
break statement
The break statement has two uses. The first is to terminate a case in the switch
statement; the second use is to force immediate termination of a loop, bypassing the normal
loop conditional test. When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next statement following the loop.
int x;
for(x=0; x<100; x++)
{
System.out.println(x);
if ( x == 10)
break;
}
This prints the numbers 0 through 10 on the screen and then terminates because the
break causes immediate exit form theloop, overriding the conditional test x<100 built into the
loop.
continue statement
The continue statement works somewhat like the break statement. But, instead of
forcing termination, continue forces the next iteration of the loop to take place, skipping any
code in between. For example the following routine displays only odd numbers from 1 to 100:
int x = 1;
do {
if ( x % 2 == 0)
continue;
} while ( x != 100);
Nested Loops
Just as if statements can be nested, so can loops. You can place a while loop within a
while loop or a for loop within a for loop. In short, when we say nested loop, we have a loop
within a loop
Example : Try creating a program that displays numbers from 1-5 in this manner
1
12
123
If the output is that short, you need not bother yourself constructing a nested loop, you
can accomplish it with a series of System.out.println(“1”), followed by another this time printing
“12” and a third one printing “123”. However, if the last number increases as it moves to the
next row as in:
1
12
27
123
1234
12345
and so on then printing it manually is not recommended since you can accomplish it using a
single print method to print the number no matter how deep the number goes. Study the
program segment below:
int x,y;
for (x=1; x<=3;x++) //outer loop
for(y=1;y<=x;y++) // inner loop
System.out.print(y);
System.out.println(); /*forces the cursor to move to the next row when the inner
loop is
completed */
Analysis:
The outer loop is executed first with x having an initial value of 1. It then performs the
next loop where another variable is initialized to 1. This loop will terminate if the value of y is
greater than x. At this point, the statement inside the inner loop will only execute once since the
value of x is only 1 therefore printing the value of y which is also 1. The cursor does not go
down the next line. There is no {} that covers the two print methods therefore the second println
statement will be executed once the inner loops condition is satisfied. The outer loops value will
only increment once the inner loops condition is satisfied or completed.
Value of x Value of y
1 1
2 1
2
3 1
2
3
Therefore if you want to increase the number being produced by the loop, change the value of x
in the outer loop (changing it to 4 would display the output below).
1
12
123
1234
28
Laboratory Exercises
Using a nested loop, create a program that produces the following output:
a) 123 b) 321 c) 321 d) 3
12 32 21 32
1 3 1 321
29
Lesson 3:
Arrays and Strings
Overview:
This lesson covers arrays, strings and string methods.
Objectives:
To develop programs with array
To distinguish what string function to be used
30
ARRAY - a collection of elements having the same data type; array is an object.
Array declaration
int[] anintarray = new int[5]; //allocating 5 elements
or
int anintarray[] = new int[5]; //allocating 5 elements
Assignning values
Initialization
STRING
String (with a capital S) is one of the new datatype, but actually String is a class built in
to Java. The class String is defined in java.lang.String which is automatically imported into every
program you write.
31
Lets look at the following Java code:
Declaration
1 String strSample;
2 StrSample = new String("Hello");
OR
SAMPLE PROGRAM
/** StringDemo.java
*/
public class StringDemo
{
public static void main(String args[])
{
String str1="Hi!"; //declaration with initial value
System.out.println(str1);
str1 = "Hello"; //assigning new value
str1 = str1 + ",World!"; //assigning using concatenation
System.out.println(str1);
}
}//end StringDemo
Comparing Strings
1. equals() method – returns true only if two Strings are identical in content. Thus a String
holding “CSIT ” with a space after “T” is not equivalent to String holding “CSIT” with no space
after “T”
32
Ex.
String name1 = “kenshin”;
String name2 = “himura”;
if (name1.equals(name2))
System.out.println(“same name”);
else
System.out.println(“not the same name”); // result is false
//another example
if (name1.equals(“kenshin ”) //there’s a space after n
System.out.println(“same name”); //result is true
else
System.out.println(“not the same name”);
// last example
if (name1.equals(“KENSHIN”))
System.out.println(“same name”);
else
System.out.println(“not the same”); //result is false
33
10. indexOf() method – determines whether a specific character occurs within a String. If it
does, the method returns the position of the character. The value –1 is returned if the
character does not exist. Like array, positions begin at zero
Ex.
String name1=”KENSHIN”;
int pos =0;
pos = name1.indexOf('K');
System.out.println("position of K in KENSHIN is " + pos);
// output : position of K in KENSHIN is 0
// an example wherein there is more than 1 occurrence of the char being searched
pos = name1.indexOf(‘N’)
System.out.println(pos)
// result is 2. It only returns the position of the first occurrence
6. replace() method – allows you to replace all occurrences of some character within a String.
Ex.
String name1 = “kexshix”;
String name2;
name2 = name1.replace(‘x’,’n’);
System.out.println(name2);
//result is kenshin
//this method is also case-sensitive
34
Array of Strings
Declaration Initialization
String[] names = new String[4]; String[] names =
{"Beth","Mely","Pearl,"Arnie"};
Assigning Values
names[0] = "Beth"; or
.
. String names[] =
names[3] = "Arnie"; {"Beth","Mely","Pearl,"Arnie"};
Lesson 4 Exercises
I. Write the Java statement for the following.
1. Declare an array of integer named numbers allocating 10 elements
___________________________
2. Declare an array of integer named num2 with initial values 2,4,6,8,and 10
___________________________
3. Store the value 10 to the first index of the array used in number 1
___________________________
4. Declare an array of String named dbz allocating 4 elements
___________________________
5. Assign “gohan” to the first index of the array used in number 4
___________________________
6. Declare an array of String named jleague with values “Clark, Bruce and John”
___________________________
7. Display the value of the first index in array jleague
___________________________
8 Display all the values of array numbers (use a loop)
____________________
35
____________________
9-10. Increase all the values of array numbers by 1 then display the new values (use a loop)
____________________
____________________
____________________
Laboratory exercise
Given an array named n with values 33,2,70,4,52,42,8,35,9,211
Write a program that will :
a) Separate all odd from even numbers
b) Display the highest number (without sorting)
c) Display the lowest number (without sorting)
d) Sort the numbers in ascending order
Note: You are to write a separate program for every requirement displaying first the value of the
array. Assign your own class name and provide your own screen display.
36
Lesson 4
Using Methods
Overview:
This lesson covers methods and how to use them.
Objectives:
To know how declare methods
To utilize the different methods in the program
37
What is a method?
}//end class
Output:
Greetings from method greet()!
38
2. Return type
3. Method name
4. Parameter List
Some methods require additional information. If a method could not receive communications
from you, called arguments, then you would have to write an infinite number of methods to
cover every possible situation. For instance, if you design a method that squares numeric
values, it makes sense to design a square method that you can supply with an argument that
represents the value to be squared, rather than having to create method square1(), square2()
and so on. When you write the method declaration for a method that can receive an argument,
you need to include the following items within the method declaration parenthesis:
The type of argument
A local name for the argument
The example below is a class that contains a method that squares a number
*** The arguments you send to the method must match in both number and type the parameter
listed in the method declaration
Methods that require multiple arguments with no return value
A method can require more than one argument. You can pass multiple arguments to a method
by listing the arguments within the call to the method and separating them with commas. The
example below contains a method that accepts two integer values. The first argument
determines what operation to perform on the second argument. If the value of the first
argument is 1, the method will compute and display the square of the second argument. If the
39
value of the first argument is 2, the method will compute and print the cube of the second
argument. Any other value for the first argument will simply display the value of the second
argument
A method with or without argument can return a value. The return type for a method can be
any type used in Java which includes the int, double, char and so on. A method’s return
type can be identified through the method’s type.
Example:
public static int Status()
the return type for this method is int
The sample program below takes an integer value and returns an integer value. The method
returns 1 if the accepted value is an odd number and will return 0 if the accepted value is an
even number
40
public class Odd_even
{ public static void main(String[] args)
{ int x;
x= is_odd(5);//method call sending 5. x takes the returned value
if (x==1)
System.out.println(“The number is odd”);
else
System.out.println(“The number is even”);
}
public static int is_odd(int y)
{ if (y/2 * 2 == y)
return 0;
else
return 1;
}// end of method is_odd
}// end of class Odd_even
What we have learned and explored is a method called - class method. We need the
keyword static in order for Java compiler to know that the method we have created is a
class method. Class method/s are directly being invoked within a class it has been
defined by calling the method name or it can also be called by another class by calling
the classname preceded by a dot "." then preceded by the method name. An example is
given on the next page
/** FirstClass.java
* This program contains a class method.
* This demonstrates that the class method could be called
* from another class.
41
*/
/** SecondClass
*
*/
public class SecondClass
{
public static void main(String args[])
{
System.out.println("I summon greet of FirstClass");
FirstClass.greet();
}
}//end SecondClass
}//end FirstClass
Note:
FirstClass should be in bytecode, before SecondClass can use it. Therefore compile
FirstClass.java before compiling and running SecondClass.java
Illustration:
FirstClass SecondClass
greet(); FirstClass.greet();
//method call for greet at FirstClass method call for greet() being called at SecondClass
An array can be used as an argument to a method, thus permitting the entire array to be passed
to the method. To pass an array to a method, the array name must appear by itself without the
square brackets or subscripts, as an actual argument within the method call. When declaring
an array as an argument, the array name is written with a pair of square brackets before (after
the data type i.e int [] x) or after the array name (i.e int x[]). When an entire array is passed to a
method, any changes made in the array within the method makes its changes directly to the
original array that was declared in the main(). As shown in the example below, array x in main
42
contains the value 1,2,3 and 4.Before the method call, the contents of array x is printed. After
printing the values, the entire array is passed to method pass_array (line 8). Within the method
pass_array, all values are increased by 1 making the values 2,3,4 and 5 then displaying them.
After the method call, the values of the array is again printed at the main().
Method Overloading
Overloading involves using one term to indicate diverse meanings. When you overload a Java
method, you write multiple methods with a shared name. The compiler understands your
meaning based on the arguments you use with the method. An example of method overloading
is provided below.
/** File name: MySecond
Version : 2
*/
public class MySecond
{
public static void main(String args[])
{ greet(); //invoke method greet()
greet(5); //invoke method greet(with argument int)
double z=greet(6.0); //invoke method greet(with argument int);
System.out.println(z);
}// end main
43
public static void greet(int x) //no parameter function need no "void"
{ int i;
for(i=1;i<=x;i++)
System.out.println("Greetings #" + i + " from method greet(with argument)!");
}//end greet()#2
Activities:
I. Write the proper method declaration/ method call for the following
1. A method named CS that does not accept and does not return a value
____________________________________
2. Call the method in number 1
____________________________________
3. A method named IT that does not accept but returns an integer value
____________________________________
4. Call method IT
____________________________________
5. A method named CSIT that accepts an integer and returns a character
____________________________________
6. A method named CCMIT that accepts two integers and returns a double
____________________________________
Laboratory exercises
1. Create a class whose main() holds two integer variables. Assign values to the variables.
Create two methods named sum() and difference, that compute the sum and difference
between the two variables respectively. Each method should perform the computation and
44
display the results. In turn, call the two methods passing the values of the 2 variables. Create
another method named product. The method should compute the product of the 2 numbers but
will not display the answer. Instead, the method should return the answer to the calling main()
which displays the answer. Provide your own screen display and class name.
2. Create a class whose main() holds an array containing 10 integers. Create two methods that
accepts the array. The first method named lowest returns the lowest from the 10 numbers while
the second method named highest returns the highest number from the list. Determine the
highest and lowest number without sorting the numbers. Your output should contain the original
list of numbers, the highest and the lowest number from the list. Supply the necessary values
for the array
3. Create a class named Commission that includes 3 variables: a double sales figure, a double
commission rate and an integer commission rate. Create 2 overloaded methods named
computeCommission(). The first method takes 2 double arguments representing sales and rate,
multiplies them and then displays the results. The second method takes 2 arguments: a double
sales figure and an integer commission rate. This method must divide the commission rate by
100.0 before multiplying by the sales figure and displaying the commission. Supply appropriate
values for the variables. Test each overloaded methods
45
Lesson 5
Creating Classes and Objects
Overview:
This lesson covers the classes and objects, how to create and use them
Objectives:
To understand the use and purpose of classes and objects in the program
To create programs with classes and objects
46
What is a class?
Class is a concept or anything abstract. It is a collection of variables, objects and sub-
classes.
Instance is an image, therefore all of a attributes of the class will be inherit by the
instantiated object.
It is said earlier that a class can contain a sub-class, example: an automobile has a fuel
gauge, a temperature gauge, a speedometer all of these are objects of class - measuring
device which is a part of a super class automobile.
A Complete Class
In order for us to say it is a complete class it should have a state and behavior.
example:
A Class dog has a state - breed, age
The same Class dog should have a behavior like- barking, eating, sleeping, playing.
These real-world objects share two characteristics: they all have state and
they all have behavior. For example, dogs have state (breed and color) and
dogs have behavior (barking, sleeping and slobbering on your newly cleaned
slacks). Bicycles have state (current gear, current pedal cadence, two
wheels, number of gears) and behavior (braking, accelerating, slowing down,
changing gears).
Software objects are modeled after real-world objects in that they, too, have
state and behavior. A software object maintains its state in variables and
implements its behavior with methods – methods are sub-routines,
procedures or functions in other programming languages.
Creating a class
When you create a class, first you must assign a name for that class and then you must
determine what data and methods will be part of the class. Suppose you want to create a class
named Mystudent. One instance variable of Mystudent might be age and two necessary
47
methods might be a method to set (or provide a value) the student’s age and another method to
retrieve the age( see Instance methods). To begin, you create a class header with three parts:
An optional access modifier
The keyword class
Any legal identifier you choose for the name of the class
Ex.
public class Mystudent
The keyword public is a class access modifier. Other access modifiers that can be used when
defining a class are final or abstract. Public classes are accessible by all objects, which means
that public classes can be extended or used as a basis for any other class. After writing the
class header public class Mystudent, you write the body of the Mystudent class, containing its
data and methods between a set of curly brackets
Ex.
public class Mystudent
{
// instance variables and methods are placed here
}
You place the instance variables or fields for the Mystudent class as statements within the curly
brackets
public class Mystudent
{
int age = 18; // variable with no access modifier is public by default
// other methods go here
}// end of class Mystudent
The allowable modifiers are private, public,friendly, protected, static and final. Private access
means no other classes can access a fields values and only methods of the same class are
allowed to set, get or otherwise use private variables. Private access is sometimes called
information hiding, and is an important component of object-oriented programs. A class’
private data can be changed or manipulated only by a class’ own methods and not by methods
that belong to other class. In contrast, most class methods are not usually private.
Instance Methods
Besides data, classes can contain methods. In the Mystudent class for example, you could
write a method that contains two methds : One to set the student’s age (named below as
AlterAge) and another to retrieve the student’s age (named GetAge).
Ex.
public class Mystudent
{ int age=18;
void AlterAge(int n) /* method with no access modifier is public by default */
48
{ age = n;
} //end of method AlterAge()
public void GetAge()
{ return age;
}
}//end of class Mystudent
The methods in the above example do not contain the keyword static. The keyword static is
used for classwide methods but not for methods that belong to objects. If you are creating a
program with main() that you will execute to perform some task then most of your methods will
be static so you call them within the main(). However if you are creating a class from which
objects will be instantiated, most methods will be nonstatic as you will be associating the
methods with individual objects. Methods used with object instantiations are called instance
methods.
Declaring Objects
Declaring a class does not create an actual object. A class is just an abstract of what an object
will be like if any objects are actually instantiated. You can create a class with fields and
methods long before you instantiate any objects that are members of that class. A two-step
process creates an object that is an instance of a class. First, you supply a type and an
identifier just as when you declare any variable and then you allocate memory for that object.
To allocate the needed memory, you must use the new operator.
Ex: Mystudent Loyda; //declaring an object Loyda
Loyda = new Mystudent(); // initializing an object to have a
memory location
You can also define and reserve memory in one statement as in:
Mystudent Loyda = new Mystudent();
In the previous example, Mystudent is the object’s type(as well as its class) and Loyda is the
name of the object. The equal sign is the assignment operator, so a value is being assigned to
object Loyda. The new operator is allocating a new, unused portion of computer memory for
object Loyda. The value that the statement is assigning to Loyda is a memory address at which
it is to be located. The last portion of the statement Mystudent() is the name of a method that
constructs Mystudent object. Mystudent() is a constructor method. A constructor method is a
method that establishes an object. When you don’t write a constructor method for a class
object, Java writes one for you and the name of the constructor method is always the name of
the class whose objects it constructs. The complete program is written below. (more of
constructors on the next lesson)
49
/** Program : MyStudent.java
Description : This program contains instance methods
that can be instanciated to other class
*/
/** StudentKo.java
This program will instanciate the attributes of Mystudent.class
*/
public class StudentKo
{
public static void main(String args[])
{
int studentAge;
MyStudent Loyda; // declaring an object
Loyda = new MyStudent(); // initializing an object to have a memory location
/* or MyStudent Loyda = new MyStudent(); */
studentAge= Loyda.age;
System.out.println("Before: age is "+studentAge);
Loyda.AlterAge(19);
studentAge=Loyda.getAge();
System.out.println("After: age is "+studentAge); Before: age is 18
} After: age is 19
}//end class StudentKo
***************************************************************************
//Example #2
//Class name Sample2.java
public class Sample2
{ String lname,fname,job;
int age;
public void setLastname(String last)
{ lname=last; }
50
public void setJob(String trabaho)
{ job = trabaho; }
// Instance of Sample2
// Class name I_sample2.java
public class I_sample2
{ public static void main(String args[])
{ String lastname,firstname,work;
int gulang;
Sample2 student = new Sample2();
student.setLastname("Himura"); //line 6
student.setFirstname("Kenshin"); //line 7
student.setAge(27); //line 8
student.setJob("Slasher"); //line 9
lastname = student.getLastname();
firstname = student.getFirstname();
work=student.getJob();
gulang = student.getAge();
System.out.println("Name : " + lastname + ", " + firstname);
System.out.println("Age : " + gulang);
System.out.println("Job : " + work);
}
}
Programming Activity
1.
Key-in the program Sample2.java and I_sample2.java
Compile the 2 programs
Run I_sample2
Take note of the output
51
Try to put a comment on lines 6-9 on the program I_sample2 then compile and run
the program
Take note of the new output. The output will be discussed in the next lesson
(overloading constructors)
ANSWERS:
52
CLASS
instance variable#1
class variable#1
instance m ethod#1
instance m ethod#2
class method#1
OBJECT#1
OBJECT#2
instance variable#1
instance variable#1
instance m ethod#1
instance m ethod#2 instance m ethod#1
instance m ethod#2
/** StudRec.java
*/
53
{
Student iskulmateko = new Student();
Student iskulmateniya = new Student();
int i=iskulmateniya.fetchschoolcode();
System.out.println("SC ni iskulmatenya: "+i);
iskulmateniya.changeschoolcode(14344);
int j=iskulmateko.fetchschoolcode();
System.out.println("SC ni iskulmateko: "+j);
}
}//end class StudRec
Laboratory Exercises
1. a . Create a class named Pizza. Data fields include String for toppings (such as
“pepperoni”), an integer for diameter in inches (such as 12) and double for price (as in
13.99). Include methods to get and set values for each of these fields
b. Create a class named TestPizza that instantiates one Pizza object and demonstrates
the use of the Pizza set and get methods.
2. Write a program that displays the employees Ids together with their first and last names.
Use two classes. The first class contains the employee data and separate methods to
set and get the ID’s and names. The other class creates objects for the employees and
uses the objects to call the methods. Create several employees and display their data
3. a. Create a class named Circle with fields named radius, area and diameter. Include
methods names setRadius(), getRadius(), computeDiameter() which computes a
circles’s diameter and computeArea which computes a circle’s area. The diameter of a
circle is twice its radius and the area is 3.14 multiplied by the square of the radius.
b. Create a class named TestCircle whose main() declares three Circle objects. Using
the setRadius() method, assign one circle a small radius value. Assign another circle a
larger radius value and assign the third circle a radius of 1. Call computeDiameter() and
computeArea() for each circle and display the results.
54
Lesson 6
Overloading Constructors
Overview:
This lesson covers constructors and how they work
Objectives:
To understand the purpose of constructor
To create a program with constructors
To gain knowledge about overloading constructors
55
Constructor Methods
A constructor method is a method that is called on an object when it is created – in other words,
when it is constructed. Unlike other methods, a constructor cannot be called directly. Instead,
Java calls constructor methods automatically. Java does 3 things when new is used to create
an instance of a class:
Allocates memory for objects
Initializes the objects instance variables either to initial values or to a default (0 for
numbers, null for objects, false for Booleans or ‘\0’ for characters)
Calls the constructor method of the class which might be one of several methods
If a class does not have constructor methods defined, an object is still created when the new
statement is used in conjunction with the class. However, you might have to set its instance
variables or call other methods that the object needs to initialize itself. By defining constructor
methods in your own classes, you can set initial values of instance variables, call methods
based on those variables, call methods on other objects and set the initial properties of an
object.
In the previous lesson we created a class named Sample2 and instantiated an object with the
statement:
Sample2 student = new Sample2();
you are actually calling a method named Sample2() that is provided by the Java compiler. A
constructor method establishes an object. The constructor method named Sample2 establishes
one Sample2 with the identifier student and provides the following initial values to Sample2’s
data fields: (recall programming experiment #1 in the previous lesson)
numeric fields are set to 0
The object type fields are set to null
If you do not want Sample2s fields to hold these default values, or if you want to perform
additional task when you create Sample2 then you write your own Constructor method. Any
constructor method you write must have the same name as the class it constructs and
constructor methods cannot have return type . An edited version of the class Sample2 is
provided on the next page.
56
Sample2() //constructor method containing initial values
{
lname="Xavier";
fname="Charles";
job="Professor";
age=60;
}
Now examine the program below. It no longer calls the setAge(),setLastname(), setFirstname()
and setJob() methods.
57
System.out.println("Name : " + lastname + ", " + firstname);
System.out.println("Age : " + gulang);
System.out.println("Job : " + work);
}
}
Sending Arguments to Constructors
Examine the program below
//class name Sample3.java
public class Sample3
{
int id;
Notice the constructor method contains an int argrument named emp_id. Once you instantiate
Sample3, you have to pass an integer value to the constructor as shown in the program below
In Sample3 class, instance method getId() returns the employee ID. You can display the
returned value in two ways. First is to directly print the result as shown in the 3
System.out.println statement above. The second is to assign a variable that will accept the
returned value of the method getId as shown below
int id1;
Sample3 test1 = new Sample3();
id1 = test1.getId(); System.out.println(“Employee id # “ + id1);
58
the employee ID , age and department. The constructor method of this class initializes an
employee’s ID number to 999, his/her age to 21 and department name as “Floating”. Once you
instantiate this class you have to send 3 arguments in order to replace the initial values
assigned to it. The program for this problem is shown below
output
//class name I_sample4.java
Employee ID : 1234
//Instance of Sample4 class
Age : 25
public class I_sample4
Department : Payroll
{ public static void main(String[] args)
{
Employee ID : 5678
Sample4 employee1 = new Sample4(1234,25,"Payroll");
Age : 30
System.out.println("Employee ID : " + employee1.getId());
Department : Human
System.out.println("Age : "+ employee1.getAge());
Resources
System.out.println("Department : " + employee1.getDept()+"\n");
?In I_sample3 and I_sample4 programs, arguments were sent to the constructors when the
objects were created. What happens if you do not include an argument to both constructors?
Ex. Sample3 test1 = new Sample3(); and Sample4 employee1 = new Sample4();
59
Symbol : Constructor Sample3 ()
Location : class Sample3
{ Sample3 test1 = new Sample3();
^
Overloading Constructors
If you create a class from which you instantiate objects, Java automatically provides you with a
constructor. Unfortunately, if you create your own constructor, the automatically created
constructor no longer exists. Therefore, once you create a constructor that takes an argument,
you no longer have the option of using the constructor that requires no arguments.
Fortunately, as with other methods, you can overload constructors. Overloading constructors
provides you with a way to create objects with or without initial arguments, as needed. For
example, you can create a class that contains a constructor method with no arguments but
contains initial values for the variables and another constructor method that accepts an
argument/arguments so you can set new values. When both constructor reside within the class,
you have the option of creating an object with or without an initial value. Analyze the program
below.
/*Class that contains multiple constructor methods each receiving different number of
arguments*/
public class Sample5
{ int stud_no,age;
String course;
60
{ return age;}
The constructor with no argument is called. The complete program is shown below
61
Laboratory Exercises
1. a .Create a class named Circle with fields named radius, area and diameter. Include a
constructor method that sets the radius to 1. Also, include methods named setRadius(),
getRadius(), computeDiameter() which computes a circle’s diameter and computeArea which
computes a circles area (The diameter of a circle is twice its radius and the area is 3.14
multiplied by the square of the radius.
b. Create a class named TestCircle whose main() method declares 3 Circle objects. Using
the setRadius() method, assign one circle a small radius value and assign another circle a
larger radius value. Do not assign a value to the radius of the 3 rd circle; instead, retain the value
assigned at the constructor. Call computeDiameter() and ComputeArea() for each circle and
display the results. Provide your own screen display.
2.Create a class named House that includes data fields for the number of occupants and the
annual income as well as methods named setOccupants(), setIncome(), getOccupants() and
getIncome() that set and return those values respectively. Additionally, create a constructor that
requires no arguments and automatically sets the occupants field to 1 and income field to 0.
Create an additional overloaded constructor . This constructor receives an integer argument
and assigns the value to the occupants field. Create a third overloaded constructor this time,
the constructor receives 2 arguments, the values of which are assigned to the occupants and
income fields respectively. Create another class named I_house that instantiates the House
class and see if the constructors work correctly.
62
Lesson 7
Using Prewritten Classes and Methods
Overview:
This lesson covers some of the prewritten classes and methods of Java language
Objectives:
To know the different prewritten classes and methods
To construct programs with that prewritten classes and methods
63
Using Automatically Imported, Prewritten Constants and Methods
There are nearly 500 classes available for you in Java. You already used several of the
prewritten classes without being aware of it. System, Character, Boolean, Byte, Short, Long,
Float and double are actually classes from which you create objects. These classes are stored
in a package, which is simply a folder that provides a convenient grouping of classes, which is
sometimes called library of classes. There are many Java packages containing classes that
are available only if you explicitly name them within your program but the group of classes that
contains the previously listed classes is used so frequently that it is available automatically to
every program you write. The package that is implicitly imported into every Java program is
named java.lang. The classes it contains are the fundamental classes, or basic classes as
opposed to the optional classes that must be explicitly named.
The class java.lang.Math contains constants and methods that you can use to perform
common mathematical functions. Commonly used constant is PI. Within the Math class, the
declaration for PI is public final static double PI = 3.141592653589793. PI is :
public so any program can access it
final so it cannot be changed
static so only one copy exists
double so it holds a large floating-pt value
all of the constants and methods in the Math class are static, which means they are class
variables and methods. Some of the common Math class methods are listed below.
Method Meaning
abs(x) Absolute value of x
acos(x) Arcosine of x
asin(x) Arcsine of x
atan(x) Arctangent of x
ceil(x) Smallest integral value not less than the
ceiling
cos(x) Cosine of x
exp(x) Exponent
Methods Meaning
floor(x) Largest integral value not greater than x
log(x) Natural logarithm of x
64
max(x,y) Larger of x and y
min(x,y) Smaller of x and y
pow(x,y) X raised to the y power
random() Random double no between 0.0 and 1.0
round(x) Closest integer to x( where x is a float and
the return value is an integer or long
sin(x) Sine of x
sqrt(x) Square root of x
tan(x) Tangent of x
Because all constants and methods in the Math class are classwide, there is no need to create
an instance. You cannot instantiate objects of type Math because the constructor for the Math
class is private and your programs cannot access the constructor.
Only few of the classes such as java.lang – are included automatically in the programs you
write. To use any of the other prewritten classes, you can use any of the following:
use the entire path with the class name
import the class
65
import the package of which the class you are using is a part
For example, the java.util class package contains useful methods that deal with dates and time.
Within this package, a class named Date is defined. You can instantiate an object of type Date
from this class by using the full class path as in:
java.util.Date date2day = new java.util.Date(); //first bullet above
alternatively, you can shorten the declaration of date2day to :
Date date2day = new Date();
by including the statement :
import java.util.Date; //second bullet above
as the first line in your program. An import statement allows you to abbreviate the lengthy class
named by notifying the Java program that when you use Date, you mean the java.util.Date
class. You must place any import statement you use before any executing statement in your
program.
An alternative to importing a class is to import an entire package of classes. You can use the
asterisk (*) as a wildcard symbol to represent all the classes in a package. Therefore, the
import statement :
import java.util.*; // third bullet
imports the Date class and any other java.util classes as well.
The Date class has several constructors. For example, if you construct a Date object with 5
integer arguments, they become the year, month, day, hour and minutes. A Date object
constructed with 3 arguments assumes the arguments to be the year, month and day and the
time is set to midnight. The Date class contains a variety of other useful methods such as
setMonth(), getMonth(), setDay, getDay(), setYear() and getYear();
import java.util.*; output :
public class DateClass My birthday is Sat Nov 01 00:00:00 CST 2003
{ public static void main(String[] args) Todays date is Wed Apr 30 15:03:39 CST 2003
{ Date date2day = new Date(); The month is 3
Date datebukas = new Date(); The date is 30
The day is 3
Date bdayko = new Date(103,10,1); The year is 103
System.out.println("My birthday is " + bdayko); Tomorrow is Thur May 01 15:11:05 CST 2003
System.out.println("Todays date is " + date2day);
System.out.println("The month is " + date2day.getMonth());
System.out.println("The date is " + date2day.getDate());
System.out.println("The day is " + date2day.getDay());
System.out.println("The year is " + date2day.getYear());
datebukas.setDate(date2day.getDate() +1);
System.out.println("Tomorrow is " + datebukas);
}
}
66
The getMonth() method returns the number of months not the actual month. January is 0,
February is 1 and so on. getDate() returns the current date while getDay() returns the current
day in numbers. 1 is Mon, 2 is Tue and so on. The getYear() method returns the year but is
1900 less than the current year. Therefore 82 means 1982 and 103 means 2003. To correct
the year displayed, edit the program and add 1900 to the getYear() as in:
System.out.println("The year is " + date2day.getYear()+1900));
This will now display the year as :
The year is 2003
You can perform arithmetic using dates. In the last line in the output, which displays the date on
the following day, you just add the number of days to calculate the next date.
datebukas.setDate(date2day.getDate() +1);
The compiler will interpret an incorrect date such as April 31 as being May 1.
Laboratory Exercises
2.Write a program to calculate how many days it is from today until the current year
3. Write a program to determine how many days it is from today until your next birthday
67
Lesson 8:
Using Frames
Overview:
This lesson covers basic graphical user interface (GUI) components
Objectives:
To know the different GUI components
To utilize GUI components in the program
68
Graphical User Interface Components
GUIs are built from GUI components (sometimes called controls or widgets (window gadgets)).
A GUI component is an object which the user interacts via mouse, the keyboard or another form
of input
Component Description
JLabel An area where uneditable text or icons can be
displayed
JTextField An area in which the user inputs data from the
keyboard. The area can also display an
information
JButton An area that triggers an event when clicked
JCheckBox A GUI component that is either selected or not
selected
JComboBox A drop-down list of items from which the user can
make a selection by clicking an item in the list or
possibly by typing into the box
JList An area where a list of items is displayed from
which the user can make a selection by clicking
once on any element in the list. Double-clicking
an element in the list generates an action event.
Multiple elements can be selected
JPanel A container in which components can be placed
Swing Overview
The classes that create the GUI components are part of the Swing GUI components from the
package javax.swing. Most swing components are written, manipulated and displayed
completely in Java. The original GUI components form the Abstract Windowing Toolkit package
are tied directly to the local platform’s graphical user interface capabilities. When a Java
program with an AWT GUI executes on different Java platforms, the program’s GUI components
display differently on each platform. The appearance and how the user interacts with the
program are known as the program’s look and feel. Swing enables programs to provide a
custom look and feel for each platform or even to change the look and feel while the program is
running. Swing components are often referred to as lightweight components – they are written
69
completely in Java so they are not “weighed down” by the complex GUI capabilities of the
platform on which they are used. AWT components (many of which parallel the swing
components) that are tied to the local platform are correspondingly called heavyweight
components – they rely on the local platform’s windowing system to determine their
functionality and their look and feel. Each heavyweight component has a peer (from package
java.awt.peer) that is responsible for the interactions between the component and the local
platform that display and manipulate the component. Several Swing components are still
heavyweight components. In particular, subclasses of java.awt.Window (such as JFrame ) that
display windows on the screen and subclasses of java.applet.Applet (such as JApplet) still
require direct interaction with the local windowing system. As such, heavyweight Swing GUI
component are less flexible than many of the lightweight components.
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
The figure above shows an inheritance hierarchy of the classes that define attributes and
behaviors that are common to Swing components. Each class is displayed with its fully qualified
package name and class name. Much of each GUI component’s functionality is derived from
these classes. A class that inherits form the Component class a component. For example,
class Container inherits from class Component, and class Component inherits from Object.
Thus, a Container is a Component and is an Object, and a Component is an Object. A class
that inherits from class Container is a Container. Thus a Jcomponent is a Container.
Class Component defines the common attributes and behaviors of all subclasses of
Component. With few exceptions, most GUI components extend class Component directly or
indirectly.
A Container is a collection of related components. In application with JFrames an in
applets, we attach components to the content pane, which is an object of class Container.
Class Container defines the common attributes and behaviors for all subclasses of Container.
One method that originates in class Container is add for adding components to a Container.
70
Another method that originates in class Container is setLayout, which enables a program to
specify the layout manager that helps a Container position and size its components.
//This program demonstrates the use of JFrame
//Jframedemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Jlabel
Labels provide text instructions or information on a GUI. Labels are defined with class JLabel –
a subclass of JComponent. A label displays a single line of read-only text, an image or both text
and an image. A program demonstrating the use of Jlabel is provided below
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
71
16 Icon iconglobe = new ImageIcon("globe.gif");
17 label2 = new JLabel("Label with text and icon",iconglobe,SwingConstants.LEFT);
18 c.add(label2);
19 //JLabel with no arguments
20 label3 = new JLabel();
21 Icon iconpaint = new ImageIcon("painting.gif");
22 label3.setText("Label with icon and text at bottom");
23 label3.setIcon(iconpaint);
24
label3.setHorizontalTextPosition(SwingConstants.CENTER);
25 label3.setVerticalTextPosition(SwingConstants.BOTTOM);
26 c.add(label3);
27 setSize(400,300);
28 setVisible(true);
29 }//end of constructor
30 public static void main(String args[])
31 { Labeldemo testlabel = new Labeldemo("JLabel demo");
32 testlabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
33 }// end of main
34 }//end of class
The program declares three Jlabels (line 5). The JLabel objects are instantiated in the
Labeldemo constructor . Line 12 creates a JLabel object with a text “Label with text”. The label
displays this text when the label.
Line 13 uses method setToolTipText (inherited into class JLabel from class
JComponent) to specify the tooltip (see output on the right side) that is displayed automatically
when the user positions the mouse over the label in the GUI. Line 14 adds label1 to the content
pane.
Several Swing components can display images by specifying an Icon as an argument to
either constructor by using a method that is normally called setIcon. An Icon is an object of
any class that implements interface Icon (package javax.swing). One such class is
ImageIcon(package javax.swing), which supports several image formats, including Graphics
Interchange Format(GIF), Portable Network Graphics (PNG) and Joint Photographic Experts
Group(JPEG). Line 16 and Line 21 defines an ImageIcon object. The file “globe.gif” and
“painting.gif” contains the image to load and store in the ImageIcon object. This file is assumed
to be in the same directory as the program. The ImageIcon object is assigned to Icon to
reference iconglobe and iconpaint. Remember, class ImageIcon implements interface Icon,
therefore, ImageIcon is an Icon.
Class JLabel supports the display of icons. Line 17 uses another JLabel constructor to
create a label that displays the text “Label with text and icon” and the Icon to which the
iconglobe refers and is left justified. Interface SwingConstants (package javax.swing) defines
72
a set of common integer constants (such as SwingConstants.LEFT) that are used with many
Swing components. By default, the text appears to the right of the image when a label contains
both text and an image. The horizontal and vertical alignments of a label can be set with
methods setHorizontalTextPosition and setVerticalTextPosition respectively.
Class JLabel provides many methods to configure a label after it has been instantiated.
Line 20 creates a JLabel and invokes no argument. Such a label has no text or Icon. Line 22
uses method setText to set the text displayed on the label. Line 23 uses method setIcon to set
the icon displayed on the label. Line 24 and 25 uses methods setHorizontalTextPosition
and setVerticalTextPosition to specify the text position in the label. Thus, the icon will appear
above the text.
JButton
A button is a component that the user clicks to trigger a specific action. A Java program can
use several types of buttons including command buttons, checkboxes, toggle buttons and radio
buttons. A command button generates an ActionEvent when the user clicks the button.
Command buttons are created with class JButton, which inherits from class AbstractButton.
Button Hierarchy
javax.swing.Component
javax.swing.AbstractButton
javax.swing.JButton javax.swing.ToggleButton
javax.swing.JCheckBox javax.swing.JRadioButton
A program demonstrating the use of JButton is presented below. Like JLabels, JButton
supports the display of icons. Two buttons are created in the program. The buttons are labeled
“plain” and “fancy”. The fancy button is defined with an icon on it. (line 9). To provide the user
with an extra level of visual interactivity with GUI, JButton can also have a rollover Icon – an
icon that is displayed when the mouse is positioned over the Button. The icon on the button
changes as the mouse moves in and out of the button’s area on the screen. Line 14 sets the
rollover icon to “globe” using setRollOverIcon() (inherited from AbstractButton into class into
JButton). Event handling for the button is performed by a single instance of inner class
Bhandler (defined at line 23-28).
73
// Program that demonstrates the use of JButton
//Jbuttondemo.java
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 public class Jbuttondemo extends JFrame
5 {
6 JButton btn1 = new JButton("Plain");
7 Icon iconheart = new ImageIcon("heart.jpg");
8 Icon iconglobe = new ImageIcon("globe.gif");
9 JButton btn2 = new JButton("Fancy",iconheart);
10 Jbuttondemo(String x)
11 { super(x);
12 Container c = getContentPane();
13 c.setLayout(new FlowLayout());
14 btn2.setRolloverIcon(iconglobe);
15 c.add(btn1);
16 c.add(btn2);
//create an instance of inner class Bhandler to use
for button event handling
17 Bhandler clicked = new Bhandler();
18 btn1.addActionListener(clicked);
19 btn2.addActionListener(clicked);
20 setSize(400,300);
21 setVisible(true);
22 }//end of constructor
//inner class for button event handling
23 private class Bhandler implements ActionListener
24 {
25 public void actionPerformed(ActionEvent y)
26 { JOptionPane.showMessageDialog(null,"You pressed "+
y.getActionCommand());
27 }//end of actionperformed()
28 }//end of class bhandler
29 public static void main(String args[])
30 { Jbuttondemo test = new Jbuttondemo("Jbutton demo program");
31 test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
32 } //end of main
33 } //end of class jbuttondemo
74
that are grouped together and only one of the JRadioButtons in the group can be selected at
any point.
//This program demonstrates the use of JCheckbox
//Jcheckboxdemo.java
1 import javax.swing.*;
2 import java.awt.event.*;
3 import java.awt.*;
75
44 // for italic checkbox events
45 if (y.getSource()==italic)
46 if(y.getStateChange()==ItemEvent.SELECTED)
47 valItalic = Font.ITALIC;
48 else
49 valItalic = Font.PLAIN;
50 // set text to whatever is clicked
51 jtxt1.setFont(newFont("TimesRoman",valBold+valItalic,14));
52 } //end of itemstatechanged
53 } //end of checkhandler
52 public static void main(String args[])
53 { Jcheckboxdemo demo = new Jcheckboxdemo("Checkbox demo program");
54 demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
55 } //end of main
56 } //end of class jchekcboxdemo
The program uses two checkbox objects to change the font style of the text displayed in
the textfield and an exit button. One checkbox applies a bold style when selected and the other
applies an italic style when selected. If both are selected, the text in the textfield becomes bold
and italized. Line 6 creates an object for JTexfField. Line 7-8 creates a checkbox labeled Bold
and Italic respectively. When the user checks an item in the checkbox, an ItemEvent occurs
that can be handled by an ItemListener. In the program above, the event handling is performed
by an instance inner class Checkhandler (click, line 19) and register it with method
addItemListener (line 33) as the item for both bold and italic checkboxes.
Radio Buttons (defined with class JRadioButton) are similar to checkboxes in that they have
two states – selected or not selected (also called deselected). The logical relationship between
radio buttons is maintained by a ButtonGroup object (package javax.swing). The
ButtonGroup itself is not a GUI component. Therefore, a ButtonGroup object is not displayed
in a user interface. Rather, the individual JRadioButton objects from the group are displayed in
the GUI. (Adding a ButtonGroup object to a container is a syntax error).
76
10 //create radio buttons
11 private JRadioButton male=new JRadioButton("Male",true);
12 private JRadioButton female = new JRadioButton("Female",false);
13 public Jradiodemo(String x)
14 { super(x);
15 Container c = getContentPane();
16 c.setLayout(new FlowLayout());
17 c.add(jlblgender);
18 c.add(jtxt1);
19 c.add(male);
20 c.add(female);
21 //create logical relationship between radio buttons
22 jtxt1.setEditable(false);
23 gendergroup.add(male);
24 gendergroup.add(female);
25 c.add(jbtnclose);
26 //register events for close button
27 Buttonhandler btnexit = new Buttonhandler();
28 //register events for radio buttons
29 Radiohandler optionclick = new Radiohandler();
30 jbtnclose.addActionListener(btnexit);
31 male.addItemListener(optionclick);
32 female.addItemListener(optionclick);
33 setSize(300,300);
34 setVisible(true);
35 } //end of constructor
36 //process close button
37 private class Buttonhandler implements ActionListener
38 { public void actionPerformed(ActionEvent a)
39 { dispose();System.exit(0);}
40 } //end of buttonhandler
Line 9 instantiates a ButtonGroup object and assigns it to reference gendergroup. This object is
the “glue” that binds the 2 radio button objects together. Class Radiohandler (lines 41-48)
77
implements interface ItemListener so it can handle item events generated by the JRadioButtons.
Each radio button in the program has an instance of this class (optionclick) registered as its
ItemListener.
JComboBox
A combo box (sometimes called drop-down list) provides a list of items to be displayed from
which the user can make a selection. Combo boxes are implemented with class JComboBox,
which inherits from class JComponent. JcomboBoxes generate ItemEvents like JCheckBox and
JRadioButton.
//This program demonstrates the use of JComboBox
//Jcombodemo1.java
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 public class Jcombodemo1 extends JFrame
5 { private String list[] = {"Colossus","Nightcrawler","Storm","Gambit","Prof. X"};
6 //list above will be placed in the combo box
7 private JComboBox xmen = new JComboBox(list);
8 private JTextField txt1 = new JTextField(15);
9 private JLabel lbl1 = new JLabel("Given Name");
10 public Jcombodemo1(String x)
11 { super (x);
12 Container d = getContentPane();
13 d.setLayout(new FlowLayout());
14 d.add(lbl1);
15 d.add(txt1);
16 d.add(xmen);
17 txt1.setEditable(false);
18 xmen.setMaximumRowCount(3);//set the rows to
3 when the
//list appears
19 // setup jcombo box and register its event
20 Listhandler showlist = new Listhandler();
21 xmen.addItemListener(showlist);
22 setVisible(true);
23 setSize(300,300);
24 } //end of container
25 //inner class to handle combo box events
26 private class Listhandler implements ItemListener
27 { public void itemStateChanged(ItemEvent a)
28 { int b = xmen.getSelectedIndex();
29 if (b==0) //if first option in the list is clicked
30 txt1.setText("Vladimir Rasputin");
31 else if (b==1)
32 txt1.setText("Kurt Wagner");
33 else if (b==2)
34 txt1.setText("Ororo Monroe");
35 else if (b==3)
78
36 txt1.setText("Remy Lebeau");
37 else
38 txt1.setText("Charles Xavier");
39 }//end if
40 } //end listhandler
In the program, the options in the combo box is placed in an array of String called
list(line 5). Line 7 creates a JComboBox object, using the Strings in array “list” as the elements
in the list. A numeric index keeps track of the ordering of items in the combo box. The first
item is at index 0, the next item is at index 1 and so on. The first item added to the combo box
appears as the currently selected item when the combo box is displayed.
Other items are selected by clicking the combo box. When clicked, the combo box
expands in a list from which the user can make a selection. Line 18 uses JComboBox method
setMaximumRowCount to set the maximum number of elements that are displayed when the
user clicks the combo box. If there are more items in the combo box than the maximum number
of elements that are displayed, the combo box automatically provides a scrollbar.
When the user makes a selection from the list, method itemStateChanged (lines 27-40)
sets the text in the textfield based on the option selected.
79
14 c.setLayout(new FlowLayout());
15 iconcombo.setMaximumRowCount(3);
16 Combohandler display = new Combohandler();
17 c.add(iconcombo);
18 iconcombo.addItemListener(display);
19 c.add(lbl);
20 setSize(400,400);
21 show();
22 }//end of constructor
23 private class Combohandler implements ItemListener
24 { public void itemStateChanged(ItemEvent a)
25 { if (a.getStateChange()==ItemEvent.SELECTED)
26 lbl.setIcon(icons[iconcombo.getSelectedIndex()]);
27 }
28 } //end of combohandler
29 public static void main(String args[])
30 { Jcombodemo test = new Jcombodemo("Jcombo box demo with icons");
31 test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
32 }//end of main
33 } //end of class jcombodemo
The program is another example of a combo box that provides a list of four image file names.
When an image file is selected, the corresponding image is displayed as an icon on a JLabel.
Line 7 declare and initialize an array icons with four new ImageIcon objects. String array
“iconlist” (line 6) contains the names of the four image files. When the user makes a selection
from the images, method itemStateChanged sets the Icon for Label. The icon is selected from
array “icons” by determining the index number of the selected item in the combo box with the
method getSelectedIndex.
The last 2 frame below shows the 2 items selected from the list
Another version of the program above is presented below. This program does not use array for
the icons. The output is similar to the output above.
80
//This program demostrates the use of Jcombo box without using //array for the icons
// Jcombodemo2.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
81
JList
A list displays a series of items from which the user may select one or more items. Lists are
created with class JList, which inherits from class JComponent. Class JList supports single-
selection lists (lists that allow only one item to be selected at a time) and multiple-selection lists
(lists that allow any number of items to be selected)
82
41 { Jlistdemo1 testlist = new Jlistdemo1("Jlist demo");
42 testlist.show();
43 testlist.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
44 } // end of main
45 } //end of class Jlistdemo
A Jlist object is instantiated at line 9 and assign to reference “xmen” in the constructor.
The argument to the JList constructor is the array of Strings (xmenlist) declared at line 8 to
display in the list. Line 15 uses method setVisibleRowCount to determine the number of
items that are displayed in the list.
Line 19 uses method setSelectionMode to specify the list selection mode. Class
ListSelectionModel defines constants SINGLE_SELECTION,
SINGLE_INTERVAL_SELECTION and MULTIPLE_INTERVAL_SELECTION to specify a
Jlists selection mode. A SINGLE_SELECTION list allows only one item to be selected at a
time. A SINGLE_INTERVAL_SELECTION list is a multiple-selection list that allows several
items in a contiguous range in the list to be selected. A MULTIPLE_INTERVAL_SELECTION
list is a multiple list that does not restrict the items that can be selected.
Unlike JComboBox, JLists do not provide a scrollbar if there are more items in the list
than the number of visible rows. In this case, JscrollPane object is used to provide the
automatic scrolling capability for the JList. Line 21 adds a new instance of class JscrollPane to
the content pane. The JscrollPane constructor receives as its argument the JComponent for
which it will provide automatic scrolling functionality (in this case, “xmen”). By default, the
scrollbar appears only when the number of items in the list exceeds the number of visible items.
Line 22 uses JList method addListSelectionListener to register an instance of an
anonymous inner class that implements ListSelectionListener (defined in the package
javax.swing.event, line 4) as the listener for JList xmen. When the user makes the selection
from the list, method valueChanged (line 23) executes and sets the value of the textfield based
on the value returned by the method getSelectedIndex.
Another version of the JList program is presented below. This program does not use an
anonymous inner class. The output is similar to the output presented above.
//Jlist program that does not use an anonymous inner class
//Jlistdemo1rev.java
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
83
{ private String xmenlist[] = {"Cyclops","Jubillee","Beast","Wolverine","Nightcrawler"};
private JList xmen = new JList(xmenlist);
private JTextField txt1 = new JTextField(15);
public Jlistdemo1rev(String s)
{ super(s);
Container a = getContentPane();
a.setLayout(new FlowLayout());
xmen.setVisibleRowCount(3);
a.add(txt1);
txt1.setEditable(false);
Multiple-Selection List
A multiple-selection list enables the user to select many items from a JList. A
SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list
by clicking the first item, then holding the Shift key while clicking the last item to select in the
range. A MULTIPLE_INTERVAL_SELECTION list allows continuous range selection as
84
described for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be
selected by holding the CTRL key while clicking each item to select. To deselect an item, hold
the CTRL key while clicking the item a second time.
// This program demonstrates the use of jlist with multiple //selection
//Jlistdemo2.java
1 import javax.swing.*;
2 import javax.swing.event.*;
3 import java.awt.*;
4 import java.awt.event.*;
19 a.add(copybutton);
20 //anonymous inner class for button event
21 copybutton.addActionListener(new ActionListener()
22 { public void actionPerformed(ActionEvent c)
23 { //place selected list in copy list
24 copylist.setListData(xmen.getSelectedValues());
25 }
26 }); //end of anonymous inner class
33 setVisible(true);
34 setSize(300,300);
35 } //end constructor
36 public static void main(String args[])
37 { Jlistdemo2 testlist = new Jlistdemo2("Jlist demo with multiple selection");
38 testlist.show();
39 testlist.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
85
40 }
41 }
The program uses multiple-selection list to copy items from one JList to another. One
list is MULTIPLE_INTERVAL_SELECTION and the other is a
SINGLE_INTERVAL_SELECTION. Line 7 creates JList “xmen” and initializes it with the
Strings in the array “xmenlist”. Lines 15 sets the number of visible rows to 5. Line 16 uses JList
method setFixedCellHeight to specify the height in pixels of each item in the list. This is to
ensure that rows in both JList (xmen and copylist) have the same height. Line 17 specifies that
xmen is a MULTIPLE_INTERVAL_SELECTION list. Line 18 adds a new JscrollPane containing
“xmenlist” to the content pane. Line 28-32 perform similar tasks for JList “copylist”, which is
defined as SINGLE_INTERVAL_SELECTION list. Line 30 uses method setFixedCellWidth to
copylists’ width to 100 pixels.
A multiple-selection list does not have a specific event associated with making multiple
selections. Normally, an event generated by another GUI component (known as an external
event) specifies when the multiple selection in the JList should be processed. In the program,
the user clicks the copy button to trigger the event that copies selected items in xmen to
copylist.
When the button is clicked, method actionPerformed is called. Line 24 uses method
setListData to set the items displayed in copylist. In the same line, xmen list’s method
getSelectedValues , which returns an array of Objects representing the selected items in the
xmen list. In the statement, the returned array is passed as the argument to copylists’
setListData method.
Assuming Cyclops, Beast and Nightcrawler is selected from the list then copy button is
clicked, the selected items will be copied to the copylist
86
public F2f(String s)
{ super (s);
Container c = getContentPane();
c.setLayout(new FlowLayout());
Buttonhandler btnclick = new Buttonhandler();
c.add(jbtnshow);
c.add(jbtnclose);
jbtnshow.setRolloverIcon(iconpaint);
jbtnshow.addActionListener(btnclick);
jbtnclose.addActionListener(btnclick);
setVisible(true);
setSize(300,300);
} //end constructor
private class Buttonhandler implements ActionListener
{ public void actionPerformed(ActionEvent y)
{ if (y.getSource()==jbtnshow)
subframe.show(); //display the other frame
else
{ dispose();
System.exit(0);}
} //enf if
} //end buttonhandler
public static void main(String args[])
{ System.out.println("Preparing to display frame... pls wait...");
F2f mainframe = new F2f("This is the main frame");
mainframe.show();
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//this is the other frame that will be called
private class Frame2 extends JFrame
{ JButton jbtnexit = new JButton("Return to main");
Frame2(String str)
{ super(str);
Container x = getContentPane();
x.setLayout(new FlowLayout());
x.setSize(200,200);
Bhandler btnreturn = new Bhandler();
x.add(jbtnexit);
jbtnexit.addActionListener(btnreturn);
setSize(200,200);
} //constructor
private class Bhandler implements ActionListener
{ public void actionPerformed (ActionEvent z)
{ dispose();} //return to the calling frame
} //end bhandler
} //end frame2
}//end class f2f
87
Using Menus with Frames
Menus are integral part of GUIs. Menus allow the user to perform actions without
unnecessarily “cluttering” a graphical user interface with extra GUI components. In Swing GUIs,
menus can be attached only to objects of the classes that provide method setJMenuBar. Two
such classes are JFrame and JApplet. The classes used to define menus are JMenuBar,
JMenu, JMenuItem , JCheckBoxMenuItem and JRadioButtonMenuItem.
Class JMenuBar ( a subclass of JComponent) contains the methods necessary to
manage a menu bar, which is a container for menus
Class JMenuItem (a subclass of javax.swing.AbstractButton) contains the methods
necessary to manage menu items. A menu item is a GUI component inside a menu that, when
selected, causes an action to be performed. A menu item can be used to initiate an action or it
can be a submenu that provides more menu items from which the user can select. Submenus
are useful for grouping related menu items in a menu.
Class JMenu (a subclass of javax.swing.JMenuItem) contains the methods necessary
for managing menus. Menus contains menu items and are added to menu bars or to other
menus as submenus. When a menu is clicked, the menu expands to show its list of menu
items. Clicking a menu item generates an action event.
Class JCheckBoxMenuItem( a subclass of javax.swing.JMenuItem) contains the
methods necessary to manage menu items that can be toggled on or off. When a
JCheckBoxMenuItem is selected, a check appears to the left of the menu item.
Class JradioButtonMenuItem ( a subclass of javax.swing.JMenuItem) contains the
methods necessary to manage menu items that can be toggled on or off like
JcheckBoxMenuItems. When multiple JRadioButtonMenuItems are maintained as part of a
ButtonGroup, only one item in the group can be selected at a given time.
88
9 JMenu editMenu = new JMenu("Edit");
10 //set up options in file menu
11 JMenuItem newItem = new JMenuItem("New");
12 JMenuItem openItem = new JMenuItem("Open");
13 JMenuItem exitItem = new JMenuItem("Exit");
14 public Jmenudemo1(String x)
15 { super(x);
16 //attach menu bar to the frame
17 setJMenuBar(menubar);
18 menubar.add(fileMenu);
19 menubar.add(editMenu);
89
// Another sample of using menus other containing gui //commponents.
//Jmenudemo2.java
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
90
48 menubar.add(styleMenu);
49 setVisible(true);
50 setSize(200,200);
51 } //end of constructor
52 private class Buttonhandler implements ActionListener
53 { public void actionPerformed(ActionEvent a)
54 { if (a.getSource()==newItem) //if option new is selected
55 JOptionPane.showMessageDialog(null,"Option New
selected","New",JOptionPane.PLAIN_MESSAGE);
56 else if (a.getSource()==openItem) //if option Open is selected
57 JOptionPane.showMessageDialog(null,"Option Open
selected","Open",JOptionPane.PLAIN_MESSAGE);
58 else if (a.getSource()==exitItem) //exit option
59 System.exit(0);
60 else if (a.getSource()==bold)//bold option in the style menu
61 lbl1.setFont(new Font("TimesRoman",Font.BOLD,12));
62 else
63 lbl1.setFont(new Font("TimesRoman",Font.ITALIC,12));
64 }
65 } //end of class buttonhandler
66 public static void main(String args[])
67 { Jmenudemo2 test = new Jmenudemo2("Menu demo");
68 test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
69 test.show();
70 } //end of main
71 }//end of class jmenudemo2
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
91
20 JRadioButtonMenuItem blue = new JRadioButtonMenuItem("Blue",false);
21 JRadioButtonMenuItem yellow = new JRadioButtonMenuItem("Yellow",false);
44 c.add(lbl);
45 lbl.setFont(plain);
46 //add menu items for style menu
47 stylemenu.add(colormenu);
48 //add a line separating the 2 options
49 stylemenu.addSeparator();
50 stylemenu.add(bimenu);
51 //class to handle radio button & checkbox events
52 Itemselected option = new Itemselected();
53 Checkselected checked = new Checkselected();
54 //attach radio buttons for Color option
55 colormenu.add(red);
56 colormenu.add(blue);
57 colormenu.add(yellow);
58 //create logical relationship between radio buttons
59 colorgroup.add(red);
60 colorgroup.add(blue);
61 colorgroup.add(yellow);
62 //attach checkbox for Typeface option
63 bimenu.add(style_bold);
64 bimenu.add(style_italic);
65 red.addItemListener(option);
66 blue.addItemListener(option);
67 yellow.addItemListener(option);
92
68 style_bold.addItemListener(checked);
69 style_italic.addItemListener(checked);
70 } //end of constructor
71 // inner class to handle Exit option in the File menu
72 private class Buttonhandler implements ActionListener
73 { public void actionPerformed(ActionEvent e)
74 {System.exit(0);}
75 }//end of class Buttonhandler
76 //inner class to handle checkbox events
77 private class Checkselected implements ItemListener
78 {
79 private int valBold = Font.PLAIN;
80 private int valItalic = Font.PLAIN;
90 if (z.getSource()==style_italic)
91 if(z.getStateChange()==ItemEvent.SELECTED)
92 valItalic=Font.ITALIC;
93 else // if unchecked
94 valItalic=Font.PLAIN;
95 //set up the typeface of the text
96 lbl.setFont(new Font("TimesRoman",valBold+valItalic,15));
97 } //end of itemstatechanged
98 }//end of class Checkselected
99 //inner class to handle radio buttons
100 private class Itemselected implements ItemListener
101 { public void itemStateChanged(ItemEvent z)
102 { if (z.getSource()==red)
103 lbl.setForeground(Color.red);
104 else if(z.getSource()==blue)
105 lbl.setForeground(Color.blue);
106 else
107 lbl.setForeground(Color.yellow);
108 }
109 }//end of class Itemselected
93
Lesson 9: Database
Overview:
This lesson covers simple database connectivity.
Objectives:
To learn how to create table in MS Access
To add, edit and delete records on the DB
94
What is Database?
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by
a database management system (DBMS). Most databases use structured query language
(SQL) for writing and querying data.
JDBC is a standard Java API for database-independent connectivity between the Java
programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database. Java can be used to write
different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.
JDBC provides the same capabilities as Object Database Connectivity (ODBC),
allowing Java programs to contain database-independent code.
Create Database
To create a Database using JDBC application. Before executing the following example,
make sure you have the following in place −
You should have admin privilege to create a database in the given schema. To
execute the following example, you need to replace
the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Steps in Creating DB
The following steps are required to create a new Database using JDBC application −
95
Import the packages: Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so you can open
a communications channel with the database.
Open a connection: Requires using the DriverManager.getConnection()
method to create a Connection object, which represents a physical connection
with the database server.
To create a new database, you need not give any database name while
preparing database URL as mentioned in the below example.
Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Clean up the environment: Requires explicitly closing all database resources
versus relying on the JVM's garbage collection.
SQL Syntax
Structured Query Language (SQL) is a standardized language that allows you to perform
operations on a database, such as creating entries, reading content, updating content, and
deleting entries.
SQL is supported by almost any database you will likely use, and it allows you to write
database code independently of the underlying database.
This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts.
After going through this chapter, you will be able to Create, Create, Read, Update, and Delete
(often referred to as CRUD operations) data from a database.
1. Create Database
The CREATE DATABASE statement is used for creating a new database.
Syntax: CREATE DATABASE DATABASE_NAME;
2. Drop Database
The DROP DATABASE statement is used for deleting an existing database.
Syntax: DROP DATABASE DATABASE_NAME;
3. Create Table
The CREATE TABLE statement is used for creating a new table.
Syntax: CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type ... );
4. Drop Table
The DROP TABLE statement is used for deleting an existing table.
Syntax: DROP TABLE table_name;
5. Insert Data
The syntax for INSERT, looks similar to the following, where column1, column2, and so
on represents the new data to appear in the respective columns
96
Syntax: INSERT INTO table_name VALUES (column1, column2, ...);
6. Select Data
The SELECT statement is used to retrieve data from a database.
Syntax: SELECT column_name, column_name, ... FROM
table_name WHERE conditions;
7. Update Data
The UPDATE statement is used to update data.
Syntax: UPDATE table_name SET column_name = value, column_name =
value, ... WHERE condition/s;
8. Delete Data
The DELETE statement is used to delete data from tables.
Syntax: DELETE FROM table_name WHERE condition/s;
Sample Programs:
// Create Database
// STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
97
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
// Create Table
// STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
98
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
// Database credentials
static final String USER = "username";
static final String PASS = "password";
99
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
100
}//end JDBCExample
// Database credentials
static final String USER = "username";
static final String PASS = "password";
// Declare variables
static Scanner scan = new Scanner(System.in);
static int idno, edad;
static String first_name, last_name, answer = “yes”;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
101
prepStmt.setString(4,edad);
// execute PreparedStatment
prepStmt.execute();
System.out.println("Inserted records into the table...");
Sytem.out.print(“Input new record?[yes/no]: ”);
answer = scan.nextLine();
}
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
// Database credentials
static final String USER = "username";
static final String PASS = "password";
102
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
103
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
// Database credentials
static final String USER = "username";
static final String PASS = "password";
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
104
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
// Delete Record / Data
// STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
105
System.out.println("Connected database successfully...");
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
106
}//end JDBCExample
// Database credentials
static final String USER = "username";
static final String PASS = "password";
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
107
// Extract records in descending order by first name.
System.out.println("Fetching records in descending order...");
sql = "SELECT id, first, last, age FROM Registration" +
" ORDER BY first DESC";
rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
108
Laboratory Exercise:
1. Create a database of salesman:
a. Table Description:
o Salesman Number – Integer – Primary Key – Not Null
o Salesman Name – VarChar
o Quarterly Sales – Real (Float)
Note: input of sales per quarter (1st, 2nd, 3rd, 4th)
o Total Sales - Double
o Commission – Real (Float)
109
Bibliography
Perry, Greg. Teach Yourself Object-Oriented Programming with Turbo C++ in 21 days
Sams Publishing 1993.
Internet Resources:
1. https://www.redbooks.ibm.com/
2. http://java.sun.com/javase/downloads
3. https://www.tutorialpoints.com/jdbc
4. https://www.w3schools.com/java
110