SlideShare a Scribd company logo
1 of 46
Download to read offline
DATA STRUCTURES
USING JAVA
PROGRAMMING DEPARTMENT
November 2010
Programming NC IV
Information and Communications Technology
Compiled by:
EUGENE F. GALANG
Area Chair
Reviewed by:
ANTONIO M. ERRO
Dean, Academic Affairs
Approved by:
CONRADO T. CAMIGLA
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
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
TABLE OF CONTENTS
Introduction to Java 4
Two main deployment environments:
Phases of a Java Program
Getting to know your Programming Environment using NetBeans
Dissecting a Program 9
8 Primitive Data Types 9
Variables 10
Operators 11
Arithmetic
Increment/Decrement
Relational
Logical and Boolean Logical
Conditional/Ternary
Order of Precedence
Statements and Blocks 15
Activity – Homeowner Sales 17
Control Flow Statements 18
If statement
If-else statement
If-else-if statement
Switch statement
Repetition Control Structures 22
While and do-while statements
For statement
Continue statement
Break statement
Method: Passing Parameters 25
Fibonacci Series 26
Nested Loop 26
ACTIVITY 27
FOR loop: POWER
Nested Loop & Methods: Diamond
Arrays
1 dimensional array 28
ACTIVITY 30
Number Sequence
HARRY POTTER & THE AMAZING WIZARD
3
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
2 dimensional array 32
Sorting and searching 34
Link list 37
Queue 37
Stack 37
ACTIVITY 41
Stack Operation using Linked List
Database Manipulation 42
ACTIVITY 45
Database Manipulation
4
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
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.
Phases of a Java Program
Task Tool to use Output
Write the program Any text editor File with .java extension
Compile the program Java Compiler File with .class extension (Java bytecodes)
Run the program Java Interpreter Program Output
5
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
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.
After opening NetBeans IDE, you will see the splash screen and the graphical user interface
(GUI) below.
SHORTCUT ICON
6
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
Step 2: Make a project
Click on File  New Project  Java  Java Application  Next
Now, a New Application dialog will appear. Edit the Project Name part and type in
"HelloApplication", then click Finish
7
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
Step 3. Type the program code then Run File
Code / Line no. These lines of code are generated
automatically by NetBeans
Launching pad of
Java application
8
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
A common bug in Java program (ex. “Semi-colon expected”).
Statement
Right-click
code, Select
Run File
Output
Semi-colon expected
9
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
DISSECTING A PROGRAM
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.
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.
Prints the text enclosed by
quotation on the screen.
Class Main should
be saved in a file
called Main.java
10
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
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.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
Float 0.0f
double 0.0d
Char 'u0000'
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];  Value enclosed with square brace ([ ]) is optional.
Example:
int rate = 80;  Declare and initialize variable rate
float salary;  Declare variable salary
salary = 15.80;  Initialize variable salary
11
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
OPERATORS
1. Arithmetic
Operation
Arithmetic
operator
Algebraic
expression
Java
expression
Description
Addition + f + 7 f + 7 Add f and 7
Subtraction - p – c p - c Subtract c from p
Multiplication * bm b * m Multiply b by m
Division / x / y x / y Divide x by y
Modulus % r mod s r % s Compute the remainder
by dividing r by s
import java.io.*;
public class ArithmeticOperatorInput {
public static void main( String[] args ) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x, y;
String str;
str = br. readLine();
x = Integer.parseInt(str);
y = Integer.parseInt(br.readLine());
System.out.println(“Product : “ + (x * y));
}
}
A java package for input /
output operation.
Creating an
object br
intended
for String
input values
Using function readLine() to read
a value to be stored in variable str.
Converting String str to Integer value
Reading and converting String input
to integer value
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);
}
}
12
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
2. Increment / Decrement Operator
Operation
Arithmetic
operator
Algebraic
expression
Description
Increment ++ x++ Increments x by 1; evaluates the value
of x before it was incremented.
++x Increments x by 1; evaluates the value
of x after it was incremented.
Decrement -- x-- Decrements x by 1; evaluates the value
of x before it was decremented.
--x 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);
}
}
13
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
3. Relational
4. Logical and Boolean Logical
P Q
Logical AND (&&)
Boolean Logical AND (&)
Logical OR (||)
Boolean Logical inclusive OR (|)
NOT P EXCLUSIVE
OR (^)
T T T T F F
T F F T F T
F T F T T T
F F F F 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
Operation
Arithmetic
operator
Algebraic
expression
Description
Greater than > a > b Is a greater than b
Greater than or equal to >= a >= b Is a greater than or equal to b
Less than < a < b Is a less than b
Less than or equal to <= a <= b Is a less than or equal to b
Equal to == a == b Is a equal to b
Not equal to != a != b Is a not equal to b
14
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
ODER OF PRECEDENCE
Operator precedence defines the compiler’s order of evaluation of operators so as to
come up with an unambiguous result.
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;
public class ConditionalOperator {
public static void main( String[] args ){
String status = "";
int grade = 80;
//get status of the student
status = (grade >= 60)?"Passed":"Fail";
//print status
System.out.println( status );
} }
class ConditionalOperator {
public static void main( String[] args ){
int score = 0;
char answer = 'a';
score = (answer == 'a') ? 10 : 0;
System.out.println("Score = " + score );
} }
15
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
STATEMENTS AND BLOCKS
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; // assignment statement
aValue++; // increment statement
System.out.println("Hello World!"); // method invocation statement
Blocks
A block is a group of zero or more statements between balanced braces and can be used
anywhere.
Operators: / * – +
Compute and display the values for x, y and its average.
x = – 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);
}
}
Output:
x = -20
y = 80
average = 30
16
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
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
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.
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);
} }
Output:
GROSS = 800.0
TAX = 40.0
NET = 760.0
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);
}
}
17
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
ACTIVITY
Homeowner Sales
Laboratory problem was downloaded and edited from Thomas L. Brown’s 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.
Input (Standard system input–the keyboard):
 homeowners name (String)
 house price (double) and
 sales commission rate (int) - for example, 6 will be entered for 6% rate.
Output (Standard output–the terminal screen):
 homeowner’s 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.
18
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
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.
19
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
class BlockDemo
{ //begin class block
public static void main(String[] args)
{ //begin main block
boolean condition = true;
if (condition)
{ // begin block 1
System.out.println("Condition is true.");
} // end block 1
else
{ // begin block 2
System.out.println("Condition is false.");
} // end block 2
} //end main block
} //end class block
20
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
selection structure – if
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”);
}
}
21
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
if: Odd or Even
output
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;
int sqr = num * num;
if(num % 2 == 0)
JOptionPane.showMessageDialog(null,num +” is evennSquared value = ” + sqr);
else
JOptionPane.showMessageDialog(null,num +” is oddnAbsolute value = ” + abs);
}
}
22
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
switch statement
Another way to indicate a branch is through the switch keyword. The switch construct
allows branching on multiple outcomes.
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;
}
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)
}
23
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
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.
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.
 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)
}
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
24
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
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.
 The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop.
 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.
class ForDemo {
public static void main(String[] args){
for(int i = 1; i < 11; i++){
System.out.println("Count is: " + i);
}
}
}
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.");
}
}
25
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
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.
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);
}
}
26
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
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.
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
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 +” “);
while(temp<13)
{
y=x;
x=temp;
temp = x + y;
System.out.print(temp + ” “);
}
}
public static void main(String args[])
{
fibo(); //method call
}
}
class NestedSeries {
public static void main(String args[]) {
int num1, num2;
for(num2 = 1; num2 <= 5; num2++) {
for(num1 = 1; num1 <= num2; num1++)
System.out.print(num1);
System.out.println();
}
}
} }
OUTPUT
1
12
123
1234
12345
27
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
ACTIVITY
FOR loop: POWER
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)
Example: 5
3
Base: 5
Exponent: 3
Result: 125
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.
28
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
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.
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; // declares an array of integers
anArray = new int[10]; // 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]);
29
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
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
1-Dimensional Array
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] );
}
}
}
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+ + ” “);
}
}
}
30
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
ACTIVITY
Number Sequence
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 North
W S S D B D W B B D W S W D B D S W B S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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.
31
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
SAMPLE OUTPUT
32
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
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).
0 1 2 3
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];  array with 4 rows and 3 columns
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 2 rows and 2 columns
VISUALIZATION
0 1
0 1 2
1 3 4
33
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
2-Dimensional Array: Multiplication Table
The code below will process and display the 7x7 Multiplication Table
public class Main {
public static void main(String[] args) {
int myarr[][]=new int [7][7];
String s="MULTIPLICATION TABLEnnt ";
for(int x=0; x<7; x++){
s =s + "t " + (x+1);
}
s+="n";
for(int x=0; x<7; x++){
s =s + "t" + (x+1);
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";
}
System.out.println(s);
}
}
//Programmed by: Ms Jovelyn B. Flores
34
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
SORTING AND SEARCHING ALGORITHM USING JAVA
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 Description
Arrays sort methods
Arrays.sort(pa); Sorts the elements of the array of a primitive type into
ascending order using their natural ordering.
Arrays.sort(pa, from, to); Sorts the elements pa[from]...pa[to-1] of a primitive type into
ascending order.
OUTPUT
SORTED VALUES
1 2 5 7 12 20 45 87
public class SortDemo {
public static void main(String[] args){
int[] arrInt = {2, 87, 45, 5, 12, 20, 1, 7};
int i;
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;
}
}
}
System.out.println("SORTED VALUES");
for (i = 0; i < arrInt.length; i++)
System.out.print(arrInt[i] + " ");
}
}
//Programmed by: Mr. Jay A. Gofredo
35
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
The program above can be written using the code below using the statement Arrays.sort().
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
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] + " ");
System.out.println("nnSORTED VALUES IN DESCENDING ORDER");
for (i = arrInt.length - 1; i >= 0; i--)
System.out.print(arrInt[i] + " ");
System.out.println("nn");
}
}
36
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
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;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int arr[] = new int[5];
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();
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");
}
}
//Programmed by: Mr. Jay A. Gofredo
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.
37
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
LINKED LIST
A method of organizing stored data in a computer’s 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.
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 First-
In-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.
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.
Representation of a LIFO stack
38
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
SAMPLE LINKED-LIST OPERATION
import javax.swing.*;
class Node {
int no;
Node ptr;
//constructor of class Node
Node(int n, Node p)
{
no = n;
ptr = p;
}
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); //call static method printList
}
} }
39
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
MENU: QUEUE MANIPULATION
import javax.swing.*;
class nodeMenu
{
Object info;
nodeMenu link;
static nodeMenu head, next, tail;
public nodeMenu(Object i, nodeMenu l) //CONSTRUCTOR
{
info = i;
link = l;
}
static void doAdd()
{
int i = Integer.parseInt(JOptionPane.showInputDialog(“Add NodenEnter 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 Listn” + output);
}
else
JOptionPane.showMessageDialog(null, “List is empty”);
}
40
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
static void doDelete()
{
if(head!=null)
{
next = head;
head = next.link;
next = null;
JOptionPane.showMessageDialog(null,”Delete NodenHEAD node deleted”);
}
else
JOptionPane.showMessageDialog(null,”List is empty”);
}
public static void main(String[] args)
{
String menu = “MAIN MENUn” +
“*1+ Add noden”+
“*2+ Display listn” +
“*3+ Delete noden” +
“*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);
}
}
41
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
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.
42
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
DATABASE MANIPULATION
This program shows a simple data manipulation using MS Access.
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.
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).
43
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
STEPS IN MANIPULATING A DATABASE
1. Create a database named student.accdb
2. Create a table named tblStudInfo. The structure is show below.
3. Add 8 records to the table
4. Open Netbeans  Create a class named DatabaseDemo  Type the code below.
/**
* @author Eugene F. Galang
*/
import java.sql.*;
public class DatabaseDemo {
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");
44
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
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url,"","");
stmt = con.createStatement();
qry = "Select * from tblstudinfo";
rs = stmt.executeQuery(qry);
//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"));
}
/*
//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);
//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) { System.out.println("ERROR-->" + e); }
}
}
45
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
ACTIVITY
Database Manipulation
Create a program that will implement the DatabaseDemo code using Menu. Sample menu is
shown below.
Where:
Add  Insert a new record
Edit  Update an existing record
Delete  Remove an existing record
View a record  Display the information of a specified user account
View all  Display all records
Exit  Terminate system run
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-using-
jdbc-.aspx
 http://www.csd.abdn.ac.uk/~bscharla/teaching/CS3514/practicals/AnduinBank/src/com
/anduin/Account.java
MAIN MENU
[1] Add
[2] Edit
[3] Delete
[4] View a record
[5] View all
[6] Exit
46
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
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
input of 5 will produce 55 (1
2
+ 2
2
+ 3
2
+ 4
2
+ 5
2
= 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.

More Related Content

What's hot

Uniti classnotes
Uniti classnotesUniti classnotes
Uniti classnotesSowri Rajan
 
FNT Software Solutions Pvt Ltd Placement Papers - PHP Technologies
FNT Software Solutions Pvt Ltd Placement Papers - PHP TechnologiesFNT Software Solutions Pvt Ltd Placement Papers - PHP Technologies
FNT Software Solutions Pvt Ltd Placement Papers - PHP Technologiesfntsofttech
 
Introduction to JADE (Java Agent DEvelopment) Framework
Introduction to JADE (Java Agent DEvelopment) FrameworkIntroduction to JADE (Java Agent DEvelopment) Framework
Introduction to JADE (Java Agent DEvelopment) FrameworkAhmed Gad
 
(D 15 180770107240)
(D 15 180770107240)(D 15 180770107240)
(D 15 180770107240)RaviModi37
 
Cosc 1436 java programming/tutorialoutlet
Cosc 1436 java programming/tutorialoutletCosc 1436 java programming/tutorialoutlet
Cosc 1436 java programming/tutorialoutletWoodardz
 
SherLog: Error Diagnosis by Connecting Clues from Run-time Logs
SherLog: Error Diagnosis by Connecting Clues from Run-time LogsSherLog: Error Diagnosis by Connecting Clues from Run-time Logs
SherLog: Error Diagnosis by Connecting Clues from Run-time LogsDacong (Tony) Yan
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of ckinish kumar
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchAlbern9271
 
Embedded SW Interview Questions
Embedded SW Interview Questions Embedded SW Interview Questions
Embedded SW Interview Questions PiTechnologies
 

What's hot (14)

pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
Uniti classnotes
Uniti classnotesUniti classnotes
Uniti classnotes
 
FNT Software Solutions Pvt Ltd Placement Papers - PHP Technologies
FNT Software Solutions Pvt Ltd Placement Papers - PHP TechnologiesFNT Software Solutions Pvt Ltd Placement Papers - PHP Technologies
FNT Software Solutions Pvt Ltd Placement Papers - PHP Technologies
 
Introduction to JADE (Java Agent DEvelopment) Framework
Introduction to JADE (Java Agent DEvelopment) FrameworkIntroduction to JADE (Java Agent DEvelopment) Framework
Introduction to JADE (Java Agent DEvelopment) Framework
 
Introduction of C++ By Pawan Thakur
Introduction of C++ By Pawan ThakurIntroduction of C++ By Pawan Thakur
Introduction of C++ By Pawan Thakur
 
(D 15 180770107240)
(D 15 180770107240)(D 15 180770107240)
(D 15 180770107240)
 
Cosc 1436 java programming/tutorialoutlet
Cosc 1436 java programming/tutorialoutletCosc 1436 java programming/tutorialoutlet
Cosc 1436 java programming/tutorialoutlet
 
Basics1
Basics1Basics1
Basics1
 
SherLog: Error Diagnosis by Connecting Clues from Run-time Logs
SherLog: Error Diagnosis by Connecting Clues from Run-time LogsSherLog: Error Diagnosis by Connecting Clues from Run-time Logs
SherLog: Error Diagnosis by Connecting Clues from Run-time Logs
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitch
 
Embedded SW Interview Questions
Embedded SW Interview Questions Embedded SW Interview Questions
Embedded SW Interview Questions
 

Viewers also liked

美 女 總 理 ----- 瑩 拉
美 女 總 理  ----- 瑩 拉美 女 總 理  ----- 瑩 拉
美 女 總 理 ----- 瑩 拉Jaing Lai
 
Artes tics
Artes ticsArtes tics
Artes ticsUPTC
 
TDC2016SP - TypeScript em aplicações modernas
TDC2016SP - TypeScript em aplicações modernasTDC2016SP - TypeScript em aplicações modernas
TDC2016SP - TypeScript em aplicações modernastdc-globalcode
 
Instruments
InstrumentsInstruments
InstrumentsSEBAS100
 
TDC2016SP - Enumerables
TDC2016SP - EnumerablesTDC2016SP - Enumerables
TDC2016SP - Enumerablestdc-globalcode
 
2008 02 01 Zeller
2008 02 01 Zeller2008 02 01 Zeller
2008 02 01 ZellerCHOOSE
 
franquicias existente en panama
franquicias existente en panamafranquicias existente en panama
franquicias existente en panamafmlisadomo
 
«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...
«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...
«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...BDA
 
TDC2016SP - Automação de testes funcionais com Python e Mechanize
TDC2016SP - Automação de testes funcionais com Python e MechanizeTDC2016SP - Automação de testes funcionais com Python e Mechanize
TDC2016SP - Automação de testes funcionais com Python e Mechanizetdc-globalcode
 
Entrega contínua com arquitetura distribuida
Entrega contínua com arquitetura distribuidaEntrega contínua com arquitetura distribuida
Entrega contínua com arquitetura distribuidaLeonardo Kobus
 
Minoristas independientes y las Franquicias
Minoristas independientes y las FranquiciasMinoristas independientes y las Franquicias
Minoristas independientes y las Franquiciasmariag0419
 
Funciones Básicas - EMdH
Funciones Básicas - EMdHFunciones Básicas - EMdH
Funciones Básicas - EMdHAdela M. Ramos
 
Building a Quantitative Trading Strategy To Beat the S&P500
Building a Quantitative Trading Strategy To Beat the S&P500Building a Quantitative Trading Strategy To Beat the S&P500
Building a Quantitative Trading Strategy To Beat the S&P500Karen Rubin
 
Divisibility rules
Divisibility rulesDivisibility rules
Divisibility rulesAYSHA NADA
 
China Jade not jaded
China Jade not jadedChina Jade not jaded
China Jade not jadedJohn Jeffery
 
Stamping Machine Report
Stamping Machine ReportStamping Machine Report
Stamping Machine ReportOliver Terry
 
JavaFX no Falando em Java 2007 - Sergio Lopes
JavaFX no Falando em Java 2007 - Sergio LopesJavaFX no Falando em Java 2007 - Sergio Lopes
JavaFX no Falando em Java 2007 - Sergio LopesCaelum
 
Como Python pode ajudar na automação do seu laboratório
Como Python pode ajudar na automação do  seu laboratórioComo Python pode ajudar na automação do  seu laboratório
Como Python pode ajudar na automação do seu laboratórioMarcel Caraciolo
 

Viewers also liked (20)

美 女 總 理 ----- 瑩 拉
美 女 總 理  ----- 瑩 拉美 女 總 理  ----- 瑩 拉
美 女 總 理 ----- 瑩 拉
 
Artes tics
Artes ticsArtes tics
Artes tics
 
TDC2016SP - TypeScript em aplicações modernas
TDC2016SP - TypeScript em aplicações modernasTDC2016SP - TypeScript em aplicações modernas
TDC2016SP - TypeScript em aplicações modernas
 
Instruments
InstrumentsInstruments
Instruments
 
TDC2016SP - Enumerables
TDC2016SP - EnumerablesTDC2016SP - Enumerables
TDC2016SP - Enumerables
 
2008 02 01 Zeller
2008 02 01 Zeller2008 02 01 Zeller
2008 02 01 Zeller
 
franquicias existente en panama
franquicias existente en panamafranquicias existente en panama
franquicias existente en panama
 
jj
jjjj
jj
 
«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...
«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...
«Кадровое обеспечение вакансий для участников ВЭД компаний-экспортеров Новоси...
 
TDC2016SP - Automação de testes funcionais com Python e Mechanize
TDC2016SP - Automação de testes funcionais com Python e MechanizeTDC2016SP - Automação de testes funcionais com Python e Mechanize
TDC2016SP - Automação de testes funcionais com Python e Mechanize
 
Entrega contínua com arquitetura distribuida
Entrega contínua com arquitetura distribuidaEntrega contínua com arquitetura distribuida
Entrega contínua com arquitetura distribuida
 
Minoristas independientes y las Franquicias
Minoristas independientes y las FranquiciasMinoristas independientes y las Franquicias
Minoristas independientes y las Franquicias
 
Funciones Básicas - EMdH
Funciones Básicas - EMdHFunciones Básicas - EMdH
Funciones Básicas - EMdH
 
Building a Quantitative Trading Strategy To Beat the S&P500
Building a Quantitative Trading Strategy To Beat the S&P500Building a Quantitative Trading Strategy To Beat the S&P500
Building a Quantitative Trading Strategy To Beat the S&P500
 
Divisibility rules
Divisibility rulesDivisibility rules
Divisibility rules
 
China Jade not jaded
China Jade not jadedChina Jade not jaded
China Jade not jaded
 
Stamping Machine Report
Stamping Machine ReportStamping Machine Report
Stamping Machine Report
 
JavaFX no Falando em Java 2007 - Sergio Lopes
JavaFX no Falando em Java 2007 - Sergio LopesJavaFX no Falando em Java 2007 - Sergio Lopes
JavaFX no Falando em Java 2007 - Sergio Lopes
 
TRAN THI NGOC-CV
TRAN THI NGOC-CVTRAN THI NGOC-CV
TRAN THI NGOC-CV
 
Como Python pode ajudar na automação do seu laboratório
Como Python pode ajudar na automação do  seu laboratórioComo Python pode ajudar na automação do  seu laboratório
Como Python pode ajudar na automação do seu laboratório
 

Similar to DATA STRUCTURES AND JAVA PROGRAMMING

Similar to DATA STRUCTURES AND JAVA PROGRAMMING (20)

Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)
 
Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)
 
A CASE STUDY JAVA IS SECURE PROGRAMMING LANGUAGE
A CASE STUDY  JAVA IS SECURE PROGRAMMING LANGUAGEA CASE STUDY  JAVA IS SECURE PROGRAMMING LANGUAGE
A CASE STUDY JAVA IS SECURE PROGRAMMING LANGUAGE
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java-Unit-I.ppt
Java-Unit-I.pptJava-Unit-I.ppt
Java-Unit-I.ppt
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
lecture 6
 lecture 6 lecture 6
lecture 6
 
Introduction to computer science
Introduction to computer scienceIntroduction to computer science
Introduction to computer science
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
Java lab1 manual
Java lab1 manualJava lab1 manual
Java lab1 manual
 
Srgoc java
Srgoc javaSrgoc java
Srgoc java
 
How to Learn Java Programming
How to Learn Java ProgrammingHow to Learn Java Programming
How to Learn Java Programming
 

More from Johndion Ruloma

COMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDE
COMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDECOMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDE
COMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDEJohndion Ruloma
 
Unpacking content standard (cs) and performance
Unpacking content standard (cs) and performanceUnpacking content standard (cs) and performance
Unpacking content standard (cs) and performanceJohndion Ruloma
 
BASIC MAINTENANCE OF COMPUTER
BASIC MAINTENANCE OF COMPUTERBASIC MAINTENANCE OF COMPUTER
BASIC MAINTENANCE OF COMPUTERJohndion Ruloma
 
Performing mensuration-and-calculations-common
Performing mensuration-and-calculations-commonPerforming mensuration-and-calculations-common
Performing mensuration-and-calculations-commonJohndion Ruloma
 
English gr-7-teachers guide q1and2
English gr-7-teachers guide q1and2English gr-7-teachers guide q1and2
English gr-7-teachers guide q1and2Johndion Ruloma
 
K to 12_PC LEARNING MODULE
K to 12_PC LEARNING MODULEK to 12_PC LEARNING MODULE
K to 12_PC LEARNING MODULEJohndion Ruloma
 
K to 12_entrep-based_pc_hardware_servicing_learning_module
K to 12_entrep-based_pc_hardware_servicing_learning_moduleK to 12_entrep-based_pc_hardware_servicing_learning_module
K to 12_entrep-based_pc_hardware_servicing_learning_moduleJohndion Ruloma
 
presentation on how to use powerpoint
presentation on how to use powerpointpresentation on how to use powerpoint
presentation on how to use powerpointJohndion Ruloma
 
Pc assembly with_configuration_and_networking
Pc assembly with_configuration_and_networkingPc assembly with_configuration_and_networking
Pc assembly with_configuration_and_networkingJohndion Ruloma
 

More from Johndion Ruloma (15)

COMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDE
COMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDECOMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDE
COMPUTER SYSTEM SERVICING NC II CURRICULUM GUIDE
 
Rubrics sample
Rubrics sampleRubrics sample
Rubrics sample
 
Unpacking content standard (cs) and performance
Unpacking content standard (cs) and performanceUnpacking content standard (cs) and performance
Unpacking content standard (cs) and performance
 
BASIC MAINTENANCE OF COMPUTER
BASIC MAINTENANCE OF COMPUTERBASIC MAINTENANCE OF COMPUTER
BASIC MAINTENANCE OF COMPUTER
 
Performing mensuration-and-calculations-common
Performing mensuration-and-calculations-commonPerforming mensuration-and-calculations-common
Performing mensuration-and-calculations-common
 
CHEFS TERMINOLOGIES
CHEFS TERMINOLOGIESCHEFS TERMINOLOGIES
CHEFS TERMINOLOGIES
 
Cms2 v1.2
Cms2 v1.2Cms2 v1.2
Cms2 v1.2
 
English gr-7-teachers guide q1and2
English gr-7-teachers guide q1and2English gr-7-teachers guide q1and2
English gr-7-teachers guide q1and2
 
Computer maintenance
Computer maintenanceComputer maintenance
Computer maintenance
 
K to 12_PC LEARNING MODULE
K to 12_PC LEARNING MODULEK to 12_PC LEARNING MODULE
K to 12_PC LEARNING MODULE
 
K to 12_entrep-based_pc_hardware_servicing_learning_module
K to 12_entrep-based_pc_hardware_servicing_learning_moduleK to 12_entrep-based_pc_hardware_servicing_learning_module
K to 12_entrep-based_pc_hardware_servicing_learning_module
 
presentation on how to use powerpoint
presentation on how to use powerpointpresentation on how to use powerpoint
presentation on how to use powerpoint
 
Pc assembly with_configuration_and_networking
Pc assembly with_configuration_and_networkingPc assembly with_configuration_and_networking
Pc assembly with_configuration_and_networking
 
Ehsd0348
Ehsd0348Ehsd0348
Ehsd0348
 
Computerized grade ppt
Computerized grade pptComputerized grade ppt
Computerized grade ppt
 

Recently uploaded

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Recently uploaded (20)

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

DATA STRUCTURES AND JAVA PROGRAMMING

  • 1. DATA STRUCTURES USING JAVA PROGRAMMING DEPARTMENT November 2010 Programming NC IV Information and Communications Technology Compiled by: EUGENE F. GALANG Area Chair Reviewed by: ANTONIO M. ERRO Dean, Academic Affairs Approved by: CONRADO T. CAMIGLA 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. 2 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 TABLE OF CONTENTS Introduction to Java 4 Two main deployment environments: Phases of a Java Program Getting to know your Programming Environment using NetBeans Dissecting a Program 9 8 Primitive Data Types 9 Variables 10 Operators 11 Arithmetic Increment/Decrement Relational Logical and Boolean Logical Conditional/Ternary Order of Precedence Statements and Blocks 15 Activity – Homeowner Sales 17 Control Flow Statements 18 If statement If-else statement If-else-if statement Switch statement Repetition Control Structures 22 While and do-while statements For statement Continue statement Break statement Method: Passing Parameters 25 Fibonacci Series 26 Nested Loop 26 ACTIVITY 27 FOR loop: POWER Nested Loop & Methods: Diamond Arrays 1 dimensional array 28 ACTIVITY 30 Number Sequence HARRY POTTER & THE AMAZING WIZARD
  • 3. 3 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 2 dimensional array 32 Sorting and searching 34 Link list 37 Queue 37 Stack 37 ACTIVITY 41 Stack Operation using Linked List Database Manipulation 42 ACTIVITY 45 Database Manipulation
  • 4. 4 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 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. Phases of a Java Program Task Tool to use Output Write the program Any text editor File with .java extension Compile the program Java Compiler File with .class extension (Java bytecodes) Run the program Java Interpreter Program Output
  • 5. 5 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 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. After opening NetBeans IDE, you will see the splash screen and the graphical user interface (GUI) below. SHORTCUT ICON
  • 6. 6 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 Step 2: Make a project Click on File  New Project  Java  Java Application  Next Now, a New Application dialog will appear. Edit the Project Name part and type in "HelloApplication", then click Finish
  • 7. 7 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 Step 3. Type the program code then Run File Code / Line no. These lines of code are generated automatically by NetBeans Launching pad of Java application
  • 8. 8 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 A common bug in Java program (ex. “Semi-colon expected”). Statement Right-click code, Select Run File Output Semi-colon expected
  • 9. 9 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 DISSECTING A PROGRAM 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. 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. Prints the text enclosed by quotation on the screen. Class Main should be saved in a file called Main.java
  • 10. 10 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 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. Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L Float 0.0f double 0.0d Char 'u0000' 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];  Value enclosed with square brace ([ ]) is optional. Example: int rate = 80;  Declare and initialize variable rate float salary;  Declare variable salary salary = 15.80;  Initialize variable salary
  • 11. 11 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 OPERATORS 1. Arithmetic Operation Arithmetic operator Algebraic expression Java expression Description Addition + f + 7 f + 7 Add f and 7 Subtraction - p – c p - c Subtract c from p Multiplication * bm b * m Multiply b by m Division / x / y x / y Divide x by y Modulus % r mod s r % s Compute the remainder by dividing r by s import java.io.*; public class ArithmeticOperatorInput { public static void main( String[] args ) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int x, y; String str; str = br. readLine(); x = Integer.parseInt(str); y = Integer.parseInt(br.readLine()); System.out.println(“Product : “ + (x * y)); } } A java package for input / output operation. Creating an object br intended for String input values Using function readLine() to read a value to be stored in variable str. Converting String str to Integer value Reading and converting String input to integer value 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); } }
  • 12. 12 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 2. Increment / Decrement Operator Operation Arithmetic operator Algebraic expression Description Increment ++ x++ Increments x by 1; evaluates the value of x before it was incremented. ++x Increments x by 1; evaluates the value of x after it was incremented. Decrement -- x-- Decrements x by 1; evaluates the value of x before it was decremented. --x 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); } }
  • 13. 13 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 3. Relational 4. Logical and Boolean Logical P Q Logical AND (&&) Boolean Logical AND (&) Logical OR (||) Boolean Logical inclusive OR (|) NOT P EXCLUSIVE OR (^) T T T T F F T F F T F T F T F T T T F F F F 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 Operation Arithmetic operator Algebraic expression Description Greater than > a > b Is a greater than b Greater than or equal to >= a >= b Is a greater than or equal to b Less than < a < b Is a less than b Less than or equal to <= a <= b Is a less than or equal to b Equal to == a == b Is a equal to b Not equal to != a != b Is a not equal to b
  • 14. 14 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 ODER OF PRECEDENCE Operator precedence defines the compiler’s order of evaluation of operators so as to come up with an unambiguous result. 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; public class ConditionalOperator { public static void main( String[] args ){ String status = ""; int grade = 80; //get status of the student status = (grade >= 60)?"Passed":"Fail"; //print status System.out.println( status ); } } class ConditionalOperator { public static void main( String[] args ){ int score = 0; char answer = 'a'; score = (answer == 'a') ? 10 : 0; System.out.println("Score = " + score ); } }
  • 15. 15 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 STATEMENTS AND BLOCKS 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; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation statement Blocks A block is a group of zero or more statements between balanced braces and can be used anywhere. Operators: / * – + Compute and display the values for x, y and its average. x = – 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); } } Output: x = -20 y = 80 average = 30
  • 16. 16 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 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 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. 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); } } Output: GROSS = 800.0 TAX = 40.0 NET = 760.0 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); } }
  • 17. 17 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 ACTIVITY Homeowner Sales Laboratory problem was downloaded and edited from Thomas L. Brown’s 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. Input (Standard system input–the keyboard):  homeowners name (String)  house price (double) and  sales commission rate (int) - for example, 6 will be entered for 6% rate. Output (Standard output–the terminal screen):  homeowner’s 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.
  • 18. 18 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 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.
  • 19. 19 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 class BlockDemo { //begin class block public static void main(String[] args) { //begin main block boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block 1 else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } //end main block } //end class block
  • 20. 20 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 selection structure – if 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”); } }
  • 21. 21 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 if: Odd or Even output 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; int sqr = num * num; if(num % 2 == 0) JOptionPane.showMessageDialog(null,num +” is evennSquared value = ” + sqr); else JOptionPane.showMessageDialog(null,num +” is oddnAbsolute value = ” + abs); } }
  • 22. 22 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 switch statement Another way to indicate a branch is through the switch keyword. The switch construct allows branching on multiple outcomes. 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; } 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) }
  • 23. 23 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 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. 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.  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) } class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } }
  • 24. 24 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 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.  The continue Statement The continue statement skips the current iteration of a for, while , or do-while loop.  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. class ForDemo { public static void main(String[] args){ for(int i = 1; i < 11; i++){ System.out.println("Count is: " + i); } } } 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."); } }
  • 25. 25 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 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. 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); } }
  • 26. 26 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 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. 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 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 +” “); while(temp<13) { y=x; x=temp; temp = x + y; System.out.print(temp + ” “); } } public static void main(String args[]) { fibo(); //method call } } class NestedSeries { public static void main(String args[]) { int num1, num2; for(num2 = 1; num2 <= 5; num2++) { for(num1 = 1; num1 <= num2; num1++) System.out.print(num1); System.out.println(); } } } } OUTPUT 1 12 123 1234 12345
  • 27. 27 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 ACTIVITY FOR loop: POWER 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) Example: 5 3 Base: 5 Exponent: 3 Result: 125 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.
  • 28. 28 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 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. 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; // declares an array of integers anArray = new int[10]; // 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]);
  • 29. 29 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 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 1-Dimensional Array 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] ); } } } 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+ + ” “); } } }
  • 30. 30 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 ACTIVITY Number Sequence 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 North W S S D B D W B B D W S W D B D S W B S 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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.
  • 31. 31 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 SAMPLE OUTPUT
  • 32. 32 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 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). 0 1 2 3 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];  array with 4 rows and 3 columns 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 2 rows and 2 columns VISUALIZATION 0 1 0 1 2 1 3 4
  • 33. 33 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 2-Dimensional Array: Multiplication Table The code below will process and display the 7x7 Multiplication Table public class Main { public static void main(String[] args) { int myarr[][]=new int [7][7]; String s="MULTIPLICATION TABLEnnt "; for(int x=0; x<7; x++){ s =s + "t " + (x+1); } s+="n"; for(int x=0; x<7; x++){ s =s + "t" + (x+1); 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"; } System.out.println(s); } } //Programmed by: Ms Jovelyn B. Flores
  • 34. 34 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 SORTING AND SEARCHING ALGORITHM USING JAVA 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 Description Arrays sort methods Arrays.sort(pa); Sorts the elements of the array of a primitive type into ascending order using their natural ordering. Arrays.sort(pa, from, to); Sorts the elements pa[from]...pa[to-1] of a primitive type into ascending order. OUTPUT SORTED VALUES 1 2 5 7 12 20 45 87 public class SortDemo { public static void main(String[] args){ int[] arrInt = {2, 87, 45, 5, 12, 20, 1, 7}; int i; 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; } } } System.out.println("SORTED VALUES"); for (i = 0; i < arrInt.length; i++) System.out.print(arrInt[i] + " "); } } //Programmed by: Mr. Jay A. Gofredo
  • 35. 35 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 The program above can be written using the code below using the statement Arrays.sort(). 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 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] + " "); System.out.println("nnSORTED VALUES IN DESCENDING ORDER"); for (i = arrInt.length - 1; i >= 0; i--) System.out.print(arrInt[i] + " "); System.out.println("nn"); } }
  • 36. 36 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 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; } public static void main(String[] args) { Scanner input = new Scanner(System.in); final int arr[] = new int[5]; 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(); 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"); } } //Programmed by: Mr. Jay A. Gofredo 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.
  • 37. 37 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 LINKED LIST A method of organizing stored data in a computer’s 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. 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 First- In-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. 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. Representation of a LIFO stack
  • 38. 38 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 SAMPLE LINKED-LIST OPERATION import javax.swing.*; class Node { int no; Node ptr; //constructor of class Node Node(int n, Node p) { no = n; ptr = p; } 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); //call static method printList } } }
  • 39. 39 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 MENU: QUEUE MANIPULATION import javax.swing.*; class nodeMenu { Object info; nodeMenu link; static nodeMenu head, next, tail; public nodeMenu(Object i, nodeMenu l) //CONSTRUCTOR { info = i; link = l; } static void doAdd() { int i = Integer.parseInt(JOptionPane.showInputDialog(“Add NodenEnter 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 Listn” + output); } else JOptionPane.showMessageDialog(null, “List is empty”); }
  • 40. 40 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 static void doDelete() { if(head!=null) { next = head; head = next.link; next = null; JOptionPane.showMessageDialog(null,”Delete NodenHEAD node deleted”); } else JOptionPane.showMessageDialog(null,”List is empty”); } public static void main(String[] args) { String menu = “MAIN MENUn” + “*1+ Add noden”+ “*2+ Display listn” + “*3+ Delete noden” + “*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); } }
  • 41. 41 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 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.
  • 42. 42 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 DATABASE MANIPULATION This program shows a simple data manipulation using MS Access. 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. 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).
  • 43. 43 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 STEPS IN MANIPULATING A DATABASE 1. Create a database named student.accdb 2. Create a table named tblStudInfo. The structure is show below. 3. Add 8 records to the table 4. Open Netbeans  Create a class named DatabaseDemo  Type the code below. /** * @author Eugene F. Galang */ import java.sql.*; public class DatabaseDemo { 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");
  • 44. 44 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 try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection(url,"",""); stmt = con.createStatement(); qry = "Select * from tblstudinfo"; rs = stmt.executeQuery(qry); //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")); } /* //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); //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) { System.out.println("ERROR-->" + e); } } }
  • 45. 45 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 ACTIVITY Database Manipulation Create a program that will implement the DatabaseDemo code using Menu. Sample menu is shown below. Where: Add  Insert a new record Edit  Update an existing record Delete  Remove an existing record View a record  Display the information of a specified user account View all  Display all records Exit  Terminate system run 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-using- jdbc-.aspx  http://www.csd.abdn.ac.uk/~bscharla/teaching/CS3514/practicals/AnduinBank/src/com /anduin/Account.java MAIN MENU [1] Add [2] Edit [3] Delete [4] View a record [5] View all [6] Exit
  • 46. 46 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 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 input of 5 will produce 55 (1 2 + 2 2 + 3 2 + 4 2 + 5 2 = 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.