You are on page 1of 211

Name: Mr. Lodelio R.

Millo Educational Background

This course provides the students with fundamental understanding of structured programming using Java. It introduces the different concepts that are commonly associated with structured programming. The course is design to provide students an indepth look at Java Programming using the structured approached in a business problemsolving environment

This course aims to enhance students knowledge in advance JAVA programming.


At the end of the course, the students are expected to:

Appreciate the use of existing java classes such as Math, String, StringBuffer, Wrapper, Process, Runtime and System classes. Learn how to use to streams to get input from user, manipulate it and display the result. Understand the role of the Java programming language as a front-end for database applications. Understand two-tier and three-tier architectures for distributed computing.

Tour of java.lang Package


Introduction to java.lang Math Class Wrapper Classes The Process of Runtime Classes The System Classes Introduction to java.text and java.util The Date and Formatter Class Text Formatting Classes Scanner Class Console I/O Writing the Standard Output Reading from the Standard Input File and File I/O Creating New File Object File Methods and Facilities File Stream I/O

The Character, String and Buffer Classes


Basic Formatting Classes


Introduction to File Handling and Stream


Advance I/O Stream


I/O Fundamentals Data within Stream Byte Stream The InputStream Methods The OutputStream Methods

Character Streams

The Reader Methods The Writer Methods String Tokenizer


The FileInputStream and the FileOutputStream Classes The BufferedInputStream and the BufferedOutputStream Classes The DataInputStream and the DataOutputStream Classes The InputStreamReader and the OutputStreamWriter Methods Byte and Character Conversion Using Other Character Encoding The FileReader and the FileWriter Classes The BufferedReader and the BufferedWriter Classes The RandomAccessFile Class

Basics Byte Stream Classes


Basic Character Stream Classes


Database Access and MySQL Using JDBC


What is JDBC Connecting to the databases

Basic Database Access and MySQL


The JDBC Support Classes Back-up and Restore MySQL Database

Swing GUI Component


Using JFrame, JInternalFrame, JTextbox, JTextArea Using JMenu, JMenuItem, JComboBox, JList Using Basic Controls

Threads

The Three part of a Thread Creating a Thread Starting a Thread Thread Scheduling Terminating a Threads Testing a Threads Accessing Thread Priority Putting Threads on Hold Other Way to Create Thread Selecting a Way to Create a Threads The Object Lock Flag Releasing the Lock Flag Thread States DeadLock

Basics Controls of Threads


Using Synchronized in Java Technology


Come to class prepared and ready to share. Always come to school earlier or on time. (Check your schedule) Respect peoples idea and opinion. Wear proper uniform Eating and using cellular phone or any electronic gadget which is not required to use is not allowed during class encounter/lesson. Read in advance. Listen to the direction of your instructor. Late submission will not be accepted. Be responsible for the things that you missed. Excuse absences are the one with medical certificate and death of the immediate family members. Other than those you are considered absent. Observe cleanliness and orderliness. Obey your professor. Do your very best.

Class Standing (60%) : Quizzes/Seatworks Long Quiz/Project Attendance Assignments/Oral Participation


Major Exam TOTAL

25% 15% 10% 10% (40%) (100%)

FINAL GRADE = (PRELIM + MIDTERM + PRE-FINAL + FINAL)/4

After the completing the lesson, you should be able to appreciate and use the following classes

Math String StringBuffer Wrapper Process System

It is a collection of predefined constants and methods for performing different mathematical operations such as trigonometric functions and logarithm. Most of its methods are defined as static

public static double abs(double a)

public static double random()


Returns the positive value of the parameter. An overloaded method. Can also take in a float or an integer or a long integer as a parameter, in which case the return type is either a float or an integer or a long integer, respectively. Returns a random positive value greater than or equal to 0.0 but less than 1.0. Returns the larger value between two double values, a and b. An overloaded method. Can also take in float or integer or long integer values as parameters, in which case the return type is either a float or an integer or a long integer, respectively. Returns the smaller value between two double values, a and b. An overloaded method. Can also take in float or integer or long integer values as parameters, in which case the return type is either a float or an integer or a long integer, respectively. Returns the smallest integer greater than or equal to the specified parameter a.

public static double max(double a, double b)


public static double min(double a, double b)

public static double ceil(double a)

public static double floor(double a)


Returns the largest integer that is lesser than or equal to the specified parameter a. Returns Euler's number e raised to the power of the passed argument a.

public static double exp(double a) public static double log(double a)

Returns the natural logarithm (base e) of a, the double value parameter.


Returns the double value of a raised to the double value of b. Returns the nearest long to the given argument. An overloaded method. Can also take in a float as an argument and returns the nearest int in this case. Returns the square root of the argument a.

public static double pow(double a, double b) public static long round(double a) public static double sqrt(double a)

public static double rint(double a)


public static double sin(double a)

Returns the closest integers, the even integer is returned Returns the trigonometric sine of the given angle a. Returns the trigonometric cosine of the given angle a. Returns the trigonometric tangent of the given angle a. Returns the trigonometric arcsine of the given angle a. Returns the trigonometric arccosine of the given angle a.

public static double cos(double a)

public static double tan(double a)


public static double asin(double a)

public static double acos(double a) public static double atan(double a)

public static double toDegrees(double angrad)

Returns the trigonometric arctangent of the given angle a


Returns the degree value approximately equivalent to the given radian value. Returns the radian value approximately equivalent to the given degree value

public static double toRadians(double angdeg)

class MathDemo { public static void main(String args[]) { System.out.println("absolute value of -5: " + Math.abs(-5)); System.out.println("absolute value of 5: " +Math.abs(-5)); System.out.println("random number(max value is 10): " + Math.random()*10); System.out.println("max of 3.5 and 1.2: " + Math.max(3.5, 1.2)); System.out.println("min of 3.5 and 1.2: " + Math.min(3.5, 1.2)); System.out.println("ceiling of 3.5: " + Math.ceil(3.5)); System.out.println("floor of 3.5: " + Math.floor(3.5)); System.out.println("e raised to 1: " + Math.exp(1)); System.out.println("log 10: " + Math.log(10)); System.out.println("10 raised to 3: " + Math.pow(10,3)); System.out.println("rounded off value of pi: " + Math.round(Math.PI)); System.out.println("square root of 5 = " + Math.sqrt(5)); System.out.println("10 radian = " + Math.toDegrees(10) + " degrees"); System.out.println("sin(90): " + Math.sin(Math.toRadians(90))); } }

absolute value of -5: 5 absolute value of 5: 5 random number(max value is 10): 4.0855332335477605 max of 3.5 and 1.2: 3.5 min of 3.5 and 1.2: 1.2 ceiling of 3.5: 4.0 floor of 3.5: 3.0 e raised to 1: 2.7182818284590455 log 10: 2.302585092994046 10 raised to 3: 1000.0 rounded off value of pi: 3 square root of 5 = 2.23606797749979 10 radian = 572.9577951308232 degrees sin(90): 1.0 Introduction

Problem: Write a program that determines the time it takes a ball to hit the ground after it has been dropped from an 800-foot tower. The mathematical formula to calculate the time in seconds that it takes to fall a given distance in feet is:

time 2 * height / g Where g is the gravitational constant equal to 32.2 ft/sec2 .


It will take 7.049073768502414 seconds to fall 800 feet.

Output

public class FallTime { public static void main (String[]args){ int height; double time;

height = 800; time = Math.sqrt(2*height/32.2);


System.out.println("It will take " + time + " seconds to fall " + height + " feet."); } }

Problem: Write a program that accepts the rectangular coordinates of two points (x1, y1) and (x2, y2) and calculates and returns the distance between two points. The distance, d, between two points is given by the formula
d ( x2 x1 ) 2 ( y2 y1 ) 2

import java.util.*; public class DistanceTwoPoints { public static void main(String[]args){ Scanner sc = new Scanner(System.in); System.out.print("Enter the value of x1: "); int x1 = sc.nextInt(); System.out.print("Enter the value of x2: "); int x2 = sc.nextInt(); double a = Math.pow(x2-x1,2); System.out.print("Enter the value of y1: "); int y1 = sc.nextInt(); System.out.print("Enter the value of y2: "); int y2 = sc.nextInt(); double b = Math.pow(y2-y1,2); double d = Math.sqrt(a+b); System.out.println("Distance between two points is: "+d); } }

Problem: Write a Java program that convert the rectangular (x,y) coordinates of a point into polar form. That is, given an x and y position on a Cartesian coordinate system. Calculate the distance from the origin, d, and the angle from the x axis, , specified by the point. The values of d and are referred to as the points polar coordinates.

Formula:
d x y
2 2

Y - axis (X, Y) r

X - axis

tan 1 ( y / x), x 0

Algorithm
Get the x and y coordinates values
Calculate the polar (r and ) coordinates values Display the polar coordinates values

public class ConvertXY { public static void main(String[] args) { double x =3.0; double y = 4.0; double distance, angle; //convert to Polar coordinates distance = getDistance(x,y); angle = getAngle(x,y); System.out.println("The polar coordinates are: "); System.out.println("Distance from the origin: " + distance); System.out.println("Angle (in degrees) from the x-axis: "+ angle); } public static double getDistance(double x, double y){ return Math.sqrt(Math.pow(x,2)+ Math.pow(y,2)); } public static double getAngle(double x, double y){ return Math.toDegrees(Math.atan(y/x)); } }

String
Combination of character literals Can be represented by array of characters or

simply by using String class String object is immutable or cannot be change

StringBuffer
Object of StringBuffer is similar to a String object,

except for the fact that the StringBuffer object is mutable or can be modified

public char charAt(int index)


public int compareTo(String anotherString)
Returns the character located in the specified index. Compares this string with the specified parameter. Returns a negative value if

public int compareToIgnoreCase(String str) public boolean equals(Object anObject)


string.

this string comes lexicographically before the other string, 0 if both of the strings have the same value and a positive value if this string comes after the other string lexicographically.

Like compareTo but ignores the case used in this string and the specified

Returns true if this string has the same sequence of characters as that of the

public boolean equalsIgnoreCase(String anotherString)

Object specified, which should be a String object. Otherwise, if the specified parameter is not a String object or if it doesn't match the sequence of symbols in this string, the method will return false.

Like equals but ignores the case used in this string and the specified string.

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

public int length()


Gets the characters from this string starting at the srcBegin index up to the srcEnd index and copies these characters to the dst array starting at the dstBegin index. Returns the length of this string.

public String replace(char oldChar, char newChar) public String substring(int beginIndex, int endIndex)

Returns the string wherein all occurrences of the oldChar in this string is replaced with newChar. Returns the substring of this string starting at the specified beginIndex index up to the endIndex index. Returns the character array equivalent of this string. Returns a modified copy of this string wherein the leading and trailing white space are removed. Takes in a simple data type such as boolean, integer or character, or it takes in an object as a parameter and returns the String equivalent of the specified parameter.

public char[] toCharArray()


public String trim()

public static String valueOf(-)

public String toLowerCase()


public String toUpperCase()

Returns a new string with all characters in lowercase. Returns a new string with all characters in upper case. Concatenates str to the end of a string.

public String concat(String anotherString) public boolean endsWith(String suffix) public int hashCode()
Test if the string ends with the specified string

public int indexOf(int ch)

Returns an integer number derived from the string Returns the position of the first occurrence of the specified character

public int lastIndexOf(int ch)

public boolean startsWith(String prefix)

Returns the position of the last occurrence of the specified character.


Test if the string begins with the specified string

public boolean startsWith(String prefix, int startPos)


Test if the string begins with the specified string, starting at the specified position.

class StringDemo { public static void main(String args[]) { String name = "Jonathan"; System.out.println("name: " + name); System.out.println("3rd character of name: " + name.charAt(2)); /* character that first appears alphabetically has lower unicode value */ System.out.println("Jonathan compared to Solomon: " +name.compareTo("Solomon")); System.out.println("Solomon compared to Jonathan: " + "Solomon".compareTo("Jonathan")); /* 'J' has lower unicode value compared to 'j' */ System.out.println("Jonathan compared to jonathan: " + name.compareTo("jonathan")); System.out.println("Jonathan compared to jonathan (ignore case): " name.compareToIgnoreCase("jonathan")); System.out.println("Is Jonathan equal to Jonathan? " + name.equals("Jonathan")); System.out.println("Is Jonathan equal to jonathan? " + name.equals("jonathan")); System.out.println("Is Jonathan equal to jonathan (ignore case)? " + name.equalsIgnoreCase("jonathan")); char charArr[] = "Hi XX".toCharArray(); /* Need to add 1 to the endSrc index of getChars */ "Jonathan".getChars(0, 2, charArr, 3); System.out.print("getChars method: "); System.out.println(charArr); System.out.println("Length of name: " + name.length()); System.out.println("Replace a's with e's in name: " + name.replace('a', 'e')); /* Need to add 1 to the endIndex parameter of substring*/ System.out.println("A substring of name: " + name.substring(0, 2)); System.out.println("Trim \" a b c d e f \": \"" + " a b c d e f ".trim() + "\""); System.out.println("String representation of boolean expression 10>10: " + String.valueOf(10>10)); /* toString method is implicitly called in the println method*/ System.out.println("String representation of boolean expression 10<10: " + (10<10)); /* Note there's no change in the String object name even after applying all these methods. */ System.out.println("name: " + name);}}

name: Jonathan 3rd character of name: n Jonathan compared to Solomon: -9 Solomon compared to Jonathan: 9 Jonathan compared to jonathan: -32 Jonathan compared to jonathan (ignore case): 0 Is Jonathan equal to Jonathan? true Is Jonathan equal to jonathan? false Is Jonathan equal to jonathan (ignore case)? true content of charArr after getChars method: Hi Jo Length of name: 8 Replace a's with e's in name: Jonethen A substring of name: Jo Trim " a b c d e f ": "a b c d e f" String representation of boolean expression 10>10: false String representation of boolean expression 10<10: false name: Jonathan

public int capacity()


Returns the current capacity of this StringBuffer object. Appends the string representation of the argument to this StringBuffer object. Takes in single parameter which may be of these data types: boolean, char, char [], double, float, int, long, Object, String and StringBuffer. Still has another overloaded version. Returns the character located in the specified index.

public StringBuffer append(-)

public char charAt(int index)

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Gets the characters from this object starting at the srcBegin index up to the srcEnd index and copies these characters to the dst array starting at the dstBegin index.
Deletes the characters within the specified range. Inserts the string representation of the second argument at the specified offset. A overloaded method. Possible data types for the second argument: boolean, char, char [], double, float, int, long, Object and String. Still has another overloaded version.

public StringBuffer delete(int start, int end)


public StringBuffer insert(int offset, -)

public int length()

Returns the number of characters in this StringBuffer object.


Replaces part of this object, as specified by the first two arguments, with the specified string str. Returns the substring of this string starting at the specified start index up to the end index. Converts this object to its string representation.

public StringBuffer replace(int start, int end, String str) public String substring(int start, int end) public String toString()

class StringBufferDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Jonathan"); System.out.println("sb = " + sb); /* initial capacity is 16 */ System.out.println("capacity of sb: " + sb.capacity()); System.out.println("append \'O\' to sb: " + sb.append("O")); System.out.println("sb = " + sb); System.out.println("3rd character of sb: " + sb.charAt(2)); char charArr[] = "Hi XX".toCharArray(); /* Need to add 1 to the endSrc index of getChars */ sb.getChars(0, 2, charArr, 3); System.out.print("getChars method: "); System.out.println(charArr); System.out.println("Insert \'jo\' at the 3rd cell: " + sb.insert(2, "jo")); System.out.println("Delete \'jo\' at the 3rd cell: " + sb.delete(2,4)); System.out.println("length of sb: " + sb.length()); System.out.println("replace: " + sb.replace(3, 9, " Ong")); /* Need to add 1 to the endIndex parameter of substring*/ System.out.println("substring (1st two characters): " + sb.substring(0, 3)); System.out.println("implicit toString(): " + sb);}}

sb = Jonathan capacity of sb: 24 append 'O' to sb: JonathanO sb = JonathanO 3rd character of sb: n getChars method: Hi Jo Insert 'jo' at the 3rd cell: JojonathanO Delete 'jo' at the 3rd cell: JonathanO length of sb: 9 replace: Jon Ong substring (1st two characters): Jon implicit toString(): Jon Ong

object representations of simple non-object variables Can use to declare reference data type Can access methods of the Object Class unlike the primitive data types

Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor:
Character ch = new Character('a');

public static boolean isDigit(char ch)


public static boolean isLetter(char ch)

Returns true if ch is a digit; otherwise, it returns a false Returns true if ch is a letter; otherwise, it returns a false Returns true if ch is a lowercase letter; otherwise, it returns a false Returns true if ch is a uppercase letter; otherwise, it returns a false Returns true if ch is a space character; otherwise, it returns a false Returns true if ch is a Java-defined whitespace; otherwise, it returns a false

public static boolean isLowerCase(char ch) public static boolean isUpperCase(char ch) public static boolean isSpaceChar(char ch)

public static boolean isWhiteSpace(char ch) public static char toLowerCase(char ch) public static char toUpperCase(char ch) public static char toString(char ch)
Returns the uppercase equivalent of ch Returns the String representation of ch

Returns the lowercase equivalent of ch

class BooleanWrapper { public static void main(String args[]) { boolean booleanVar = 1>2; Boolean booleanObj = new Boolean("TRue"); /* primitive to object; can also use valueOf method */ Boolean booleanObj2 = new Boolean(booleanVar); System.out.println("booleanVar = " + booleanVar); System.out.println("booleanObj = " + booleanObj); System.out.println("booleanObj2 = " + booleanObj2); System.out.println("compare 2 wrapper objects: " + booleanObj.equals(booleanObj2)); /* object to primitive */ booleanVar = booleanObj.booleanValue(); System.out.println("booleanVar = " + booleanVar); } }

Sample Output booleanVar = false booleanObj = true booleanObj2 = false compare 2 wrapper objects: false booleanVar = true

Process Class
provides methods for manipulating processes

such as killing the process, running the process and checking the status of the process. This class represents running programs

Runtime Class
represents the runtime environment.
Two important methods in the class are the

getRuntime and the exec method

Process Methods
public abstract void destroy()
Kills the current process.

public abstract int waitFor() throws InterruptedException

Runtime Methods

Does not exit until this process terminates.

public static Runtime getRuntime()


Returns the runtime environment associated with the current Java application.

public Process exec(String command) throws IOException


Causes the specified command to be executed. Allows you to execute new processes.

class RuntimeDemo { public static void main(String args[]) { Runtime rt = Runtime.getRuntime(); Process proc; try { proc = rt.exec("regedit"); proc.waitFor(); //try removing this line } catch (Exception e) { System.out.println("regedit is an unknown command."); } } }

provides many useful fields and methods such as the standard input, the standard output and a utility method for fast copying of a part of an array. Here are some interesting methods from the class. Note that all the class's methods are static.

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

public static long currentTimeMillis()

Copies length items from the source array src starting at srcPos to dest starting at index destPos. Faster than manually programming the code for this yourself. Returns the difference between the current time and January 1, 1970 UTC. Time returned is measured in milliseconds. Kills the Java Virtual Machine (JVM) running currently. A non-zero value for status by convention indicates an abnormal exit. Runs the garbage collector, which reclaims unused memory space for recycling. Changes the stream associated with System.in, which by default refers to the keyboard. Changes the stream associated with System.out, which by default refers to the console.

public static void exit(int status)

public static void gc()


public static void setIn(InputStream in)

public static void setOut(PrintStream out)

import java.io.*; class SystemDemo { public static void main(String args[]) throws IOException { int arr1[] = new int[5000000]; int arr2[] = new int[5000000]; long startTime, endTime; /* initialize arr1 */ for (int i = 0; i < arr1.length; i++) { arr1[i] = i + 1; } /* copying manually */ startTime = System.currentTimeMillis(); for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } endTime = System.currentTimeMillis(); System.out.println("Time for manual copy: " + (endTime-startTime) + " ms."); /* using the copy utility provided by java the arraycopy method */ startTime = System.currentTimeMillis(); System.arraycopy(arr1, 0, arr2, 0, arr1.length); endTime = System.currentTimeMillis(); System.out.println("Time w/the use of arraycopy: " + (endTime-startTime) + " ms."); System.gc(); //force garbage collector to work System.setIn(new FileInputStream("temp.txt")); /* in NetBeans, temp.txt should be locate in the project folder */ System.exit(0); } }

Sample Output Time for manual copy: 32 ms. Time w/the use of arraycopy: 31 ms.

Curve Plotting

y x 8 3
2

import java.io.*; public class Sample1 { public static void main(String[] args) throws IOException{ int x,y; //71 spaces StringBuffer line = new StringBuffer ("| for (x=1;x<=15;x++){ y= (int) Math.pow(x-8,2.0)+3; line.setCharAt(y,'*');//set the character to an asterisk System.out.println(line); line.setCharAt(y,' '); //reset character to a blank } } }

");

| | | | * | * | * | * | * | * | * | * | * | | |

*
* *

* * *

Event-based programs provide a fully functioning GUI from which the user has a number of graphical components from which to choose.

Top Level Container


A basic window structure that includes such things as

Intermediate Container

borders and resizing capabilities and can hold both intermediate containers and atomic components that ties the GUI into the operating system itself can hold other intermediate containers and atomic components. Used to simplify placement and exact positioning of atomic components items of information. Must be placed into a container using add() method

A graphical object displayed in a top-level container that

Atomic Component

Graphical objects used to accept and/or display individual

Component Type Top-Level Container Top-Level Container

AWT Name Frame Applet

Swing Name JFrame JApplet

Top-Level Container
Top-Level Container Intermediate Container Intermediate Container Intermediate Container

Dialog
Window Panel InternalFrame LayeredPane

JDialog
JWindow JPanel JInternalFrame JLayeredPane

Intermediate Container

RootPane

JRootPane

Component Type Atomic Atomic

AWT Name Button Menu

Swing Name JButton JMenu

Atomic
Atomic Atomic Atomic Atomic

Label
CheckBox JRadioButton TextField TextArea

JLabel
JCheckBox JRadioButton JTextField JTextArea

Java Foundation Classes (JFC)


which is an important part of the Java SDK, refers to a

5 APIs

collection of APIs that simplifies the development Java GUI applications. AWT Swing Java 2D Accessibility Drag and Drop

All these APIs assist developers in designing and implementing visually-enhanced applications.

AWT components that use native code Swing is written entirely using the Java programming language Swing provides a platform-independent implementation ensuring that applications deployed across different platforms have the same appearance. AWT, however, does ensure that the look and feel of an application run on two different machines be comparable.

Component

Container

An abstract class for objects that can be displayed on the console and interact with the user. The root of all other AWT classes. other components.

An abstract subclass of the Component class. A component that can contain

Panel

Extends the Container class. A frame or window without the title bar, the menu

Window

bar nor the border. Super class of the Applet class.

Also extends Container class. A top-level window, which means that it cannot

Frame

be contained in any other object. Has no borders and no menubar.

Extends the Window class. A window with a title, menubar, border, and resizing

Frame(String title)

corners. Has four constructors, two of which have the following signatures: Frame()

void setSize(int width, int height)


To set the size of the window, the overloaded setSize

void setSize(Dimension d)
Resizes this component to the width and height

method is used.

void setVisible(boolean b)

provided as parameters. Resizes this component to d.width and d.height based on the Dimension d specified.
A window by default is not visible unless you set its

visibility to true. Here is the syntax for the setVisible method.

import java.awt.*; public class SampleFrame extends Frame { public static void main(String args[]) { SampleFrame sf = new SampleFrame(); sf.setSize(100, 100); //Try removing this line sf.setVisible(true); //Try removing this line } }

Graphics
Several graphics method are found in the Graphics class.
drawLine() fillRect() drawRect() clearRect() drawPolyline() drawPolygon() fillPolygon() getColor() setColor() getFont() setFont() drawString()

Related to this class is the Color class, which has three constructors. Constructor Format Description Color(int r, int g, int b) Integer value is from 0 to 255. Color(float r, float g, float b) Float value is from 0.0 to 1.0. Color(int rgbValue) Value range from 0 to 224-1 (black to white). Red: bits 16-23 Green: bits 8-15 Blue: bits 0-7

import java.awt.*; public class GraphicsPanel extends Panel { GraphicsPanel() { setBackground(Color.black); //constant in Color class } public void paint(Graphics g) { g.setColor(new Color(0,255,0)); //green g.setFont(new Font("Helvetica",Font.PLAIN,16)); g.drawString("Hello GUI World!", 30, 100); g.setColor(new Color(1.0f,0,0)); //red g.fillRect(30, 100, 150, 10); } public static void main(String args[]) { Frame f = new Frame("Testing Graphics Panel"); GraphicsPanel gp = new GraphicsPanel(); f.add(gp); f.setSize(600, 300); f.setVisible(true); } }

Here is a list of AWT controls. Controls are components such as buttons or text fields that allow the user to interact with a GUI application. These are all subclasses of the Component class. Label TextField TextArea Button Checkbox CheckboxGroup Choice List Scrollbar

import java.awt.*; class FrameWControls extends Frame { public static void main(String args[]) { FrameWControls fwc = new FrameWControls(); fwc.setLayout(new FlowLayout()); //more on this later fwc.setSize(600, 600); fwc.add(new Button("Test Me!")); fwc.add(new Label("Labe")); fwc.add(new TextField()); CheckboxGroup cbg = new CheckboxGroup(); fwc.add(new Checkbox("chk1", cbg, true)); fwc.add(new Checkbox("chk2", cbg, false)); fwc.add(new Checkbox("chk3", cbg, false)); List list = new List(3, false); list.add("MTV"); list.add("V"); fwc.add(list); Choice chooser = new Choice(); chooser.add("Avril"); chooser.add("Monica"); chooser.add("Britney"); fwc.add(chooser); fwc.add(new Scrollbar()); fwc.setVisible(true); }}

The position and size of the components within each container is determined by the layout manager. The layout managers governs the layout of the components in the container. These are some of the layout managers included in Java. 1. FlowLayout 2. BorderLayout 3. GridLayout 4. GridBagLayout 5. CardLayout The layout manager can be set using the setLayout method of the Container class. The method has the following signature. void setLayout(LayoutManager mgr) - If you prefer not to use any layout manager at all, you pass null as an argument to this method. But then, you would have to position the elements manually with the use of the setBounds method of the Component class. public void setBounds(int x, int y, int width, int height) - The method controls the position based on the arguments x and y, and the size based on the specified width and height. This would be quite difficult and tedious to program if you have several Component objects within the Container object. You'll have to call this method for each component.

The FlowLayout is the default manager for the Panel class and its subclasses, including the Applet class. It positions the components in a left to right and top to bottom manner, starting at the upper-lefthand corner. FlowLayout Constructors

FlowLayout() -Creates a new FlowLayout object with the center alignment and 5-unit horizontal and vertical gap applied to the components by default.
FlowLayout(int align) - Creates a new FlowLayout object with the specified alignment and the default 5-unit horizontal and vertical gap applied to the components. FlowLayout(int align, int hgap, int vgap) -Creates a new FlowLayout object with the first argument as the alignment applied and the hgap-unit horizontal and vgap-unit vertical gap applied to the components.

The gap refers to the spacing between the components and is measured in pixels. The alignment argument should be one of the following: 1. FlowLayout.LEFT 2. FlowLayout.CENTER 3. FlowLayout.RIGHT import java.awt.*; class FlowLayoutDemo extends Frame { public static void main(String args[]) { FlowLayoutDemo fld = new FlowLayoutDemo(); fld.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10)); fld.add(new Button("ONE")); fld.add(new Button("TWO")); fld.add(new Button("THREE")); fld.setSize(100, 100); fld.setVisible(true);} }

The BorderLayout divides the Container into five parts- north, south, east, west and the center. Each components is added to a specific region. The north and south regions stretch horizontally whereas the east and west regions adjust vertically. The center region, on the other hand, adjusts in both horizontally and vertically. This layout is the default for Window objects, including objects of Window's subclasses Frame and Dialog type. BorderLayout Constructors BorderLayout() - Creates a new BorderLayout object with no spacing applied among the different components.

BorderLayout(int hgap, int vgap) -Creates a new BorderLayout object with hgapunit horizontal and vgap-unit spacing applied among the different components.

The following list gives the valid regions are predefined fields in the BorderLayout class. 1. BorderLayout.NORTH 2. BorderLayout.SOUTH 3. BorderLayout.EAST 4. BorderLayout.WEST 5. BorderLayout.CENTER import java.awt.*; class BorderLayoutDemo extends Frame { public static void main(String args[]) { BorderLayoutDemo bld = new BorderLayoutDemo(); bld.setLayout(new BorderLayout(10, 10)); //may remove bld.add(new Button("NORTH"), BorderLayout.NORTH); bld.add(new Button("SOUTH"), BorderLayout.SOUTH); bld.add(new Button("EAST"), BorderLayout.EAST); bld.add(new Button("WEST"), BorderLayout.WEST); bld.add(new Button("CENTER"), BorderLayout.CENTER); bld.setSize(200, 200); bld.setVisible(true);} }

With the GridLayout manager, components are also positioned from left to right and top to bottom as in the FlowLayout manager. In addition to this, the GridLayout manager divides the container into a number of rows and columns. All these regions are equally sized. It always ignores the component's preferred size. The following is the available constructors for the GridLayout class. GridLayout Constructors GridLayout() - Creates a new GridLayout object with a single row and a single column by default. GridLayout(int rows, int cols) - Creates a new GridLayout object with the specified number of rows and columns. GridLayout(int rows, int cols, int hgap, int vgap) - Creates a new GridLayout object with the specified number of rows and columns. Hgapunit horizontal and vgap-unit vertical spacing are applied to the components.

import java.awt.*; class GridLayoutDemo extends Frame { public static void main(String args[]) { GridLayoutDemo gld = new GridLayoutDemo(); gld.setLayout(new GridLayout(2, 3, 4, 4)); gld.add(new Button("ONE")); gld.add(new Button("TWO")); gld.add(new Button("THREE")); gld.add(new Button("FOUR")); gld.add(new Button("FIVE")); gld.setSize(200, 200); gld.setVisible(true); } }

To create more complex layouts, you can combine the different layout managers with the use of panels. Remember that a Panel is a Container and a Component at the same time. You can insert Components into the Panel and then add the Panel to a specified region in the Container.

import java.awt.*; class ComplexLayout extends Frame { public static void main(String args[]) { ComplexLayout cl = new ComplexLayout(); Panel panelNorth = new Panel(); Panel panelCenter = new Panel(); Panel panelSouth = new Panel(); /* North Panel */ //Panels use FlowLayout by default panelNorth.add(new Button("ONE")); panelNorth.add(new Button("TWO")); panelNorth.add(new Button("THREE")); /* Center Panel */ panelCenter.setLayout(new GridLayout(4,4)); panelCenter.add(new TextField("1st")); panelCenter.add(new TextField("2nd")); panelCenter.add(new TextField("3rd"));panelCenter.add(new TextField("4th")); /* South Panel */ panelSouth.setLayout(new BorderLayout()); panelSouth.add(new Checkbox("Choose me!"), BorderLayout.CENTER); panelSouth.add(new Checkbox("I'm here!"), BorderLayout.EAST); panelSouth.add(new Checkbox("Pick me!"), BorderLayout.WEST); /* Adding the Panels to the Frame container */ //Frames use BorderLayout by default cl.add(panelNorth, BorderLayout.NORTH); cl.add(panelCenter, BorderLayout.CENTER); cl.add(panelSouth, BorderLayout.SOUTH); cl.setSize(300,300); cl.setVisible(true); } }

Like the AWT package, the Swing package provides classes for creating GUI applications. The package is found in javax.swing. The main difference between these two is that Swing components are written entirely using Java whereas the latter is not. As a result, GUI programs written using classes from the Swing package have the same look and feel even when executed on different platforms. Moreover, Swing provides more interesting components such as the color chooser and the option pane. The names of the Swing GUI components are almost similar to that of the AWT GUI components. An obvious difference is in the naming conventions of the components. Basically, the name of Swing components are just the name of AWT components but with an additional prefix of J.

JComponent The root class for all Swing components, excluding top-level containers. JButton A "push" button. Corresponds to the Button class in the AWT package. JCheckBox An item that can be selected or deselected by the user. Corresponds to the Checkbox class in the AWT package. JFileChooser Allows user to select a file. Corresponds to the FileChooser class in the AWT package. JTextField Allows for editing of a single-line text. Corresponds to TextField class in the AWT package. JFrame Extends and corresponds to the Frame class in the AWT package but the two are slightly incompatible in terms of adding components to this container. Need to get the current content pane before adding a component.

JPanel Extends JComponent. A simple container class but not top-level. Corresponds to Panel class in the AWT package. JApplet Extends and corresponds to the Applet class in the AWT package. Also slightly incompatible with the Applet class in terms of adding components to this container. JOptionPane Extends JComponent. Provides an easy way of displaying pop-up dialog box. JDialog Extends and corresponds to the Dialog class in the AWT package. Usually used to inform the user of something or prompt the user for an input. JColorChooser Extends JComponent. Allow the user to select a color.

import javax.swing.*; import java.awt.*; class SwingDemo { JFrame frame; JPanel panel; JTextField textField; JButton button; Container contentPane; void launchFrame() { /* initialization */ frame = new JFrame("My First Swing Application"); panel = new JPanel(); textField = new JTextField("Default text"); button = new JButton("Click me!"); contentPane = frame.getContentPane(); /* add components to panel uses FlowLayout by default */ panel.add(textField); panel.add(button); /* add components to contentPane uses BorderLayout */ contentPane.add(panel, BorderLayout.CENTER); frame.pack(); //causes size of frame to be based on the components frame.setVisible(true); } public static void main(String args[]) { SwingDemo sd = new SwingDemo(); sd.launchFrame(); }}

import javax.swing.*; class JOptionPaneDemo { JOptionPane optionPane; void launchFrame() { optionPane = new JOptionPane(); String name = optionPane.showInputDialog("Hi, what's your name?"); optionPane.showMessageDialog(null, "Nice to meet you, " + name + ".", "Greeting...", optionPane.PLAIN_MESSAGE); System.exit(0); } public static void main(String args[]) { new JOptionPaneDemo().launchFrame(); } }

The Delegation Event Model The Delegation event model describes how your program can respond to user interaction. To understand the model, let us first study its three important components. 1. Event Source The event source refers to the GUI component that generates the event. For example, if the user presses a button, the event source in this case is the button. 2. Event Listener/Handler The event listener receives news of events and processes user's interaction. When a button is pressed, the listener may handle this by displaying an information useful to the user. 3. Event Object When an event occurs (i.e., when the user interacts with a GUI component), an event object is created. The object contains all the necessary information about the event that has occurred. The information includes the type of event that has occurred, say, the mouse was clicked. There are several event classes for the different categories of user action. An event object has a data type of one of these classes.

Initially, a listener should be registered with a source so that it can receive information about events that occur at the source. Only registered listeners can receive notifications of events. Once registered, a listener simply waits until an event occurs. When something happens at the event source, an event object describing the event is created. The event is then fired by the source to the registered listeners. Once the listener receives an event object (i.e., a notification) from the source, it goes to work. It deciphers the notification and processes the event that occurred.

The event source registers a listener through the add<Type>Listener methods. void add<Type>Listener(<Type>Listener listenerObj) <Type> depends on the type of event source. It can be Key, Mouse, Focus, Component, Action and others. Several listeners can register with one event source to receive event notifications A registered listener can also be unregistered using the remove<Type>Listener methods.

void remove<Type>Listener(<Type>Listener listenerObj).

An event object has an event class as its reference data type. At the root of event class heirarchy is the EventObject class, which is found in the java.util package. An immediate subclass of the EventObject class is the AWTEvent class. The AWTEvent class is defined in java.awt package. It is the root of all AWT-based events. Here are some of the AWT event classes.

Take note that all AWTEvent subclasses follow this naming convention: <Type>Event

ComponentEvent

Extends AWTEvent. Instantiated when a component is moved, resized, made visible or hidden. Extends ComponentEvent. The abstract root event class for all component-level input event classes. Extends AWTEvent. Instantiated when a button is pressed, a list item is double-clicked, or a menu item is selected. Extends AWTEvent. Instantiated when an item is selected or deselected by the user, such as in a list or a checkbox. Extends InputEvent. Instantiated when a key is pressed, released or typed. Extends InputEvent. Instantiated when a mouse button is pressed, released, or clicked (pressed and released), or when a mouse cursor enteres or exits a visible part of a component. Extends AWTEvent. Instantiated when the value of a text field or a text area is changed. Extends ComponentEvent. Instantiated when a Window object is opened, closed, activated, deactivated, iconified, deiconified, or when focus is transferred into or out of the window.

InputEvent ActionEvent

ItemEvent

KeyEvent

MouseEvent

TextEvent

WindowEvent

Event listeners are just classes that implement the <Type>Listener interfaces. The following table shows some of the listener interfaces commonly used. ActionListener - Receives action events. MouseListener - Receives mouse events. MouseMotionListener - Receives mouse motion events, which include dragging and moving the mouse. WindowListener - Receives window events. ActionListener Method The ActionListener interface contains only one method. public void actionPerformed(ActionEvent e) - Contains the handler for the ActionEvent e that occurred.

MouseListener Methods These are the MouseListener methods that should be overriden by the implementing class. public void mouseClicked(MouseEvent e) -Contains the handler for the event when the mouse is clicked (i.e., pressed and released). public void mouseEntered(MouseEvent e) - Contains the code for handling the case wherein the mouse enters a component. public void mouseExited(MouseEvent e) - Contains the code for handling the case wherein the mouse exits a component. public void mousePressed(MouseEvent e) - Invoked when the mouse button is pressed on a component. public void mouseReleased(MouseEvent e) - Invoked when the mouse button is released on a component.

MouseMotionListener Methods The MouseMotionListener has two methods to be implemented. MouseListener Methods public void mouseDragged(MouseEvent e)- Contains the code for handling the case wherein the mouse button is pressed on a component and dragged. Called several times as the mouse is dragged. public void mouseMoved(MouseEvent e) - Contains the code for handling the case wherein the mouse cursor is moved onto a component, without the mouse button being pressed. Called multiple times as the mouse is moved.

WindowListener Methods These are the methods of the WindowListener interface. public void windowOpened(WindowEvent e) -Contains the code for handling the case when the Window object is opened (i.e., made visible for the first time). public void windowClosing(WindowEvent e) - Contains the code for handling the case when the user attempts to close Window object from the object's system menu. public void windowClosed(WindowEvent e) - Contains the code for handling the case when the Window object was closed after calling dispose (i.e., release of resources used by the source) on the object. public void windowActivated(WindowEvent e) Invoked when a Window object is the active window (i.e., the window in use). public void windowDeactivated(WindowEvent e) - Invoked when a Window object is no longer the active window. public void windowIconified(WindowEvent e) - Called when a Window object is minimized. public void windowDeiconified(WindowEvent e) - Called when a Window object reverts from a minimized to a normal state.

Create a class that describes and displays the appearance of your GUI application. Create a class that implements the appropriate listener interface. This class may refer to the same class as in the first step. In the implementing class, override ALL methods of the appropriate listener interface. Describe in each method how you would like the event to be handled. You may give empty implementations for methods you don't want to handle. Register the listener object, the instantiation of the listener class in step 2, with the source component using the add<Type>Listener method.

import java.awt.*; import java.awt.event.*; public class MouseEventsDemo extends Frame implements MouseListener, MouseMotionListener { TextField tf; public MouseEventsDemo(String title){ super(title); tf = new TextField(60); addMouseListener(this); } public void launchFrame() { /* Add components to the frame */ add(tf, BorderLayout.SOUTH); setSize(300,300); setVisible(true); } public void mouseClicked(MouseEvent me) { String msg = "Mouse clicked."; tf.setText(msg); } public void mouseEntered(MouseEvent me) { String msg = "Mouse entered component."; tf.setText(msg); } public void mouseExited(MouseEvent me) { String msg = "Mouse exited component."; tf.setText(msg); } public void mousePressed(MouseEvent me) { String msg = "Mouse pressed."; tf.setText(msg); } public void mouseReleased(MouseEvent me) { String msg = "Mouse released."; tf.setText(msg); } public void mouseDragged(MouseEvent me) { String msg = "Mouse dragged at " + me.getX() + "," + me.getY(); tf.setText(msg);} public void mouseMoved(MouseEvent me) { String msg = "Mouse moved at " + me.getX() + "," + me.getY(); tf.setText(msg); } public static void main(String args[]) { MouseEventsDemo med = new MouseEventsDemo("Mouse Events Demo"); med.launchFrame(); } }

To store and retrieve data on a file in Java, tow items are required:
A file A file stream

File also known as data file is a collection of data that is stored together under a common name on a storage medium Example of files

Prices.dat Exper1.dat

records scores.dat

info.txt math.mem

A file stream is a one-way transmission path that is used to connect a filed stored on a physical device to a program
A file stream that receives or reads data from file

into a program is referred as input file stream A file stream that sends or writes data to a file is referred as output file stream

Two stream objects


Input stream object: System.in An instance of java.io.BufferedInputStream which is a subclass of java.io.InputStream Provides a transmission path from keyboard to program Output stream object: System.out An instance of java.io.BufferedOutputStream which is a subclass of java.io.OutputStream Provides a transmission path from program to terminal screen

Mode Input
Output

For a Character-Based File Use a FileReader class


Use a FileWriter class

For a Byte-Based File Use a FileInputStream class


Use a FileOutputStream class

A data file is a collection of data stored together on an external storage medium under a common name
A character-based file is one in which each data item in the file is stored using a character-based code such as ASCII. A character based file is also referred to as text file. A byte-based file is one in which each data item in the file is stored using computers internal binary code. A byte-based file is also referred to as binary file.

Writing into File

FileWriter

BufferedWriter

Used for basic output A basic stream used for character-based output Common methods: write(), flush(), close() Used for buffering Provides output buffering, which typically improves performance Common methods: write(), flush(), close() Used for processing Provides a number of useful output methods Common methods: flush(), close(), print(-) and println(-)

PrintWriter

Sample declaration: FileWriter fw = new FileWriter(outFile); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); Note: FileWriter fw = new FileWriter(file, true); // this will open the file in append mode

import java.io.*; public class WriteTextPrices { public static void main(String[]args) throws IOException { //set the basic output stream FileWriter fw = new FileWriter("prices.txt"); //buffer it for faster output BufferedWriter bw = new BufferedWriter(fw); //this provides sets of useful methods PrintWriter pw = new PrintWriter(bw); pw.println("Maths 39.95"); pw.println("Bulbs 3.22"); pw.println("Fuses 1.08"); pw.close(); } }

FileReader
Used for basic input A basic stream used for character-based input.

BufferedReader

Supplies character-by-character input. Common methods: read()

Used for processing Provides buffering, which typically improves

performance. Supplies character-by-character and line-by-line input and typically uses a FileInputStream object argument Common methods: read(), readLine()

import java.io.*; public class ReadTextPrices { public static void main(String[]args) throws IOException{ String filename = "prices.txt"; int i; String inLine; //set up the basic input stream FileReader fr = new FileReader(filename); //buffer the input stream BufferedReader br = new BufferedReader(fr); //read and display three lines for (i =0;i<3;i++) { inLine =br.readLine(); //read a line System.out.println(inLine); //display the line } br.close(); } }

import java.io.*; Import java.util.*; public class ReadTextPrices { public static void main(String[]args) throws IOException{ String filename = "prices.txt"; int i; double price; String inLine, desc; StringTokenizer st; BufferedReader br = new BufferedReader(new FileReader(filename)); for (i =0;i<3;i++) { inLine =br.readLine(); //read a line st = new StringTokenizer(inLine); desc = st.nextToken(); price = Double.parseDouble(st.nextToken()); System.out.println(Description: + desc + \t + Price: + price); } br.close(); } }

import java.io.*; public class CopyTextPrices { public static void main(String[]args) throws IOException{ int i; FileReader fr = new FileReader(info.txt); FileWriter fw = new FileWriter(fw); int c; while((c=fr.read())!=EOF) { fr.write(c); } fr.close(); fw.close(); } }

In java, there is a way to break up a line of text into what are called tokens. A token is a smaller piece of a string. This method of breaking up tokens are come from the StringTokenizer class. Let's say that we wanted to break up the following line of text into smaller pieces:
"Hello and welcome to programming

Here, the token we need is just a simple white space. So here is how to declare a StringTokeizer object:
StringTokenizer name = new StringTokenizer(variable, Token(s));

where in the above, name is an appropriate name for the tokenizer object; variable is the name of a String variable you are using or even just a simple string; and token(s) is the token you are specifying.

In the above definition, if the second argument of the constructor is not specified, the token, by default, is a white space. If the token that is declared does not exist in the String you are searching through, the entire string is returned to you.

Import statements
In order for the StringTokenizer class to be used, you must import it from a certain library; here the util library.
An import statement always appears outside the class header line. So here is how the StringTokenizer statement will look:
import java.util.*; public class XXXXXXXXXX { //code here }

boolean hasMoreTokens()
This method will return a boolean value that will represent

int countTokens()

if there are any more tokens left in the line you are trying to tokenize. The truereturn will show that there is at least 1 more token in the line. number of tokens in the String. This method does not advance the position in the String.

This method will simply return an integer representing the

String nextToken()

This method is the primary method of the class as it will

get you the next piece of data in the String. The position in the string is changed after this method is called.

import java.util.StringTokenizer; public class StringTokenizerExample{ public static void main(String args[]){ String s = "What on earth is going on here?"; //by default, a white space: StringTokenizer st = new StringTokenizer(s); //when there are still more tokens, print out // the next one: while(st.hasMoreTokens()) System.out.println(st.nextToken()); } //main } //class

FileOutputStream

Used for basic output A basic stream used for byte-based output Supplies character-by-character output Provides output buffering, which typically improves performance Supplies character-by-character and line-by-line output Typically uses a FileOutputStream object argument Typically uses either a FileOutputStream or BufferedOutputStream object argument

BufferedOutputStream

DataOutputStream

Sample declaration: FileOutputStream fos = new FileOutputStream (outFile); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos); Note: FileOutputStream fos = new FileOutputStream (outFile); // this will open the file in append mode

flush()

close()

Flushes the stream, which forces any buffered output bytes to be written to the file Closes the file output stream Writes a byte to the underlying output stream as a 1-byte value Writes a boolean to the underlying stream as a 1-byte value. The value true is written as the cast value (byte) 1, and the value false is written as the cast value (byte) 0. Writes the String s to the underlying output stream as a sequence of bytes. The higher 8 bits of each character are discarded

writeBytes(int b)

writeBoolean(boolean v) writeBytes(String s)

writeChar(int v)

writeChars(String s)

Writes a char to the underlying output stream as a 2-byte Unicode value, with the high byte written first.
Write the String s to the underlying output stream as a sequence if characters. Writes each character to the underlying output stream as a 2-byte written first.

writeDouble(double v)
Convert the double value v to a long and then writes the long value to the

writeFloat(float v)

underlying output stream using 8 bytes, with the high byte written first. Convert the float value v to an int and then writes the int value to the underlying output stream using 4 bytes, with the high byte written first. written first.

writeInt(int v)

Write an int to the underlying output stream using 4 bytes, with the high byte

writeLong(long v)
Write a long value to the underlying output stream using 8 bytes, with the

writeShort(short v)
writeUTF(String v)

high byte written first. high byte written first.

Write a short value to the underlying output stream using 2bytes, with the

Write a String to the underlying output stream using motified UTF-8

encoding machine indepedent

import java.io.*; public class WritePrices2 {


public static void main(String[]args) throws IOException { FileOutputStream fos = new FileOutputStream("d:\\prices.dat"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos); dos.writeDouble(39.95); dos.writeDouble(3.22); dos.writeDouble(1.08); dos.close(); } }

FileInputStream
BufferedInputStream DataInputStream
Basic stream for byte-based input Supplies character-by-character input Provides buffering, which improves performance Supplies character-by-character and line-by-line input Typically uses FileInputStream or BufferedInputStream object

argument Supplies additional input methods

Sample declaration: FileInputStream fis = new FileInputStream (outFile); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis);

close()

readBoolean() readByte()

Closes the input stream Read a boolean from the input stream Read a byte from the input stream Read a char (16 bits) from the input stream Read a double (64 bits) from the input stream Read a float (32 bits) from the input stream

readChar()

readDouble() readFloat() readInt()

readLong

Read a int (32 bits) from the input stream


Read a long (64 bits) from the input stream Read a short (16 bits) from the input stream Replaced by BufferedReader.readLine()

readShort

readLine()

import java.io.*; public class ReadPrices2 { public static void main(String[]args)throws IOException { String filename="d:\\prices.dat"; FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); System.out.println("The values read from the " + filename + " files are:"); System.out.println(dis.readDouble()); System.out.println(dis.readDouble()); System.out.println(dis.readDouble()); dis.close(); } }

File Access
Is the manner in which files are written and retrieved

Two types of files access


Sequential Access
Data in the file are accessed sequentially, one item after another

Random Access
Also known as Direct access Individual data in the in the middle of the file can be retrieved, modified or rewritten without reading or writing any other data

Random access file is created as an object of the class RandomAccessFile The basic stream object needed for creating and using a random access file requires a file name, either as a string variable , string constant, or File object and a mode

RandomAccessFile raf = new RandomAccessFile(products.dat, rw);

Mode of RandomAccessFile
"r"
Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown.

"rw"
Open for reading and writing. If the file does not already exist then an attempt will be made to create it.

"rws"
Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.

"rwd"
Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device.

Return type

Method Name

void close() Closes this random access file stream and releases any system resources associated with the stream. FileChannel getChannel() Returns the unique FileChannel object associated with this file. FileDescriptor getFD() Returns the opaque file descriptor object associated with this stream. long getFilePointer() Returns the current offset in this file. long length() Returns the length of this file. int read() Reads a byte of data from this file. int read(byte[] b) Reads up to b.length bytes of data from this file into an array of bytes. int read(byte[] b, int off, int len) Reads up to len bytes of data from this file into an array of bytes.

Return type

Method Name

boolean readBoolean() Reads a boolean from this file. byte readByte() Reads a signed eight-bit value from this file. char readChar() Reads a Unicode character from this file. double readDouble() Reads a double from this file. float readFloat() Reads a float from this file. void readFully(byte[] b) Reads b.length bytes from this file into the byte array, starting at the current file pointer. void readFully(byte[] b, int off, int len) Reads exactly len bytes from this file into the byte array, starting at the current file pointer.

Return type

Method Name

int readInt() Reads a signed 32-bit integer from this file. String readLine() Reads the next line of text from this file. long readLong() Reads a signed 64-bit integer from this file. short readShort() Reads a signed 16-bit number from this file. int readUnsignedByte() Reads an unsigned eight-bit number from this file. int readUnsignedShort() Reads an unsigned 16-bit number from this file. String readUTF() Reads in a string from this file.

Return type

Method Name void seek(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. void setLength(long newLength) Sets the length of this file. int skipBytes(int n) Attempts to skip over n bytes of input discarding the skipped bytes. void write(byte[] b) Writes b.length bytes from the specified byte array to this file, starting at the current file pointer. void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this file. void write(int b) Writes the specified byte to this file. void writeBoolean(boolean v) Writes a boolean to the file as a one-byte value.

Return type void

Method Name writeByte(int v) Writes a byte to the file as a one-byte value.

void writeBytes(String s) Writes the string to the file as a sequence of bytes. void writeChar(int v) Writes a char to the file as a two-byte value, high byte first. void writeChars(String s) Writes a string to the file as a sequence of characters.

void writeDouble(double v) Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first. void writeFloat(float v) Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.

Return type void

Method Name writeInt(int v) Writes an int to the file as four bytes, high byte first.

void writeLong(long v) Writes a long to the file as eight bytes, high byte first. void writeShort(int v) Writes a short to the file as two bytes, high byte first. void writeUTF(String str) Writes a string to the file using UTF-8 encoding in a machine-independent manner. void writeInt(int v) Writes an int to the file as four bytes, high byte first. void writeLong(long v) Writes a long to the file as eight bytes, high byte first. void writeShort(int v) Writes a short to the file as two bytes, high byte first.

The key to creating and using random access files is imposing a structure on the file so that specific items can be located and updated in place. The most common structure consists of fixed-length records that themselves consist of a set of fixed-length items

A record consisting of integer product identification code, an integer number representing the quantity in stock, and a double precision number representing the items selling price
Integer Identification Code 4 bytes Integer Quantity 4 bytes Double Precision Price 8 bytes

import java.io.*; public class DisplayNext { public static void main(String[]args)throws IOException { String filename = "d:\\test.dat"; RandomAccessFile raf = new RandomAccessFile(filename,"rw"); raf.writeChars("Next"); raf.close(); } }

import java.io.*; public class DisplayReversed { static final int SIZEOFCHAR = 2; // there are 2 bytes per char public static void main(String[]args)throws IOException{ String filename = "d:\\test.dat"; char ch; long last, position, setbytepos; RandomAccessFile raf = new RandomAccessFile(filename,"rw"); last = raf.length(); //get the length of the file System.out.println(last); position = last- SIZEOFCHAR; //starting position of last char while(position>=0) { raf.seek(position); //move to the char ch = raf.readChar(); System.out.print(ch+"|"); position = position SIZEOFCHAR; } raf.close();} }

Product Information to be stored in a Random Access File


Identification Code 1001 1002 1003 Quantity in Stock 476 348 517 Selling Price 28.35 32.56 51.27

1004
1005

284
165

23.75
35.25

import java.io.*; public class WriteRandom { public static void main(String[]args)throws IOException { String filename ="products.dat"; String acctString, amtString, priceString; int acct, amt; double price; //set up the keyboard for string input InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); //set up the basic random access input/output stream RandomAccessFile raf = new RandomAccessFile(filename,"rw"); //enter and store data for five records for (int i=1; i<=5; i++){ System.out.print("Enter the identification number: "); acctString = br.readLine(); acct = Integer.parseInt(acctString); raf.writeInt(acct); System.out.print("Enter the quantity in stock: "); amtString = br.readLine(); amt = Integer.parseInt(amtString); raf.writeInt(amt); System.out.print("Enter the price: "); priceString = br.readLine(); price = Double.parseDouble(priceString); raf.writeDouble(price); } System.out.println("The file "+ filename + " has been written."); System.out.println("The length of file is "+ raf.length() + " bytes"); raf.close(); }}

import java.io.*;
public class ReadRandom { public static void main (String[]args) throws IOException { String filename = "d:\\products.dat"; int acct, amt; double price; //set the basic random access input/output stream RandomAccessFile raf =new RandomAccessFile(filename, "r"); //print headings System.out.println(" Quantity"); System.out.println("ID. No. In Stock Price"); System.out.println("------- --------- ------"); //read and print the data for (int i=1; i<=5; i++){ acct = raf.readInt(); amt = raf.readInt(); price = raf.readDouble(); System.out.println(" "+ acct + " "+ amt + " "+ price); } raf.close(); } }

Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion etc. The File object represents the actual file/directory on the disk. There are following constructors to create a File object:

File(File parent, String child); Following syntax creates a new File

instance from a parent abstract pathname and a child pathname string. File(String pathname) Following syntax creates a new File instance by converting the given pathname string into an abstract pathname. File(String parent, String child) Following syntax creates a new File instance from a parent pathname string and a child pathname string. File(URI uri) Following syntax creates a new File instance by converting the given file: URI into an abstract pathname.

Methods 1 public String getName() Returns the name of the file or directory denoted by this abstract pathname. 2 public String getParent() Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory. 3 public File getParentFile() Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory. 4 public String getPath() Converts this abstract pathname into a pathname string. 5 public boolean isAbsolute() Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise

Methods
6 7 public String getAbsolutePath() Returns the absolute pathname string of this abstract pathname. public boolean canRead() Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise. public boolean canWrite() Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise. public boolean exists() Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise

10 public boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.

Methods
11 public boolean isFile() Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise public long lastModified() Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs. public long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. public boolean createNewFile() throws IOException Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists. public boolean delete() Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.

12

13

14

15

Methods 16 public void deleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

17 public String[] list() Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
18 public String[] list(FilenameFilter filter) Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. 20 public File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. 21 public File[] listFiles(FileFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

Methods
23 public boolean mkdirs() Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise. 24 public boolean renameTo(File dest) Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise 25 public boolean setLastModified(long time) Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise . 26 public boolean setReadOnly() Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise. 27 public static File createTempFile(String prefix, String suffix, File directory) throws IOException Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.

Methods
29 public int compareTo(File pathname) Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument. public int compareTo(Object o) Compares this abstract pathname to another object. Returns returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument. public boolean equals(Object obj) Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname. public String toString() Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.

30

31

32

import java.io.File; public class DirList { public static void main(String args[]) { String dirname = "/java"; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println( "Directory of " + dirname); String s[] = f1.list(); for (int i=0; i < s.length; i++) { File f = new File(dirname + "/" + s[i]); if (f.isDirectory()) { System.out.println(s[i] + " is a directory"); } else { System.out.println(s[i] + " is a file"); } } } else { System.out.println(dirname + " is not a directory"); } }}

JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly translate between the world of the database, and the world of the Java application. The idea of a universal database access API is not a new one. For example, Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows environment. JDBC API aims to be as simple as possible while providing developers with maximum flexibility.

To connect to a database, you first need a JDBC Driver. JDBC Driver: set of classes that interface with a specific database engine.

Java Application

JDBC Driver Manager JDBCODBC Bridge Vendor Specific JDBC Driver Vendor Specific JDBC Driver

Database

Database

JDBC drivers exist for every major database including: MS Access, Oracle, IBM DB2, Informix, Postgre SQL, SQL Server, Sybase, and MySQL.

Import the required package Load the driver Define the connection URL Establish connection with database Create statement Execute query Process the result of the query Close connection

Import the package java.sql.* that contains useful classes and interfaces to access & work with database.

import java.sql.*;

Need to load suitable driver for underlying database. Different drivers & types for different databases are available. For MS Access, load following driver available with j2se.

Class.forName(sun.jdbc.odbc.JdbcOdbcDriver );

For Oracle, load the following driver. You have to download it explicitly.

Class.forName(oracle.jdbc.driver.OracleDriver );

For Oracle, load the following driver. You have to download it explicitly.

Class.forName("com.mysql.jdbc.Driver");

Class.forName()

Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to: Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class. For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread: Class t = Class.forName("java.lang.Thread")

Class.forName() will throw a ClassNotFoundException if your CLASSPATH is not set up properly. Hence, it's a good idea to surround the forName() with a try/catch block.

To get a connection, we need to specify the URL of a database (Actually we need to specify the address of the database which is in the form of URL) The only difficulty in establishing a connection is specifying the correct URL. In general, the URL has the following format:
jdbc:subprotocol:subname. JDBC indicates that this is a JDBC Connection The subprotocol identifies the driver you want to use. The subname identifies the database name/location. As we are using Microsoft Access database and we have loaded a JDBC-ODBC driver.

String URL = jdbc:odbc:personDSN; or String URL = jdbc:odbc:Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=+ dbname;

Here's how you might connect to MySQL: "jdbc:mysql://localhost/dbname";

String url =

Use DriverManager (this class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their application) to get the connection object. The URL of the database is passed to the getConnection method.

Connection con = DriverManager.getConnection(URL);

If DataBase requires username & password, you can use the overloaded version of getConnection method as shown below:

String usr = umair; String pwd = vu; Connection con = null; con = DriverManager.getConnection(URL, usr, pwd);

The JDBC Statement object sends SQL statements to the database. Statement objects are created from active Connection objects. For example:
Statement stmt = con.createStatement();

With a Statement object, you can issue SQL calls directly to the database.

The next step is to pass the SQL statements & to execute them.

Two methods are generally used for executing SQL queries. These are: executeQuery(sql) method Used for SQL SELECT queries. Returns the ResultSet object that contains the results of the query and can be used to access the query results. String sql = SELECT * from sometable; ResultSet rs = stmt.executeQuery(sql);

executeUpdate(sql)method This method is used for executing an update statement like INSERT, UPDATE or DELETE Returns an Integer value representing the number of rows updated

String sql = INSERT INTO tablename + (columnNames) Values (values) ; int count = stmt.executeUpdate(sql); Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE and ALTER TABLE

getMaxRows/setMaxRows

Determines the number of rows a ResultSet

getQueryTimeout/setQueryTimeout

may contain Unless explicitly set, the number of rows are unlimited (return value of 0)

Specifies the amount of a time a driver will wait

for a STATEMENT to complete before throwing a SQLException

A ResultSet contains the results of the SQL query.

Useful Methods
All methods can throw a SQLException
close Releases the JDBC and database resources The result set is automatically closed when the associated Statement object executes a new query getMetaDataObject Returns a ResultSetMetaData object containing information about the columns in the ResultSet

Useful Methods
next

Attempts to move to the next row in the ResultSet If successful true is returned; otherwise, false The first call to next positions the cursor a the first row findColumn Returns the corresponding integer value corresponding to the specified column name Column numbers in the result set do not necessarily map to the same column numbers in the database getXxx Returns the value from the column specified by column name or column index as an Xxx Java type Returns 0 or null, if the value is a SQL NULL Legal getXxx types:
double Date short Object byte String long int float Time

To close the database connection:


stmt.close(); connection.close();

Note: Some application servers, such as BEA WebLogic maintain a pool of database connections.
This is much more efficient, as applications do not have

the overhead of constantly opening and closing database connections.

7/29/2013

145

import java.sql.*; public class SampleJDBC { public static void main(String[]args){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D:/Person.mdb;"; // String database = "jdbc:odbc:myDBDSN" ; Connection cn = DriverManager.getConnection(db,"",""); Statement st = cn.createStatement(); st.execute("Select * from tblPerson'"); ResultSet rs = st.getResultSet(); if (rs != null){ while(rs.next()){ System.out.println(rs.getString(1) + "\t"+ rs.getString(2) + "\t"+ rs.getString(3)); }} rs.close(); cn.close(); }catch(Exception e){ e.printStackTrace();} }}

7/29/2013

148

To get started, we will first examine JDBC code for creating new tables. This java code creates a table for storing coffee data: Heres the SQL Statement:

CREATE TABLE COFFEES (COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, SALES INTEGER, TOTAL INTEGER);
7/29/2013 149

You could create this table via MySQL, but you can also create it via JDBC. A few things to note about the table:

The column named SUP_ID contains an integer value

indicating a Supplier ID.


Suppliers will be stored in a separate table. In this case, SUP_ID is referred to as a foreign key.

The column named SALES stores values of SQL type

INTEGER and indicates the number of pounds of coffee sold during the current week. The final column, TOTAL, contains a SQL INTEGER which gives the total number of pounds of coffee sold to date.
7/29/2013 150

import java.sql.*; public class CreateCoffees { public static void main(String args[]) { String url = "jdbc:mysql://localhost/cerami"; Connection con; String createString; createString = "create table COFFEES " + "(COF_NAME VARCHAR(32), " + "SUP_ID INTEGER, " + "PRICE FLOAT, " + "SALES INTEGER, " + "TOTAL INTEGER)"; Statement stmt;

7/29/2013

151

try { Class.forName("com.mysql.jdbc.Driver"); 1 } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { 2 con = DriverManager.getConnection(url); 3 stmt = con.createStatement(); 4 stmt.executeUpdate(createString); stmt.close(); 6 con.close(); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); }

}
}
7/29/2013 JDBC, Part I 152

7/29/2013

JDBC, Part I

153

import java.sql.*;

public class InsertCoffees {


public static void main(String args[]) throws SQLException { System.out.println ("Adding Coffee Data"); ResultSet rs = null; PreparedStatement ps = null; String url = "jdbc:mysql://localhost/cerami"; Connection con; Statement stmt; try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); }

7/29/2013

154

try {

2 con = DriverManager.getConnection(url); 3 stmt = con.createStatement(); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); 4 stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.executeUpdate ("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); 6 stmt.close(); con.close(); System.out.println ("Done"); } catch(SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); }

} }
7/29/2013 JDBC, Part I 155

7/29/2013

JDBC, Part I

156

import java.sql.*; public class SelectCoffees { public static void main(String args[]) throws SQLException { ResultSet rs = null; PreparedStatement ps = null; String url = "jdbc:mysql://localhost/cerami"; Connection con; Statement stmt; try { Class.forName("org.gjt.mm.mysql.Driver"); 1 } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url); 2 stmt = con.createStatement();
157

3
7/29/2013

ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES:"); while (uprs.next()) { 5 String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } 6 uprs.close(); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
7/29/2013

158

7/29/2013

159

SQL Exceptions
Nearly every JDBC method can throw a SQLException

in response to a data access error If more than one error occurs, they are chained together SQL exceptions contain:
Description of the error, getMessage The SQLState (Open Group SQL specification) identifying the exception, getSQLState A vendor-specific integer, error code, getErrorCode A chain to the next SQLException, getNextException

7/29/2013

160

try {
... // JDBC statement. } catch (SQLException sqle) { while (sqle != null) { System.out.println("Message: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("Vendor Error: " + sqle.getErrorCode()); sqle.printStrackTrace(System.out); sqle = sqle.getNextException(); } }

7/29/2013

161

Three types of Statement objects are available. Statement


The Statement objects are used for executing

simple SQL statements

PreparedStatement
The PrepaeredStatement are used for executing

precompiled SQL statements and passing in different parameters to it.

CallableStatement
Theses are used for executing stored procedures.

163

From the last lecture, we know how to use JDBC Statement objects for querying/updating tables. The PreparedStatement object provides similar functionality and provides two additional benefits:
Faster execution Parameterized SQL Statements

7/29/2013

164

Unlike a regular Statement object, a PreparedStatement object is given a SQL statement when it is created. The advantage: the SQL statement will be sent to the database directly, where it will be pre-compiled. As a result, PreparedStatements are generally faster to execute that regular Statements, especially if you execute the same PreparedStatement multiple times.

7/29/2013

165

PreparedStatements are generally more convenient that regular Statements because they can easily be parameterized. For example, you can create a PreparedStatement SQL template, and then specify parameters for the your SQL query (examples to follow.)

7/29/2013

166

As with Statement objects, you create a PreparedStatement object with a Connection method. For example:

PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

In this example, the ? indicates a parameter placeholder which can be set via the JDBC API.

7/29/2013

167

Once you have your PreparedStatement, you need to supply parameter values for each of the question mark placeholders. You do this by calling one of the setXXX methods defined in the PreparedStatement API.
If the value you want to substitute for a question mark is a Java int,

you call the setInt() method. If the value you want to substitute for a question mark is a Java String, you call the setString() method. In general, there is a setXXX method for each type in the Java programming language.

7/29/2013

168

setXXX arguments:
The first argument indicates which question mark

placeholder is to be set. The second argument indicates the replacement value.

For example:
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");

7/29/2013

169

These two code fragments accomplish the same thing: Code Fragment 1:
String updateString = "UPDATE COFFEES SET SALES = 75 " + "WHERE COF_NAME LIKE 'Colombian'"; stmt.executeUpdate(updateString);

Code Fragment 2:

PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate():

7/29/2013

JDBC, Part II

170

To execute a PreparedStatement:
executeUpdate() executeQuery()

Same as a regular Statement, except that no SQL String parameter is specified (because it has already been specified.)

7/29/2013

171

Once a parameter has been set with a value, it will retain that value until it is reset to another value or the clearParameters() method is called. You can therefore create one PreparedStatement and:

set two parameters, then execute. change just one parameter, then re-execute. change another parameter, then re-execute, etc.

7/29/2013

172

An example:

updateSales.setInt(1, 100); updateSales.setString(2, "French_Roast"); updateSales.executeUpdate(); // changes SALES column of French Roast row to 100 updateSales.setString(2, "Espresso"); updateSales.executeUpdate(); // changes SALES column of Espresso row to 100 (the first // parameter stayed 100, and the second parameter was reset // to "Espresso")

7/29/2013

173

You can often make coding easier by using a for loop or a while loop to set values for input parameters. The next code fragment illustrates the basic idea:

One PreparedStatement is created. A for loop runs 5 times. Each time through, the code sets a

new value and executes the SQL statement. Updates sales for 5 different coffees.

7/29/2013

174

executeQuery() always returns a ResultSet object. executeUpdate() returns an int that indicates how many rows of the table were updated.
For example:
updateSales.setInt(1, 50); updateSales.setString(2, "Espresso"); int n = updateSales.executeUpdate(); // n = 1 because one row had a change in it

In this case, only 1 row is affected. Hence, executeUpdate() returns 1. When the method executeUpdate() is used to execute a table creation/alteration statement, it always return 0.

7/29/2013

175

PreparedStatement updateSales; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME like ?"; updateSales = con.prepareStatement(updateString); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = {"Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf"}; int len = coffees.length; for(int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); }

7/29/2013

176

7/29/2013

177

Sometimes you need to use two or more tables to get the data you want. For example:
Proprietor of the Coffee Break wants a list of the coffees he buys from

A join is a database operation that relates two or more tables by means of values that they share in common.
In out example, the tables COFFEES and SUPPLIERS both have a

Acme, Inc. This involves data from two tables: COFFEES and SUPPLIERS. To do this, you must perform a SQL Join.

column SUP_ID, which can be used to join them.

7/29/2013

178

Before going any further, we need to create the SUPPLIERS table and populate it with values. The code below create the table:
String createSUPPLIERS = "create table SUPPLIERS " + "(SUP_ID INTEGER, SUP_NAME VARCHAR(40), " + "STREET VARCHAR(40), CITY VARCHAR(20), " + "STATE CHAR(2), ZIP CHAR(5))"; stmt.executeUpdate(createSUPPLIERS);

7/29/2013

179

The code below inserts data for three suppliers:


stmt.executeUpdate("insert into SUPPLIERS values (101, " + 'Acme, Inc.', '99 Market Street', 'Groundsville', " + 'CA', '95199'"); stmt.executeUpdate("Insert into SUPPLIERS values (49," + 'Superior Coffee', '1 Party Place', 'Mendocino', 'CA', " + '95460'"); stmt.executeUpdate("Insert into SUPPLIERS values (150, " + 'The High Ground', '100 Coffee Lane', 'Meadows', 'CA', " + '93966'");

7/29/2013

JDBC, Part II

180

The following code selects the whole table and lets us see what the table SUPPLIERS looks like:
ResultSet rs = stmt.executeQuery("select * from SUPPLIERS"); The result set will look similar to this:

SUP_ID SUP_NAME STREET CITY STATE ZIP -----------------------------------------------------------------------------------101 Acme, Inc. 99 Market Street Groundsville CA 95199 49 Superior Coffee 1 Party Place Mendocino CA 95460 150 The High Ground 100 Coffee Lane Meadows CA 93966

7/29/2013

181

Now that we have both tables, we can proceed with the Join. The goal is the find coffees that are purchased from a particular supplier. Since both tables have a SUP_ID, we can use this ID to perform the Join. Since you are using two tables within one SQL statement, you usually indicate each field with a TableName.FieldName. For example: COFFEES.SUP_ID or SUPPLIERS.SUP_ID.

7/29/2013

182

Heres the Join:


String query = " SELECT COFFEES.COF_NAME " + "FROM COFFEES, SUPPLIERS " + "WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' " + "and SUPPLIERS.SUP_ID = COFFEES.SUP_ID"; ResultSet rs = stmt.executeQuery(query); System.out.println("Coffees bought from Acme, Inc.: "); while (rs.next()) { String coffeeName = rs.getString("COF_NAME"); System.out.println(" " + coffeeName); }

7/29/2013

183

The code fragment on the last slide will produce the following output:
Coffees bought from Acme, Inc.: Colombian Colombian_Decaf

Full code is available on the next few slides

7/29/2013

184

import java.sql.*; public class Join { public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; String query = "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from COFFEES, SUPPLIERS " + "where SUPPLIERS.SUP_NAME like 'Acme, Inc.' and " + "SUPPLIERS.SUP_ID = COFFEES.SUP_ID"; Statement stmt; try { Class.forName("myDriver.ClassName");1 } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); }
7/29/2013 185

try { con = DriverManager.getConnection (url, 2 "myLogin", "myPassword"); 3 stmt = con.createStatement(); 4 ResultSet rs = stmt.executeQuery(query); System.out.println("Supplier, Coffee:"); while (rs.next()) { 5 String supName = rs.getString(1); String cofName = rs.getString(2); System.out.println(" " + supName + ", " + cofName); }

stmt.close(); 6 con.close();
} catch(SQLException ex) { System.err.print("SQLException: "); System.err.println(ex.getMessage()); } }
7/29/2013

186

7/29/2013

187

There are times when you do not want one statement to take effect unless another one also succeeds. For example:
1. 2.

If the first statement succeeds, but the second one fails, you are out $400! To do with this possibility, most database support many levels of transactions.

Take $400 out of your Checking Account. Take this $400 and transfer to your Savings Account.

7/29/2013

188

A transaction is a set of one or more statements that are executed together as a unit. Hence, either all of the statements are executed, or none of the statements are executed.

7/29/2013

189

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where con is an active connection:
con.setAutoCommit(false);

7/29/2013

190

Once auto-commit mode is disabled, no SQL statements will be committed until you call the commit() method explicitly. All statements executed after the previous call to the method commit will be included in the current transaction and will be committed together as a unit. The code on the next slide illustrates the basic idea.

7/29/2013

191

con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true);

7/29/2013

192

To cancel a transaction, call the rollback() method. This aborts the transaction and restores values to what they were before the attempted update. If you are executing multiple statements within a transaction, and one of these statements generates a SQLException, you should call the rollback() method to abort the transaction and start over again. Complete example is on the next few slides.

7/29/2013

193

import java.sql.*; public class TransactionPairs { public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null; Statement stmt; PreparedStatement updateSales; PreparedStatement updateTotal; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME = ?"; String updateStatement = "update COFFEES " + "set TOTAL = TOTAL + ? where COF_NAME = ?"; String query = "select COF_NAME, SALES, TOTAL from COFFEES";

7/29/2013

194

try { Class.forName("myDriver.ClassName"); 1 } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); }

try { 2 con = DriverManager.getConnection(url, "myLogin", "myPassword"); 3 updateSales = con.prepareStatement(updateString); updateTotal = con.prepareStatement(updateStatement) int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = {"Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf"}; int len = coffees.length;
7/29/2013 195

con.setAutoCommit(false); for (int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate();
updateTotal.setInt(1, salesForWeek[i]); updateTotal.setString(2, coffees[i]); updateTotal.executeUpdate(); 4 con.commit(); } con.setAutoCommit(true); updateSales.close(); 6 updateTotal.close();

7/29/2013

196

} catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); if (con != null) { try { System.err.print("Transaction is being "); System.err.println("rolled back"); con.rollback(); } catch(SQLException excep) { System.err.print("SQLException: "); System.err.println(excep.getMessage()); } } } } }

7/29/2013

197

1. 2. 3. 4. 5.
6. 7.

8.
9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

It indicates a parameter placeholder used in PreparedStatement It is a simple API for connecting from Java applications to multiple databases. What does ODBC stands for? Driver for MS Access Database A methods used for executing SQL SELECT queries that returns the ResultSet object File extension of 2000-2003 MS Access database It returns the class object associated with the class or interface with the given string name It is used for executing precompiled SQL statements and passing in different parameters to it. A method used for executing an update statement like INSERT, UPDATE or DELETE that returns an Integer value representing the number of rows updated A type of exception that occurs if you use Class.forName() It contains useful classes and interfaces to access & work with database. This class will attempt to load the driver classes referenced in the "jdbc.drivers" system property A method used to close the Connection, Statement and ResultSet object A method of DriverManager class to pass the connection url of the database A right way to create a statement object in Java It contains the results of the query and can be used to access the query results A method of ResultSet object that attempts to move to the next row A type of exception that refers to data access error Type of statement used for executing simple SQL statements It is used for executing stored procedures.

7/29/2013

198

1-8 Steps in using JDBC (in order) 9-11 Different Types of statement 12-15 DML Statements 16-17 DDL Statement 18-20 Examples of database engine

A ResultSet contains the results of the SQL query Represented by a table with rows and columns Maintains a cursor pointing to its current row of data. Initially the cursor positioned before the row (0). First row has index 1 A default ResultSet object is not updatable and has a cursor that moves forward only. You can iterate over through it only once and only from the first row to last row.

Updatable and/or Scrollable ResultSet


It is possible to produce ResultSet objects that are

scrollable and/or updatable (since JDK 1.2) With the help of such ResultSet, it is possible to move forward as well as backward with in RestultSetobject. Another advantage is, rows can be inserted, updated or deleted by using updatable ResultSet object

String sql = SELECT * FROM Person; PreparedStatement pStmt = con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSI TIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = pStmt.executeQuery( );

The following code fragment, illustrates how to make a ResultSet object that is scrollable and updatable

Other Useful Methods next( )


Attempts to move to the next row in the ResultSet, if available The next() method returns true or false depending upon whether the next row

previous( )

is available (exist) or not. Before retrieving any data from ResultSet, always remember to call next()at least once because initially cursor is positioned before first row.
-Moves the cursor to the previous row in the ResultSet object, if available -

absolute(int)

Returns true if cursor is on a valid row, false it is off the result set. -Throws exception if result type is TYPE_FORWARD_ONLY.

Moves the cursor to the given row number in the ResultSetobject. -If given row number is positive, moves the cursor forward with respect to

beginning of the result set. If the given row number is negative, the cursor moves to the absolute row position with respect to the end of the result set.

updaters (for primitives, String and Object)


Used to update the column values in the current row or in insert row (discuss later) -Do not update the underlying database -Each update method is overloaded; one that takes column name while other takes column index. For example String updater are available as:
updateString(String columnName, String value) updateString(String columnIndex, String value)

updateRow( )

Updates the underlying database with new contents of the current row of this ResultSetobject An updatable resultset object has a special row associate with it i.e. insert row -Insert row a buffer, where a new row may be constructed by calling updater methods. -Doesnt insert the row into a result set or into a database. Inserts the contents of the current row into this ResultSet object and into the database too. -Moves the cursor back to the position where it was before calling moveToInsertRow()

moveToInsertRow(int)

insertRow( )

last( ) & first( )


Moves the cursor to the last & first row of the

ResultSetobject respectively. -Throws exception if the ResultSet is TYPE_FORWARD_ONLY


getRow( )
Returns the current row number

deleteRow( )
Deletes the current row from this ResultSet object

and from the underlying database. Throws exception if the cursor is on the insert row.

import java.sql.*; public class ResultSetEx { public static void main (String args[ ]) { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String url = jdbc:odbc:personDSN; Connection con = DriverManager.getConnection(url); String sql = SELECT * FROM Person; PreparedStatement pStmt = con.prepateStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = pStmt.executeQuery(); // moving cursor forward i.e. first row rs.next( ); // printing column name value of current row (first) System.out.println(moving cursor forward); String name = rs.getString(Name); System.out.println(name); // moving cursor forward i.e. on to second row rs.next( ); // moving cursor backward i.e to first row rs.previous( ); // printing column name value of current row (first) System.out.println(moving cursor forward); name = rs.getString(Name); System.out.println(name); con.close(); }catch(Exception sqlEx){ System.out.println(sqlEx); } } // end main } // end class

import java.sql.*; public class ResultSetEx { public static void main (String args[ ]) { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver ); String url = jdbc:odbc:personDSN; Connection con = DriverManager.getConnection(url); String sql = SELECT * FROM Person; PreparedStatement pStmt = con.prepateStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pStmt.executeQuery(); // moving cursor to second row rs.absolute(2); // update address column of 2nd row in rs rs.updateString(Address, model town); // update the row in database rs.updateRow( ); con.close(); }catch(Exception sqlEx){ System.out.println(sqlEx); } } // end main 32 } // end class

import java.sql.*; public class ResultSetEx { public static void main (String args[ ]) { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver ); String url = jdbc:odbc:personDSN; Connection con = DriverManager.getConnection(url); String sql = SELECT * FROM Person; PreparedStatement pStmt = con.prepateStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = pStmt.executeQuery(); // moving cursor to insert row rs.moveToInsertRow(); // updating values in insert row rs.updateString( Name , imitiaz ); rs.updateString( Address , cantt ); rs.updateString( phoneNum , 9201211 ); // inserting row in resultset & into database rs.insertRow( ); con.close(); }catch(Exception sqlEx){ System.out.println(sqlEx); } } // end main } // end class

import java.sql.*; public class ResultSetEx { public static void main (String args[ ]) { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver ); String url = jdbc:odbc:personDSN; Connection con = DriverManager.getConnection(url); String sql = SELECT * FROM Person; PreparedStatement pStmt = con.prepateStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = pStmt.executeQuery(); // moves to last row of the resultset rs.last(); // retrieving the current row number int rNo = rs.getRow(); System.out.println(current row number + rNo); // delete current row from rs & db i.e. 4 because // previously we have called last() method rs.deleteRow( ); con.close(); }catch(Exception sqlEx){ System.out.println(sqlEx); } } // end main } // end class

Meta Data is data (information) about data. The actual data has no meaning without existence of Meta data. ResultSet Meta Data will help you in answering such questions

How many columns are in the ResultSet? What is the name of given column? Are the column name case sensitive? What is the data type of a specific column? What is the maximum character size of a column? Can you search on a given column?

Creating ResultSetMetaData object From a ResultSet (the return type of executeQuery() ), derive a ResultSetMetaData object by calling getMetaData() method as shown in the given code snippet (here is a valid ResultSetobject): ResultSetMetaData rsmd = rs.getMetaData();

ResultSetMetaData methods
getColumnCount ( )
Returns the number of columns in the result set

getColumnDisplaySize (int)
Returns the maximum width of the specified column in characters

getColumnName(int) / getColumnLabel (int)


The getColumnName() method returns the database name of the column The getColumnLabel() method returns the suggested column label for printouts

getColumnType (int)
Returns the SQL type for the column to compare against types in java.sql.Types

You might also like