You are on page 1of 46

DATA STRUCTURES

USING JAVA
PROGRAMMING DEPARTMENT
November 2010

Programming NC IV
Information and Communications Technology

Compiled by:

EUGENE F. GALANG
Area Chair

Reviewed by:

Approved by:

ANTONIO M. ERRO

CONRADO T. CAMIGLA

Dean, Academic Affairs

School Director

No part of this module may be reproduced or utilized in any form or by any means (electronic,
photocopying, and recording) without the written permission of the author and the school.

2
TABLE OF CONTENTS
Introduction to Java
Two main deployment environments:
Phases of a Java Program
Getting to know your Programming Environment using NetBeans

Dissecting a Program
8 Primitive Data Types
Variables

9
9
10

Operators
Arithmetic
Increment/Decrement
Relational
Logical and Boolean Logical
Conditional/Ternary
Order of Precedence

11

Statements and Blocks

15

D
R
F
I
L
E
M
O
N
C

Activity Homeowner Sales

17

Control Flow Statements


If statement
If-else statement
If-else-if statement
Switch statement

18

Repetition Control Structures


While and do-while statements
For statement
Continue statement
Break statement

22

Method: Passing Parameters


Fibonacci Series
Nested Loop

25
26
26

ACTIVITY
FOR loop: POWER
Nested Loop & Methods: Diamond

27

Arrays
1 dimensional array

28

ACTIVITY
Number Sequence
HARRY POTTER & THE AMAZING WIZARD

30

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

3
2 dimensional array
Sorting and searching
Link list
Queue
Stack
ACTIVITY
Stack Operation using Linked List
Database Manipulation
ACTIVITY
Database Manipulation

32

D
R

34
37
37
37

F
I
L
E
M
O
N

41

42
45

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

4
Introduction to Java
Java was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called Oak, in
honor of the tree outside Gosling's window, its name was changed to Java
because there was already a language called Oak.
The original motivation for Java was the need for platform independent
language that could be embedded in various consumer electronic products
like toasters and refrigerators. One of the first projects developed using
Java was a personal hand-held remote control named Star 7.

Two main deployment environments:


1. The Java Runtime Environment (JRE) supplied by the Java 2 Software Development Kit
(SDK) contains the complete set of class files for all the Java technology packages, which
includes basic language classes and GUI component classes.
2. The web browser. Most commercial browsers supply a Java technology interpreter and
runtime environment.

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y

Phases of a Java Program

T
R
A
I
N
I
N
G

Task
Tool to use
Write the program
Any text editor
Compile the program Java Compiler
Run the program
Java Interpreter

Data Structures using Java

Output
File with .java extension
File with .class extension (Java bytecodes)
Program Output

eugene . jay . john. lary . romel . romelyn

I
N
S
T
I
T
U
T
E

5
Getting to know your Programming Environment using Netbeans
An Integrated Development Environment (IDE) is a programming environment integrated into a
software application that provides a GUI builder, a text or code editor, a compiler and/or
interpreter and a debugger.
Step 1: Using NetBeans 6.8
To start the NetBeans IDE in Windows, click on Start Button Programs NetBeans
NetBeans IDE 6.8 or double click on the shortcut icon on the desktop.

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N

SHORTCUT ICON

After opening NetBeans IDE, you will see the splash screen and the graphical user interface
(GUI) below.

T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

6
D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

Step 2: Make a project


Click on File New Project Java Java Application Next

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G

Now, a New Application dialog will appear. Edit the Project Name part and type in
"HelloApplication", then click Finish

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

I
N
S
T
I
T
U
T
E

7
D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

Step 3. Type the program code then Run File

I
N
F
O
R
M
A
T
I
O
N

Launching pad of
Java application

T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G

Code / Line no.

Data Structures using Java

These lines of code are generated


automatically by NetBeans

eugene . jay . john. lary . romel . romelyn

I
N
S
T
I
T
U
T
E

8
D
R

Right-click
code, Select
Run File

Statement

F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

Output

I
N
F
O
R
M
A
T
I
O
N

A common bug in Java program (ex. Semi-colon expected).

Semi-colon expected

T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

9
DISSECTING A PROGRAM
Package is similar to a folder on
your computer that organizes a
set of related classes.

Comment is used to
document a part of the
code. It is not part of the
program.

public access specifier indicates


that class Main is accessible to
other classes from other packages.

Class Main should


be saved in a file
called Main.java

Prints the text enclosed by


quotation on the screen.

8 PRIMITIVE DATA TYPES


Variables must first be declared before they can be used. A variable's data type determines the
values it may contain, plus the operations that may be performed on it.
1. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum
value of -128 and a maximum value of 127 (inclusive).
2. short: The short data type is a 16-bit signed two's complement integer. It has a
minimum value of -32,768 and a maximum value of 32,767 (inclusive).
3. int: The int data type is a 32-bit signed two's complement integer. It has a minimum
value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
4. long: The long data type is a 64-bit signed two's complement integer. It has a minimum
value
of
-9,223,372,036,854,775,808
and
a
maximum
value
of
9,223,372,036,854,775,807 (inclusive).
5. float: A single-precision 32-bit floating point.
float h = 340282355999999999999999999999999999999.99f;
float f = Float.MAX_VALUE;
6. double: The double data type is a double-precision 64-bit floating point. For decimal
values, this data type is generally the default choice.
7. boolean: The boolean data type has only two possible values: true and false.
8. char: The char data type is a single 16-bit Unicode character.
Data Structures using Java

eugene . jay . john. lary . romel . romelyn

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

10
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared
but not initialized will be set to a reasonable default by the compiler. The following chart
summarizes the default values for the above data types.

D
R
F
I
L
E
M
O
N

Data Type

Default Value (for fields)

byte

short

int

long

0L

Float

0.0f

double

0.0d

Char

'\u0000'

A
G
U
I
L
A
R

String (or any object) Null


boolean

False

VARIABLES
Variable is a symbolic name associated with a value that can be changed.
Rules and conventions for naming your variables.
1. Variable names are case-sensitive. A variable name can be any legal identifier a
sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the
underscore character "_".
2. Subsequent characters may be letters, digits, dollar signs, or underscore characters.
3. If the name you choose consists of only one word, spell that word in all lowercase
letters. If it consists of more than one word, capitalize the first letter of each subsequent
word.
To declare and initialize a variable
Data_type name [=initial value];
Example:
int rate = 80;
float salary;
salary = 15.80;

Value enclosed with square brace ([ ]) is optional.

Declare and initialize variable rate


Declare variable salary
Initialize variable salary

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

11
OPERATORS
1. Arithmetic

D
R

Operation
Addition
Subtraction
Multiplication
Division
Modulus

Arithmetic
operator
+
*
/
%

Algebraic
expression
f+7
pc
bm
x/y
r mod s

Java
expression
f+7
p-c
b*m
x/y
r%s

Description
Add f and 7
Subtract c from p
Multiply b by m
Divide x by y
Compute the remainder
by dividing r by s

public class ArithmeticOperator {


public static void main( String[] args ){
int x = 5, y = 3, prod, sum, diff, quot, remain;
prod = x * y;
sum = x + y;
diff = x - y;
quot = x / y;
remain = x % y;
System.out.println( Product: + prod );
System.out.println( Sum: + sum);
System.out.println( Difference: + diff);
System.out.println( Quotient: + quot );
System.out.println( Remainder: + remain);
}
}

import java.io.*;

A java package for input /


output operation.

public class ArithmeticOperatorInput {


public static void main( String[] args ) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Creating an
int x, y;
object br
Using function readLine() to read
String str;
intended
a value to be stored in variable str.
for String
str = br. readLine();
Converting String str to Integer value
input values
x = Integer.parseInt(str);
Reading and converting String input
y = Integer.parseInt(br.readLine());
to integer value
System.out.println(Product : + (x * y));
}
}
Data Structures using Java

eugene . jay . john. lary . romel . romelyn

F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

12
2. Increment / Decrement Operator
Operation
Increment

Arithmetic
operator
++

Algebraic
expression
x++
++x

Decrement

--

x---x

Description
Increments x by 1; evaluates the value
of x before it was incremented.
Increments x by 1; evaluates the value
of x after it was incremented.
Decrements x by 1; evaluates the value
of x before it was decremented.
Decrements x by 1; evaluates the value
of x after it was decremented.

import java.io.*;
public class ArithmeticOperator {
public static void main( String[] args ) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int number1, number2;
number1 = Integer.parseInt(br.readLine());
number1++;
System.out.println(Processed value: + number1);
number2 = number1++;
System.out.println(Processed value of number1: + number);
System.out.println(Processed value of number2: + number2);
number2 = ++number1;
System.out.println(Processed value of number1: + number);
System.out.println(Processed value of number2: + number2);
}
}

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

13
3. Relational
Operation
Greater than
Greater than or equal to
Less than
Less than or equal to
Equal to
Not equal to

Arithmetic
operator
>
>=
<
<=
==
!=

Algebraic
expression
a>b
a >= b
a<b
a <= b
a == b
a != b

Description
Is a greater than b
Is a greater than or equal to b
Is a less than b
Is a less than or equal to b
Is a equal to b
Is a not equal to b

4. Logical and Boolean Logical

T
T
F
F

T
F
T
F

Logical AND (&&)

Logical OR (||)

Boolean Logical AND (&)


T
F
F
F

Boolean Logical inclusive OR (|)


T
T
T
F

NOT P

EXCLUSIVE
OR (^)

F
F
T
T

F
T
T
F

The basic difference between Logical and Boolean Logical operators is that
Logical operators support short-circuit evaluations (or partial evaluations), while
Boolean Logical doesn't.

(5 == 3) && (12%2 >= 6)


Will immediately return FALSE since (5 == 3) yields to false.
(5 == 3) & (12%2 >= 6)
Will evaluate both condition before returning FALSE.

For exclusive OR (^), both operands must always be evaluated in order to


calculate the result.

5. Conditional / Ternary
The conditional operator ?: is a ternary operator. This means that it takes in three
arguments that together form a conditional expression.
Syntax : exp1?exp2:exp3
where
exp1 is a Boolean expression whose result is either true or false
exp2 is the value returned if emp1 is true
exp3 is the value returned if emp1 is false

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

14
public class ConditionalOperator {
public static void main( String[] args ){
String status = "";
int grade = 80;

D
R
F
I
L
E
M
O
N

//get status of the student


status = (grade >= 60)?"Passed":"Fail";
//print status
System.out.println( status );

}}

A
G
U
I
L
A
R

class ConditionalOperator {
public static void main( String[] args ){
int score = 0;
char answer = 'a';

I
N
F
O
R
M
A
T
I
O
N

score = (answer == 'a') ? 10 : 0;


System.out.println("Score = " + score );
}}

ODER OF PRECEDENCE
Operator precedence defines the compilers order of evaluation of operators so as to
come up with an unambiguous result.

T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G

Given a complicated expression,


6 % 2 * 5 + 4 / 2 + 88 - 10
Rewrite the expression and place some parenthesis based on operator precedence
((6 % 2) * 5) + (4 / 2) + 88 - 10;
Data Structures using Java

eugene . jay . john. lary . romel . romelyn

I
N
S
T
I
T
U
T
E

15
STATEMENTS AND BLOCKS
D
R

Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms
a complete unit of execution. The following types of expressions can be made into a
statement by terminating the expression with a semicolon (;).
Such statements are called expression statements.
aValue = 8933.234;
aValue++;
System.out.println("Hello World!");

// assignment statement
// increment statement
// method invocation statement

Blocks
A block is a group of zero or more statements between balanced braces and can be used
anywhere.

Operators: / * +

4a

y = 2(a^2) + 6a

class compute {
public static void main(String args[])
{
int a = 5;
int x = ((5 * a) / (10 * a)) (4 * a);
int y = (2 * (a * a)) + (6 * a);
int ave = (x + y ) / 2;
System.out.println(x = + x);
System.out.println(y = + y);
System.out.println(average = + ave);
}
}

C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N

Compute and display the values for x, y and its average.


x=

F
I
L
E
M
O
N

Output:
x = -20
y = 80
average = 30

T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

16
Calculation: Compute for the Gross, Net, Tax
Create a program that will compute the gross and netpay of an employee where rate =
100 and hrs worked = 8. The formula for gross, tax and net is as follows:
gross = rate * hrs worked
tax = 5% of gross
net = gross tax
class grossNet {
public static void main(String args[]) {
double gross, net, tax, rate = 100, hrsWorked=8;
gross = rate * hrsWorked;
tax = gross * .05;
net = gross tax;
System.out.println(GROSS = + gross);
System.out.println(TAX = + tax);
System.out.println(NET = + net);
} }

F
I
L
E
M
O
N
C

Output:
GROSS = 800.0
TAX = 40.0
NET = 760.0

Quadratic Formula using JOptionPane


Create a program that will display the result of the equation
qF = ax^2 + bx + c
where
a=5, b=2 and c=3.
The program should accept the value for x. Use JOptionPane.showInputDialog for the
input value and JOptionPane.showMessageDialog for displaying the result of qF.
import javax.swing.JOptionPane;
class quadFormula {
public static void main(String args[])
{
int x, a=5, b=2, c=3, qF;
String str = JOptionPane.showInputDialog(Enter a number);
x = Integer.parseInt(str);
qF = (a*x*x) + (b * x) + c;
JOptionPane.showMessageDialog(null, Computed Value: + qF);
}
}

Data Structures using Java

D
R

eugene . jay . john. lary . romel . romelyn

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

17
ACTIVITY
Homeowner Sales
Laboratory problem was downloaded and edited from Thomas L. Browns page at
http://boisdarc.tamu-commerce.edu/~tombrown/lab/cs431/lab1fa06

Problem Definition:
Design a program that inputs data about a house to be sold and produces output about
the house and a potential sales transaction.

D
R
F
I
L
E
M
O
N
C

Input (Standard system inputthe keyboard):


homeowners name (String)
house price (double) and
sales commission rate (int) - for example, 6 will be entered for 6% rate.

Output (Standard outputthe terminal screen):


homeowners name
house price
commission
computed selling cost

Processing
Commission is the product of home price and sales commission rate.
The selling cost is the sum of home price and the commission.

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

18
CONTROL FLOW STATEMENTS
Decision control structures are Java statements that allow us to select and execute specific
blocks of code while skipping other sections.
if statement
The if-then statement tells your program to execute a certain section of code only if a
particular test evaluates to true.
SYNTAX
if( boolean_expression )
statement;

if( boolean_expression ) {
statement1;
statement2;
...
}

if-else statement
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false.
SYNTAX
if( boolean_expression )
statement;
else
statement;

if( boolean_expression ){
statement1;
statement2;
...
}
else{
statement1;
statement2;
...
}

if-else-if statement
The statement in the else-clause of an if-else block can be another if-else structure. This
cascading of structures allows us to make more complex selections.
The if-else if statement has the form,
if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;
Take note that you can have many else-if blocks after an if-statement. The else-block is optional
and can be omitted. In the example shown above, if boolean_expression1 is true, then the
program executes statement1 and skips the other statements. If boolean_expression2 is true,
then the program executes statement 2 and skips to the statements following statement3.
Data Structures using Java

eugene . jay . john. lary . romel . romelyn

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

19

class BlockDemo
{
public static void main(String[] args)
{
boolean condition = true;
if (condition)
{
System.out.println("Condition is true.");
}
else
{

D
R

//begin main block

F
I
L
E
M
O
N

// begin block 1

//begin class block

// end block 1

// begin block 2
System.out.println("Condition is false.");

}
}
}

// end block 2
//end main block
//end class block

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

20
selection structure if
D
R

import javax.swing.JOptionPane;
class selectStruct {
public static void main(String args[]) {
int choice;
String str;
str = JOptionPane.showInputDialog(Main Menu \n +
*1+ Name \n +
*2+ School \n +
*3+ Course \n +
*4+ Exit);
choice =Integer.parseInt(str);
if(choice ==1)
JOptionPane.showMessageDialog(null, iana mel f. galang);
else if(choice ==2)
JOptionPane.showMessageDialog(null, DFCAIT);
else if(choice ==3)
JOptionPane.showMessageDialog(null, Programming);
else if(choice ==4)
JOptionPane.showMessageDialog(null, by: Eugene);
}
}

F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

21
if: Odd or Even
import javax.swing.*;
class evenOdd
{
public static void main(String args[])
{
int num = Integer.parseInt(JOptionPane.showInputDialog(Enter a number));
int abs=num;
if(num<0)
abs *= -1;

D
R
F
I
L
E
M
O
N
C

int sqr = num * num;


if(num % 2 == 0)
JOptionPane.showMessageDialog(null,num + is even\nSquared value = + sqr);
else
JOptionPane.showMessageDialog(null,num + is odd\nAbsolute value = + abs);
}
}

output

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

22
switch statement
Another way to indicate a branch is through the switch keyword. The switch construct
allows branching on multiple outcomes.

F
I
L
E
M
O
N

The switch statement has the form,


switch( switch_expression ) {
case case_selector1:
statement1; //
statement2; //block 1
. . . //
break;
case case_selector2:
statement1; //
statement2; //block 2
. . . //
break;
...
default:
statement1; //
statement2; //block n
. . . //
break;
}

C
A
G
U
I
L
A
R

The body of a switch statement is known as a switch block. Any statement immediately
contained by the switch block may be labeled with one or more case or default labels.
The switch statement evaluates its expression and executes the appropriate case.
To prevent the program from executing statements in the subsequent cases, we use a
break statement as our last statement.

Repetition Control Structures


Repetition control structures are Java statements that allows us to execute specific
blocks of code a number of times. There are three common types of repetition control
structures, the while, do-while and for loops.
The while and do-while Statements
The while statement continually executes a block of statements while a particular
condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
Data Structures using Java

D
R

eugene . jay . john. lary . romel . romelyn

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

23
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until
the expression evaluates to false.
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}

The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block
are always executed at least once.
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}

The for Statement


The for statement provides a compact way to iterate over a range of values.
Programmers often refer to it as the "for loop" because of the way in which it
repeatedly loops until a particular condition is satisfied.
for (initialization; termination; increment) {
statement(s)
}

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

24
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it is executed once, as the loop
begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
class ForDemo {
public static void main(String[] args){
for(int i = 1; i < 11; i++){
System.out.println("Count is: " + i);
}
}
}

The continue Statement


The continue statement skips the current iteration of a for, while , or do-while loop.
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}

The break Statement


break terminates the enclosing switch statement, and flow of control transfers to the
statement immediately following the switch. You can also use the form of the break
statement to terminate a for, while, or do-while loop.

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

25
Method: Passing Parameters
A method is a set of code which is referred to by name and can be called (invoked) at any point
in a program simply by utilizing the method's name. Think of a method as a subprogram that
acts on data and often returns a value.
Each method has its own name. When that name is encountered in a program, the execution of
the program branches to the body of that method. When the method is finished, execution
returns to the area of the program code from which it was called, and the program continues on
to the next line of code.

D
R
F
I
L
E
M
O
N
C

import javax.swing.*;
class startEnd
{
public static void main(String args[])
{
int x = Integer.parseInt(JOptionPane.showInputDialog(Enter starting number));
int y = Integer.parseInt(JOptionPane.showInputDialog(Enter ending number));
disp(x,y);
}
static void disp(int a, int b)
//series will be displayed if a <= b
{
String out=;
for( ; a <= b; a++)
out = out + a + ;
JOptionPane.showMessageDialog(null,out);
}
}

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

26
Fibonacci Series
The Fibonacci numbers are the numbers in the following sequence: By definition, the first two
Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.
Some sources omit the initial 0, instead the sequence begins with two 1s.
class Fibonacci //1 1 2 3 5 8 13
{
static void fibo()
{
int x=1, y=1, temp=x+y;;
System.out.print(x + + y + + temp + );

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N

public static void main(String args[])


{
fibo();
//method call
}
}

Nested Loop
The placing of one loop inside the body of another loop is called nesting. When you "nest" two
loops, the outer loop takes control of the number of complete repetitions of the inner
loop. When working with nested loops, the outer loop changes only after the inner loop is
completely finished

for(num2 = 1; num2 <= 5; num2++) {


for(num1 = 1; num1 <= num2; num1++)
System.out.print(num1);
System.out.println();
}
}
}}

Data Structures using Java

F
I
L
E
M
O
N
C

while(temp<13)
{
y=x;
x=temp;
temp = x + y;
System.out.print(temp + );
}
}

class NestedSeries {
public static void main(String args[]) {
int num1, num2;

D
R

OUTPUT
1
12
123
1234
12345

eugene . jay . john. lary . romel . romelyn

T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

27
ACTIVITY
FOR loop: POWER

D
R

Create a program that will compute the power of a number given the base and its exponent.
Use any looping structure (while, do-while, for)
3
Example: 5
Base: 5
Exponent: 3
Result: 125

F
I
L
E
M
O
N
C

ACTIVITY
Nested Loop & Methods: Diamond
Create a program that will ask the user to choose from 1 to 6 based on the given main menu.
The output of the program depends on the selected item.
A sample screenshot is shown below in which the user had selected number 5.

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

28
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of
an array is established when the array is created. After creation, its length is fixed.
An array stores multiple data items of the same datatype, in a contiguous block of memory,
divided into a number of slots.

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

An array of ten elements


Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the above illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.

Declaring a Variable to Refer to an Array


Like declarations for variables of other types, an array declaration has two components:
the array's type and the array's name. An array's type is written as type[], where type is
the data type of the contained elements; the square brackets are special symbols
indicating that this variable holds an array. The size of the array is not part of its type
(which is why the brackets are empty). One way to create an array is with the new
operator.
int[] anArray;
anArray = new int[10];

// declares an array of integers


// allocates memory for 10 integers

Initializing, and Accessing an Array


Assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
An index number or subscript is assigned to each member of the array, allowing the
program and the programmer to access individual values when necessary.
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

29
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Length of the array is determined by the number of values provided between curly
brackets { and }.

Array length
In order to get the number of elements in an array, you can use the length field of an
array. The length field of an array returns the size of the array. It can be used by writing,
arrayName.length

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

public class ArraySample


// 5 6 12 7 3
{
public static void main( String[] args ){
int[] ages = {5, 6, 12, 7, 3};
for( int i=0; i<ages.length; i++ ){
System.out.print( ages[i] );
}
}
}

I
N
F
O
R
M
A
T
I
O
N

1-Dimensional Array

T
E
C
H
N
O
L
O
G
Y

class array13579
{
public static void main(String args[])
{
int A[] = new int[5];
for (int i = 0; i < 5; i++)
{
A[i] = i*2 + 1;
System.out.print(A*i+ + );
}
}
}

T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

30
ACTIVITY
Number Sequence

D
R

Create an array that will store the number sequence 10 20 30 40 to a one dimensional array.
The program will display the content of the array along with its total.

ACTIVITY
HARRY POTTER & THE AMAZING WIZARD

http://java.itags.org/java-essentials/52684/
http://forums.sun.com/thread.jspa?threadID=789887

Declare and initialize a 20-element array. In each element place one of the following characters:
W Wizard
S Sword
D Demon
B Blank Save spot.

Example an array can look like this:


South
W S
0
1

S
2

D
3

B
4

D
5

W
6

B
7

B
8

D
9

W
10

S
11

W
12

D
13

B
14

D
15

S
16

W
17

North
B
S
18 19

You ask the player to select a location in Hogarth Tower. (Choose a number from 0 19) That
places the player at a position in the array. In the example if the user enters a 4 as a starting
position (starting at 0). So, the entry at that position is a B (Blank).
Based on the rules below the player can then move North (add 1 to the array index) or South
(subtract 1 from the array index). Here are the rules:
(1) For each Blank (B) spot, output the message Safe Place; 2 points is awarded.
(2) For each Wizard (W) spot, output the message You picked up a Wizard; 3 Points is
Awarded.
(3) For each Sword (S) spot, output the message You picked up a Sword; 4 Points is
awarded.
(4) For each Demon (D) encountered, display the message A demon has attacked;
subtract 5 points.
The game is over when
(a) The player types in 99 this ends the game. Print out the accumulated points
(b) When the points are below 0 the player is killed. Display You are killed if the point
garnered by the player is below zero.
Make sure the player does not go beyond the array boundary. The boundary is limited by the
size of the array of 19 elements.

Data Structures using Java

F
I
L
E
M
O
N

eugene . jay . john. lary . romel . romelyn

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

31
SAMPLE OUTPUT
D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

32
2-Dimensional Array
One dimensional array can be visualized as a stack of elements; two dimensional arrays can be
visualized as a multicolumn table or grid.
By convention, the first subscript is understood to be for rows and the second for columns. By
default, both subscripts start with zero.
The following table illustrates how the subscripts are specified for this array, which has three (3)
rows and four (4) columns. The array consists of 12 elements (3 x 4).

D
R
F
I
L
E
M
O
N
C

A
G
U
I
L
A
R

0 [0][0] [0][1] [0][2] [0][3]


1 [1][0] [1][1] [1][2] [1][3]
2 [2][0] [2][1] [2][2] [2][3]

Declaring a Variable to Refer to an Array


data_type variable[][] = new data_type[number of rows][number of columns]
int values[][] = new int[4][3];

Initializing, and Accessing an Array


values[0][0] = 1;
values[0][1] = 2;
values[1][0] = 3;
values[1][1] = 4;

int values[][] = {{1,2}, {3,4}};

array with 4 rows and 3 columns

VISUALIZATION
0
1
0
1
2
1
3
4

array with 2 rows and 2 columns

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

33
2-Dimensional Array: Multiplication Table
The code below will process and display the 7x7 Multiplication Table

D
R
F
I
L
E
M
O
N

public class Main {


public static void main(String[] args) {
int myarr[][]=new int [7][7];
String s="MULTIPLICATION TABLE\n\n\t ";
for(int x=0; x<7; x++){
s =s + "\t " + (x+1);
}

C
A
G
U
I
L
A
R

s+="\n";
for(int x=0; x<7; x++){
s =s + "\t" + (x+1);

I
N
F
O
R
M
A
T
I
O
N

for(int y=0; y<7; y++){


myarr[x][y]=(x+1) * (y+1);
//if-else is setting the alignment of numbers
if(myarr[x][y] >= 10)
s += "\t" + myarr[x][y];
else
s += "\t " + myarr[x][y];
}
s+="\n";

T
E
C
H
N
O
L
O
G
Y

}
System.out.println(s);
}
}
//Programmed by: Ms Jovelyn B. Flores

T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

34
SORTING AND SEARCHING ALGORITHM USING JAVA
D
R

SORTING
It is the process of putting a collection of data in some order. Professional programmers use
one of the java.util.Arrays.sort() methods; they do not write their own, except perhaps in
unusual cases.
Method
Arrays sort methods
Arrays.sort(pa);
Arrays.sort(pa, from, to);

Description

Sorts the elements of the array of a primitive type into


ascending order using their natural ordering.
Sorts the elements pa[from]...pa[to-1] of a primitive type into
ascending order.

public class SortDemo {


public static void main(String[] args){
int[] arrInt = {2, 87, 45, 5, 12, 20, 1, 7};
int i;

A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N

for (i = arrInt.length; --i >= 0; ) {


for (int j = 0; j < i; j++) {
if (arrInt[j] > arrInt[j+1]) {
int temp = arrInt[j];
arrInt[j] = arrInt[j+1];
arrInt[j+1] = temp;
}
}
}

T
E
C
H
N
O
L
O
G
Y

System.out.println("SORTED VALUES");
for (i = 0; i < arrInt.length; i++)
System.out.print(arrInt[i] + " ");

T
R
A
I
N
I
N
G

}
}
//Programmed by: Mr. Jay A. Gofredo

I
N
S
T
I
T
U
T
E

OUTPUT
SORTED VALUES
1 2 5 7 12 20 45 87

Data Structures using Java

F
I
L
E
M
O
N

eugene . jay . john. lary . romel . romelyn

35
The program above can be written using the code below using the statement Arrays.sort().

D
R
F
I
L
E
M
O
N

import java.util.*;
public class SortDemo {
public static void main(String[] args){
int[] arrInt = {2,87,45,5,12,20,1,7};
int i;
Arrays.sort(arrInt);

System.out.println("SORTED VALUES IN ASCENDING ORDER");


for (i = 0; i < arrInt.length; i++)
System.out.print(arrInt[i] + " ");

A
G
U
I
L
A
R

System.out.println("\n\nSORTED VALUES IN DESCENDING ORDER");


for (i = arrInt.length - 1; i >= 0; i--)
System.out.print(arrInt[i] + " ");
System.out.println("\n\n");
}
}

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y

OUTPUT
SORTED VALUES IN ASCENDING ORDER
1 2 5 7 12 20 45 87
SORTED VALUES IN DESCENDING ORDER
87 45 20 12 7 5 2 1

T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

36
LINEAR SEARCH
Linear searching is a good way to find an element from the array. The array can be of any order,
it checks whether a certain element (number, string, etc.) is in a specified array or not.

D
R
F
I
L
E
M
O
N

import java.util.*;
public class SearchValue {
static int searchItem(final int[] data, final int key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}

C
A
G
U
I
L
A
R

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
final int arr[] = new int[5];

I
N
F
O
R
M
A
T
I
O
N

System.out.println("Enter 5 numbers");
for (int i = 0; i < arr.length; i++)
arr[i] = input.nextInt();

System.out.print("Enter the element to search: ");


int num=input.nextInt();

T
E
C
H
N
O
L
O
G
Y

int n = searchItem(arr, num);


if ((n >= 0) && (n < arr.length))
System.out.println(num + " is found at index: " + n);
else
System.out.println("Not Found");
}

T
R
A
I
N
I
N
G

}
//Programmed by: Mr. Jay A. Gofredo

I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

37
LINKED LIST
A method of organizing stored data in a computers memory or on a storage medium based on
the logical order of the data and not on its physical order. All stored data are assigned with
physical address in the memory which the computer uses to locate the information.
In each record, there is a field that contains a reference (i.e., a link) to the next record in the
sequence. Singly-linked lists contain nodes which have a data field as well as a next field, which
points to the next node in the linked list.

D
R
F
I
L
E
M
O
N
C

A linked list whose nodes contain two fields: an integer value and a link to the next node

QUEUE
A queue is a particular kind of collection in which the entities in the collection are kept in order
and the principal operations on the collection are the addition of entities to the rear terminal
position and removal of entities from the front terminal position. This makes the queue a FirstIn-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue
will be the first one to be removed.

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y

Representation of a FIFO Queue

STACK
A stack is a Last-In-First-Out (LIFO) data structure. A stack is characterized by only two
fundamental operations: push and pop. The push operation adds to the top of the list. The pop
operation removes an item from the top of the list, and returns this value to the caller.

T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Representation of a LIFO stack


Data Structures using Java

A
G
U
I
L
A
R

eugene . jay . john. lary . romel . romelyn

38
SAMPLE LINKED-LIST OPERATION
import javax.swing.*;
class Node {
int no;
Node ptr;

D
R
F
I
L
E
M
O
N

//constructor of class Node


Node(int n, Node p)
{
no = n;
ptr = p;
}

C
A
G
U
I
L
A
R

static void printList(Node list){


//display list
Node node =list;
String out=";
while (node !=null)
{
out += node + > *" + node.no + "+ + node.ptr + \n ;
node =node.ptr;
}
JOptionPane.showMessageDialog(null,link list \n+out);
}
public static void main(String args[]) { //main method
int noNodes = Integer.parseInt(JOptionPane.showInputDialog(number of nodes: ));
if (noNodes>=2 && noNodes<=5)
{
int ctr = 1;
Node head, dummy, node;
int value = Integer.parseInt(JOptionPane.showInputDialog(number + ctr));
//1st node created
node = new Node(value, null);
head = node;
ctr++;
//2nd upto last node created
while(ctr<=noNodes)
{
value = Integer.parseInt(JOptionPane.showInputDialog(number + ctr));
dummy = new Node(value,null);
node.ptr = dummy;
node = dummy;
ctr++;
}
printList(head);
}
} }
Data Structures using Java

//call static method printList

eugene . jay . john. lary . romel . romelyn

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

39
MENU: QUEUE MANIPULATION
D
R

import javax.swing.*;

F
I
L
E
M
O
N

class nodeMenu
{
Object info;
nodeMenu link;

static nodeMenu head, next, tail;


public nodeMenu(Object i, nodeMenu l)
{
info = i;
link = l;
}

A
G
U
I
L
A
R

//CONSTRUCTOR

static void doAdd()


{
int i = Integer.parseInt(JOptionPane.showInputDialog(Add Node\nEnter a number));
if(head == null)
{
head = new nodeMenu(i,null);
tail = head;
}
else
{
next = new nodeMenu(i,null);
tail.link = next;
tail=next;
}
}
static void doDisplay()
{
String output=";
if (head != null)
{
next = head;
while(next!=null)
{
output = output + (next + -> + next.info + + next.link + \n);
next = next.link;
}
JOptionPane.showMessageDialog(null, Display List\n + output);
}
else
JOptionPane.showMessageDialog(null, List is empty);
}
Data Structures using Java

eugene . jay . john. lary . romel . romelyn

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

40
static void doDelete()
{
if(head!=null)
{
next = head;
head = next.link;
next = null;
JOptionPane.showMessageDialog(null,Delete Node\nHEAD node deleted);
}
else
JOptionPane.showMessageDialog(null,List is empty);
}
public static void main(String[] args)
{
String menu = MAIN MENU\n +
*1+ Add node\n+
*2+ Display list\n +
*3+ Delete node\n +
*4+ Exit;
int choice=0;
do
{
String str = JOptionPane.showInputDialog(menu);
if(str.equals())
JOptionPane.showMessageDialog(null, enter a number);
else
{
choice = Integer.parseInt(str);
if (choice == 1)
doAdd();
else if (choice == 2)
doDisplay();
else if (choice == 3)
doDelete();
else if (choice == 4)
JOptionPane.showMessageDialog(null, Programmer: eugene);
}
} while(choice != 4);
}

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G

}
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

41
D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

ACTIVITY
Stack Operation using Linked List
Create a program using linked list that will ask the user to enter the number of elements of the
linked list. Implement the operation involving stacks where elements are added and deleted at
the top of the stack or at the beginning of the list.

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

42
DATABASE MANIPULATION
This program shows a simple data manipulation using MS Access.

D
R

Glossary of terms:
1. Connection
A connection (session) with a specific database. SQL statements are executed and results
are returned within the context of a connection.

F
I
L
E
M
O
N

2. ResultSet
A table of data representing a database result set, which is usually generated by executing a
statement that queries the database.
3. Statement
The object used for executing a static SQL statement and returning the results it produces.
4. Class.forname
Returns the Class object associated with the class or interface with the given string name.
5. DriverManager.getConnection
Attempts to establish a connection to the given database URL.
6. createStatement
Creates a Statement object for sending SQL statements to the database.
7. executeQuery
Executes the given SQL statement, which returns a single ResultSet object.
8. executeUpdate
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE
statement.
9. Close
Releases this Statement object's database and JDBC resources immediately instead of
waiting for this to happen when it is automatically closed.
10. Next
Moves the cursor down one row from its current position.
11. getInt / getString / getDouble / getBoolean / getByte / getFloat
Retrieves the value of the designated column in the current row of the ResultSet.
12. Exception handling
A programming language construct designed to handle the occurrence of exceptions (special
conditions that change the normal flow of program execution).

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

43
STEPS IN MANIPULATING A DATABASE
1. Create a database named student.accdb

D
R

2. Create a table named tblStudInfo. The structure is show below.

F
I
L
E
M
O
N
C
A
G
U
I
L
A
R

3. Add 8 records to the table

I
N
F
O
R
M
A
T
I
O
N

4. Open Netbeans Create a class named DatabaseDemo Type the code below.

/**
* @author Eugene F. Galang

*/
import java.sql.*;
public class DatabaseDemo {

T
R
A
I
N
I
N
G

public static void main(String args[])


{
Connection con;
ResultSet rs;
Statement stmt;
String qry;
int ctr;
String url =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/ student.accdb";

System.out.println("Database manipulation using Access");


Data Structures using Java

T
E
C
H
N
O
L
O
G
Y

eugene . jay . john. lary . romel . romelyn

I
N
S
T
I
T
U
T
E

44
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url,"","");

D
R
F
I
L
E
M
O
N

stmt = con.createStatement();
qry = "Select * from tblstudinfo";
rs = stmt.executeQuery(qry);

C
A
G
U
I
L
A
R

//DISPLAY CONTENT OF TABLE tblstudinfo


while (rs.next())
{
System.out.print(rs.getInt("id") + ", ");
System.out.print(rs.getString("sname") + ", ");
System.out.println(rs.getString("sadd"));
}

I
N
F
O
R
M
A
T
I
O
N

/*
//CODE FOR APPENDING A RECORD
qry = "INSERT INTO tblStudInfo VALUES(150,JING,'ILOCOS')";
ctr = stmt.executeUpdate(qry);
System.out.println("No of rows affected=" + ctr);

T
E
C
H
N
O
L
O
G
Y

//CODE FOR UPDATING AN EXISTING RECORD


qry = "UPDATE tblStudInfo SET sname='JORGE' WHERE id=105";
ctr = stmt.executeUpdate(qry);
System.out.println("No of rows affected=" + ctr);

//CODE FOR DELETING AN EXISTING RECORD.


qry = "DELETE FROM tblStudInfo where id=105";
ctr = stmt.executeUpdate(qry);
System.out.println("No of rows affected=" + ctr);
*/
stmt.close();
con.close();
}catch(Exception e)

T
R
A
I
N
I
N
G

System.out.println("ERROR-->" + e);

}
I
N
S
T
I
T
U
T
E

}
}

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

45
ACTIVITY
Database Manipulation

D
R

Create a program that will implement the DatabaseDemo code using Menu. Sample menu is
shown below.
MAIN MENU
[1] Add
[2] Edit
[3] Delete
[4] View a record
[5] View all
[6] Exit

C
A
G
U
I
L
A
R

Where:
Add
Edit
Delete
View a record
View all
Exit

F
I
L
E
M
O
N

Insert a new record


Update an existing record
Remove an existing record
Display the information of a specified user account
Display all records
Terminate system run

I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y

REFERENCES
Webpage URL:
http://dwcl.wordpress.com/
http://mathbits.com/mathbits/java/methods/Lesson1.htm
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
http://www.webopedia.com/TERM/L/linked_list.html
http://en.wikipedia.org/wiki/Linked_list
http://en.wikipedia.org/wiki/Queue_%28data_structure%29
http://en.wikipedia.org/wiki/Stack_%28data_structure%29
http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/lang/Class.html
http://www.dotnetfunda.com/articles/article700-database-operation-in-java-usingjdbc-.aspx
http://www.csd.abdn.ac.uk/~bscharla/teaching/CS3514/practicals/AnduinBank/src/com
/anduin/Account.java
Data Structures using Java

eugene . jay . john. lary . romel . romelyn

T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

46
ADDITIONAL ACTIVITIES
1. Write a program that mimics a calculator. The program should take two integers and the
operation to be performed. It should then output the number, the operator and the result. (For
division, if the denominator is zero, output an appropriate message).
2. The cost of an international call from New York to Paris is calculated as follows: Connection fee
$1.99, $2.00 for the first three minutes and $0.45 for each additional minute. Write a program
that prompts the user to enter the number of minutes the call lasted and outputs the amount
due. Format your output with two decimal places.
3. Wire-Gram has hired you as a consultant to build an application that will calculate the cost of
telegram. The application should include a way to enter the message and compute the cost
based on $4.20 for the first 10 characters and $0.02 for each letter over 10. The total number of
letters and the total cost should display for the person entering the telegram.
4. Consider a problem in which the percentage commission earned by a salesperson is determined
by a commission code, as shown in the following table:
SALESPERSON CODE
COMMISSION FACTOR (%)
R or r
18
T or t
10
S or s
22
Y or y
10
The commission is the product of the total sales and the commission factor. Salespeople whose
code X receive half of their total sales as their commission. Write a program that accepts the
total sales and commission code then outputs the total cost to the customer.
5. Write a program that will compute for the factorial of a supplied number. The factorial of the
number is the product of those numbers starting from 1 to the supplied number.
6. Write a program that will derive the sum of the square of series of a number. For example, an
2
2
2
2
2
input of 5 will produce 55 (1 + 2 + 3 + 4 + 5 = 55).
7. Write a program that reverses the input number. Formulate an equation to come up with the
answer. Apply loop statements in your solution. For example, an input of 1234 will produce
4321.
8. Write a program to convert a number to an English equivalent string formed from the digits. For
example, 123 represented by one two three and 9620 is represented by nine six two zero.
9. Write a program that will ask for inputs that will only terminate at an entry of zero. Calculate the
average of only positive and negative numbers.
10. Write a program that takes a one-line sentence as input and then outputs the following
response:
o If the sentence ends with the question mark ? and the input contains an even number
of characters, then output the word Yes.
o If the sentence ends with the question mark ? and the input contains an odd number
of characters, then output the word No.
o If the sentence ends with the exclamation mark ! then output the word Wow.
o In all other cases, your program will output the string You always say followed by the
input string enclosed in quotes.
Your output should all be on one line. Be sure to note that in the last case, your output must
include quotation marks around the echoed input string. Your program should have a loop that
allows the user to repeat this until the user indicates that he wants to end the program. Your
program does not have to check the input to see that the user entered a legitimate sentence.

Data Structures using Java

eugene . jay . john. lary . romel . romelyn

D
R
F
I
L
E
M
O
N
C
A
G
U
I
L
A
R
I
N
F
O
R
M
A
T
I
O
N
T
E
C
H
N
O
L
O
G
Y
T
R
A
I
N
I
N
G
I
N
S
T
I
T
U
T
E

You might also like