You are on page 1of 134

By Phach Sina Email: sina_phach@yahoo.

com Phone: 092 892 950

Chapter 1: Introduction
Objective:

Introduction about java and model application structure of java application for edit, compile and run java.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Java Overview:
Java object oriented programming 100% that development by Sun Microsoft System company.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Web site for Java


www.javasoft.com (Suns java site) www.gamlan.com (incredible collection of java resource) www.javaworld.com (online magazine devote to java)

www.booksite.net/bishop (for this book and its

companion text)

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Applications for write or edit within java


JCreator
Eclipse JBuilder NetBeans

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Applications for run java code


Jdk1.5.0

Jdk1.6.0

How to save java code ?


When you save, You must be save extension .java

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
public class ClassName{ public static void main(String []args){ statements; } } *** you should be save in(path): C:\Program Files\Java\jdk1.5.0 or jdk1.6.0\bin: File name: ClassName.java
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

How to compile java code?


1. After we saved and we want to compile it : Start run : cmd OK
C:\Program Files\Java\jdk1.5.0 or jdk1.6.0\bin javac ClassName.java 2. Or we can compile within JCreator

How to runs ?
1. Start run : cmd OK
C:\Program Files\Java\jdk1.5.0 or jdk1.6.0\bin java ClassName 2. OR we can run within JCreator

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodesthe machine language of the Java Virtual Machine (Java VM).[2] The java launcher tool then runs your application with an instance of the Java Virtual Machine (Figure 1.1). The terms "Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform. Figure 1.1. Compiling and running an application.
[2]

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Structure
import PackageName.*; class ClassName{ public static void main(String []args){ statement1; statement2; . . statementn; } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import java.io.*; public class HelloJava{ static int x; static int y; public static void main(String []args){ System.out.println("Hello java "); x=100; y=200; System.out.println("Value x and y: "+x+"\t"+y);

} }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 2: Data type, Variable, Array


Number:
int

: 32 bit long : 64 bit short : 16 bit byte : 8 bit double : 64 bit float : 32 bit
point number : ( ex: 12.22)
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

integer:
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647. This data type is used for integer values.

byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to 127 (inclusive). We can save memory in large byte.

short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is used to save memory in large
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

long
The long data type is a 64-bit. It ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values.

float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float (instead of double) to save memory in large arrays.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data type is generally the default choice for decimal values.

boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data type for conditional statements. true and false are not the same as True and False. They are defined constants of the language.

char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
2011

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 3: Operator
Algorithm : + , - , * , / , % ,... o Cooperation : > , < , >= , <= ,... o Relation : && , || , ! , != , == Example:
o

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example2:
class ArithmeticDemo { public static void main (String[] args){ int result = 1 + 2; // result is now 3 System.out.println(result); result = result - 1; // result is now 2 System.out.println(result); result = result * 2; // result is now 4 System.out.println(result); result = result / 2; // result is now 2 System.out.println(result); result = result + 8; // result is now 10 result = result % 7; // result is now 3 System.out.println(result); }}
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Assign Operator

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 4: Control Statement


If statement: Use the if statement to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if condition is true }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
class Ifstatement{ static int a,b; static String max=""; public static void main(String []args){ a=20; b=10; if(a>b){ max="Value of a is bigger value of b"; } System.out.println("Max :"+max); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Control Statements:

If...else statement:
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example: class Max{


static int a,b; static String max=""; public static void main(String []args){ a=2; b=10; if(a>b){ max=max+ "Value of a is bigger value of b"; } else{ max="Value of a is smaller than value of b; } System.out.println("Max:"+max); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

If...else if...else Statement :


Use the if....else if...else statement to select one of several blocks of code to be executed. Syntax: if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import javax.swing.*; public class Maximum { int a,b,c; String myRead(String m){ return JOptionPane.showInputDialog(null,m); } void myOut(String m){ JOptionPane.showMessageDialog(null,m); } public Maximum() { String m; a=Integer.parseInt(myRead("Input value of A:")); b=Integer.parseInt(myRead("Inpute value of B:")); c=Integer.parseInt(myRead("Input value of C:"));
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

if(a>b){

if(a>c){ m="Max is A:"+a; } else{ m="Max is C:"+c; }


} else if(b>a){ if(b>c){ m="Max is B:"+b; } else{ m="Max is C:"+c; } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

else{ m=; } myOut(m);


} /* end of constrator */ public static void main (String[] args) { new Maximum(); } } /* end of class */

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

for Loop
Syntax for (variable=startvalue;variable<=endvalue;variable=variable+increment){ code to be executed } Example The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import javax.swing.*; class Test{ int i=0; String report=""; public Test(){ for(i=0;i<=5;i++){ report=report+"\t"+i+"\n"; } JOptionPane.showMessageDialog(null,report); } public static void main (String[] args) { new Test(); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

For...In Statement
The for...in statement loops through the properties of an object. Syntax for (variable :s object) { code to be executed } Note: The code in the body of the for...in loop is executed once for each property.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import javax.swing.*; class Test{ int a[]=new int[4]; String report=""; String myRead(String m){ return JOptionPane.showInputDialog(null,m); } public Test(){ for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(myRead("Input Number")); } for(int x : a){ report=report+"\t"+x+"\n"; } JOptionPane.showMessageDialog(null,report); }} ____________________________________________________________
Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950 2011

The while Loop The while loop loops through a block of code while a specified condition is true. Syntax while (variable<=endvalue) { code to be executed }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
public class hello { static int i=0; public static void main (String[] args) { while(i<=5){ System.out.println(i+"\n"); i++; } } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

The do...while Loop


The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true. Syntax do { code to be executed } while (variable<=endvalue); Example The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
public class hello { static int i=0; public static void main (String[] args) { do{ i=i+1; System.out.println("Statement ="+i); }while(i<=5); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Switch Statement
Use the switch statement to select one of many blocks of code to be executed. Syntax switch(n){ case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case ____________________________________________________________ automatically. Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import javax.swing.*; class Days{ int num; String day; String myRead(String m){ return JOptionPane.showInputDialog(null,m); } void Display(String m){ JOptionPane.showMessageDialog(null,m); } public Days(){ num=Integer.parseInt(myRead("Input number of days :")); switch(num){ case 1:day="Monday"; break; case 2:day="Tuesday";break; ____________________________________________________________
Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950 2011

case 3:day="Wednesday";break; case 4:day="Thusday";break; case 5:day="Friday";break; case 6:day="Sartuday";break; default:day="Sunday"; } Display("Today is :"+day); } public static void main (String[] args) { new Days(); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Functions
you can put your code into a function. A function contains code that will be executed by an event or by a call to the function.
Syntax function functionname(var1,var2,...,varX){ some code } The parameters var1, var2, etc. are variables or values passed into the function. Note: A function with no parameters must include the parentheses () after the function name.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
class Test{ String sum(String fn,String ln,int age){ return "Mrs/Mr. "+fn+"_"+ln+" has age: "+age; } public Test(){ System.out.println(sum("Dara","Vichet",25)); } public static void main (String[] args) { new Test(); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 5: Introduction Classes and Object


Class in Java: Class is temple that define form of object. Its has contain data, code and methods.

Syntax 1:
class ClassName{ type instance-variable1; type instance-variable2; type method1(.....){ ....} type method2(.....){.....} //........ }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Syntax 2:
Class ClassName{ constructor1; constructor2; . . . datafield1; datafield2; method1; method1; }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 1:
class Student { static int id,age; static String name,sex; static String Display(){ id=1; name="Dara"; sex="Male"; age=26; return id+"\t"+name+"\t"+sex+"\t"+age; } public static void main (String[] args) { System.out.println(Display()); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 2:
class Student { int id,age; String name,sex; String Display(){ return id+"\t"+name+"\t"+sex+"\t"+age; } Student(){ id=10; name="Dara"; sex="Male"; age=45; }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Student(int id,int age,String name,String sex ){ this.id=id; this.name=name; this.sex=sex; this.age=age; } public static void main (String[] args) { System.out.println("ID\tName\tSex\t Age"); Student stu=new Student(); System.out.println(stu.Display()); Student stu2=new Student(20,50,"Vichet","Male"); System.out.println(stu2.Display()); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Object:
With the knowledge you now have of the basics of the Java programming language, you can learn to write your own classes. In this lesson, you will find information about defining your own classes, including declaring member variables, methods, and constructors. You will learn to use your classes to create objects, and how to use the objects you create.

* This section covers creating and using objects. You will learn how to instantiate an object, and, once instantiated, how to use the dot operator to access the object's instance variables and methods.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

How to Create Objects:


As you know, a class provides the blueprint for objects; you create an object from a class creates an object and assigns it to a variable: Syntax: ClassName objects=new ClassName(...); objects.datamember(); Example: Point originOne = new Point(23, 94); Rectangle rectTwo = new Rectangle(50, 100);
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 1 :
class Student { static int id,age; static String name,sex; static String Display(){ return id+"\t"+name+"\t"+sex+"\t"+age; } public static void main (String[] args) { Student stu=new Student(); stu.id=20; stu.name="John "; stu.age=30; stu.sex="Male"; System.out.println(stu.Display()); } ____________________________________________________________ } Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com

Tel: 092892950

2011

Example 2 :
import javax.swing.*; public class Book { String id,author; double price; public String myRead(String m){ return JOptionPane.showInputDialog(null,m); } public void Display(String m){ JOptionPane.showMessageDialog(null,m); } public void setId(String id){this.id=id;} public void setAuthor(String author){this.author=author;} public void setPrice(double price){this.price=price;} public String getId(){return id;} public String getAuthor(){return author;}
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public double getPrice(){return price;} public String ToString(){ String report=""; return report=report+getId()+"\n"+getAuthor()+"\n"+getPrice()+"\n"; } public Book() { id="01"; author="Veng heng"; price=12.8; } public Book(String id,String author,double price){ setId(id); setAuthor(author); setPrice(price); }}

/* end of class Book


2011

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

/* Call Class Book()


public class TestBook { public static void main(String[] args) { Book b1=new Book(); b1.setId("002"); b1.setAuthor("Joh smith"); Book b2=new Book("003","Gently",200.00); b1.Display(b1.ToString()); b2.Display(b2.ToString()); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 3: Design and write Definition Class Product. Class Product:


public class Product { int id; String name; double price; void setId(int id){this.id=id;} void setName(String name) {
this.name=name;
}

void setPrice(double p){price=p;} int getId(){return id;} String getName(){return name;} double getPrice(){return price;}

String toDisplay(){ return getId()+"\t"+getName()+ "\t + getPrice()+"\n"; } Product(){ id=1; name="ABC"; price=24.00; } Product(int id,String name,double price){ setId(id); setName(name); setPrice(price); } } /* End of Class Product as : Product.java***
2011

____________________________________________________________ ****Save

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

Class MyStore for Display all Product:


import javax.swing.*; public class MyStore { int n=Integer.parseInt(myRead("Number of Product=")); Product p[]=new Product[n];
String myRead(String m){

return JOptionPane.showInputDialog(null,m); } void Display(String m){ JTextArea dis=new JTextArea(m); JOptionPane.showMessageDialog(null,dis,"Information of Products , __ JOptionPane.PLAIN_MESSAGE); } void myAddProduct(){ for(int i=0;i<p.length;i++){ int id=Integer.parseInt(myRead("ID")); String name=myRead("Name"); double price=Double.parseDouble(myRead("Price")); p[i]=new Product(id,name,price); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Class MyStore for Display all Product:


import javax.swing.*; public class MyStore { int n=Integer.parseInt(myRead("Number of Product=")); Product p[]=new Product[n]; String myRead(String m){ return JOptionPane.showInputDialog(null,m); } void Display(String m){ JTextArea dis=new JTextArea(m); JOptionPane.showMessageDialog(null,dis,"Information of Products , __ JOptionPane.PLAIN_MESSAGE); } void myAddProduct(){ for(int i=0;i<p.length;i++){ int id=Integer.parseInt(myRead("ID")); String name=myRead("Name"); double price=Double.parseDouble(myRead("Price")); p[i]=new Product(id,name,price); } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950 2011

public void SortPrice(){ for(int i=0;i<p.length;i++) for(int j=i+1;j<p.length;j++){ if(p[i].price>p[j].price){ Product temp; temp=p[i]; p[i]=p[j]; p[j]=temp; } } } String getProduct(){ String message=""; for(Product x : p) message=message+x.toDisplay(); return message; }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

void Search(){ Product pro=new Product(); String strname,question; String report=""; boolean t=false; question=myRead("Do you want to search? yes/no "); if(question.equalsIgnoreCase("yes")){ strname=myRead("Search by name:"); for(int i=0;i<p.length;i++){ if(strname.equalsIgnoreCase(p[i].getName())) report=report+p[i].getId()+"\t"+p[i].getName()+"\t"+p[i].getPrice()+"\n"; } Display(report); } } public MyStore() {
}
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public static void main (String[] args) { MyStore ms=new MyStore(); ms.myAddProduct(); ms.SortPrice(); ms.Display(ms.getProduct()); ms.Search(); } /* End of main() Program } /* End of Class MyStore

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 6: Inheritance
In this chapters, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class for extened is called a superclass ( base class or a parent class).
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

This picture is want to show about Employee class is a derived class that extended from the Person class.
Person: (name,sex)

Employee: (id,name,sex,position,salary Syntax: class Subclass extends SuperClass{ . . . }


____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 1:
class A{ .... public A(){ .......... } } class B extends A{ .... public B(){ .... } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 2:
class Person{ String name; String sex; ....... public Person(){ name=sok; sex=Male; } }

class Employee extends Person{ int id; String position; double salary; public Employee(){ super(); id=1; position=program; salary=400; } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Access Rule ( Keyword) :


+ public : It can access in subclass. + protected : It can access in subclass. + private : It can not access in subclass. *Note: If we dont declare, Default is public. Example:
class A { private int x; protected int y; public int w; } class B extends A{ public B(){ x=10; //Error y=20; //OK w=100; //OK } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

super(): use for call data-member of super class (base class).

Example 1:
class A { protected int x; protected int y; public String toString(){ return x+"\t"+y; } } class B extends A{ int z; public B(){ super(); } public String display(){ return super.toString()+"\t"+z; } public static void main (String[] args) { B testSuper=new B(); testSuper.x=10; testSuper.y=20; testSuper.z=30; System.out.println(testSuper.display()); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 2:
Point

Circle

class Point{ int x,y; void setX(int x){this.x=x;} void setY(int y){this.y=y;} int getX(){return x;} int getY(){return y;} String GetvalXY(){ return getX()+"\t"+getY(); }
____________________________________________________________

Point(){ x=10; y=20; } Point(int x,int y){ this.x=x; this.y=y; } } 2011

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

class Circle extends Point{ double radius; void setRadius(double r){radius=r;} double getRadius(){return radius;} double getArea(){ return Math.PI*radius*radius; } String Display(){ return super.GetvalXY()+"\t"+ getRadius()+"\t"+getArea(); } public Circle(){ super(); radius=3.11; } public Circle(int x,int y,double r){ super(x,y); radius=r; }

public static void main (String[] args) { Circle c1=new Circle(); Circle c2=new Circle(100,200,2); System.out.println(c1.Display()); System.out.println(c2.Display()); } }

-------Result:............

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 7: Polimorphism
Group of object reference to other class in the same

one hierarchy and the same time.


Product

Book

Dictionary
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class Product { String code; String description; void setCode(String c){code=c;} void setDescription(String d){description=d;} String getCode(){return code;} String getDescription(){return description;} public String toString(){ return getCode()+"\t"+getDescription(); }

public Product() { code="001"; description="USA"; } public Product(String c,String d){ code=c; description=d; }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class Book extends Product{ String author; int page; void setAuthor(String a){author=a;} void setPage(int p){page=p;} String getAuthor(){return author;} int getPage(){return page;} public String toString(){ return super.toString()+"\t"+getAuthor()+"\t"+getPage(); } public Book() { super(); author="Sina"; page=10; } public Book(String c,String d,String a,int p){ code=c; description=d; author=a; page=p; } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class Dictionary extends Book{ int word; void setWord(int w){word=w;} int getWord(){return word;} public String toString(){ return super.toString()+"\t"+getWord(); } public Dictionary() { super(); word=200; } public Dictionary(String c,String d,String a,int p,int w){ code=c; description=d; author=a; page=p; word=w; } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class TestDictionary { public static void main (String[] args) { Product p[]=new Product[5]; p[0]=new Product("002","Japan"); p[1]=new Book("003","USA","David",120); p[2]=new Dictionary("004","Cambodia","Sina",120,2000); p[3]=new Product("005","China"); p[4]=new Book("006","Cambodia","John",100); String report=""; for(int i=0;i<p.length;i++){report=report+"\t"+p[i].toString()+"\n; } System.out.println(report); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 8: Abstract, Interface


1. Abstract:
Advantage of abstract class is allow we use polymorphism form,

Although any classes not the same hierarchy.


Abstract classes : An abstract class is any class with

at least one abstract method. an abstract class can not be used to declare objects any more. Abstract method mean that it is incomplete or method no body.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Syntax:
abstract class ClassName{ . . . abstract return-type MethodName(...); . . . }

Example 1:
Famer

Triangle

Circle

Rectangle 2011

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

//---------- Class Famer ----------------------abstract class Famer { abstract double Area(); } //----------- End of Class Famer -------------

//------------ Class Triangle ------------------public class Triangle extends Famer{ double base; double height; double Area(){return (base*height)/2;} double getBase(){return base;} double getHeight(){return height;} public String toString(){ return "Base:\t"+getBase()+"\tHeight:\t"+getHeight()+"\tAreaTriangle:\t"+Area();} public Triangle(double b,double h) {base=b;height=h; } }
// -------------- End of Class Triangle --------------____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

//------------- Class Circle --------------public class Circle extends Famer{ double radius; void setRadius(double r){radius=r;} double getRadius(){return radius;} double Area(){ return Math.PI*radius*radius; } public String toString(){ return "Radius:"+"\t"+getRadius()+"\t"+"Area Circle:\t"+Area(); } public Circle(double r) { radius=r; } }
//-------------- End of Class Circle -----------------

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

//--------------- Class Rectangle -------------------public class Rectangle extends Famer { double height; double width; void setHeight(double h){height=h;} void setWidth(double w){width=w;} double getHeight(){return height;} double getWidth(){return width;} double Area(){return (height*width); } public String toString(){ return "Height:\t"+height+"Width:\t"+width+"Area Rectangle:\t"+Area(); } public Rectangle(double h,double w) { height=h; width=w; } } // ----------------- End of Rectangle ------------------____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

//--------------- Class TestAbstract -----------------public class TestAbstract{ public static void main(String []args){ Famer f[]=new Famer[3]; f[0]=new Triangle(2.00,4.00); f[1]=new Circle(3.00); f[2]=new Rectangle(3,4); String str=""; for(int i=0;i<f.length;i++){str=str+f[i].toString()+"\n";} System.out.println(str); } } //----------------- End of Class TestAbstract ------------

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 2:
Employee

Full-Time

Part-Time

Commision

abstract class Employee { int id; String name; abstract double getSalary(); abstract double getTax(); abstract double getAmount(); }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class FullTime extends Employee { double salary=0; double tax=0; double getSalary(){return salary;} double getTax(){ if(salary<100) return (salary*10)/100; else return (salary*20)/100; } double getAmount(){ return getSalary()- getTax();} public String toString(){ String str="Full Time :\n"; str=str+"Salary:\t"+getSalary()+"\tTax:\t"+getTax()+"\tAmount:\t"+getAmount(); return str; } public FullTime(){salary=50.0;tax=0.01;} public FullTime(double s,double t) { this.salary=s; this.tax=t; } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950 2011

public class PartTime extends Employee { double hours,rate; public double getSalary(){ return hours*rate; } public double getTax(){ if(getSalary()<100) return (getSalary()*10)/100; else return (getSalary()*20)/100; } public double getAmount(){ return getSalary()-getTax(); } public String toString(){ String str="Part-Time:\n"; str=str+"Hours:\t"+hours+"\tRate:\t"+rate+"\tSalary:\t"+getSalary()+ "\tTax:\t"+getTax()+"\tAmount:\t"+getAmount(); return str; } public PartTime(){hours=100; rate=5; } public PartTime(double h,double r) {hours=h; rate=r; } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class Commision extends Employee { double base,totalsale; double getSalary(){return base+(totalsale*10)/100;} double getTax(){ double tax; if(getSalary()<100) tax=(getSalary()*10)/100; else tax=(getSalary()*20)/100; return tax; } double getAmount(){return getSalary()-getTax(); } public String toString(){ String str="Commision:\n"; str=str+"Base:\t"+base+"\tTotal of Sale:\t"+totalsale+"\tSalary:\t"+getSalary()+ "\tTax:\t"+getTax()+"\tAmount\t"+getAmount(); return str; } public Commision(double b,double s) { base=b; totalsale=s; } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950 2011

public class EmployeeDB { public static void main (String[] args) { IOUtility io=new IOUtility(); int number; String str=""; number=io.getInt("Number of Employee:"); Employee e[]=new Employee[number]; e[0]=new FullTime(120,0.5); e[1]=new PartTime(96,5); e[2]=new Commision(50,500); for(int i=0;i<e.length;i++) str=str+e[i].toString()+"\n"; System.out.println(str); } } -----------Result: -------------3 Full Time : Salary: 120.0 Tax: 24.0 Amount: 96.0 Part-Time: Hours: 96.0 Rate: 5.0 Salary: 480.0 Tax: 96.0 Amount: 384.0 Commision: Base: 50.0 Total of Sale: 500.0 Salary: 100.0 Tax: 20.0 Amount 80.0
____________________________________________________________

Java Programming prepare by Phach Sina Process completed. e-mail:sina_phach@yahoo.com Tel: 092892950

2011

2. Interface: In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants. There are method no bodies. Interfaces cannot be instantiated, they can only be implemented by classes or extended by other interfaces. (Extension is discussed later in this chapter.)

Syntax:
interface InterfaceName{ datatype variable=value; ........................... return-type MethodName(parameter); ........................... }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

How to calling Interface:


class ClassName implements InterfaceName{ ........................... ........................... ........................... }

Example 1 :
public interface Relatable { public int isLargerThan(Object ob); }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class RectanglePlus implements Relatable { public int width = 0; public int height = 0; public RectanglePlus(int w, int h) {width = w; height = h; } public int getArea() { return width * height; } // a method to implement Relatable public int isLargerThan(Object ob) { RectanglePlus otherRect = (RectanglePlus) ob; if (this.getArea() < ob.getArea()) return -1; else if (this.getArea() > otherRect.getArea()) return 1; else return 0; } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example 2 :
interface Mycomparable { boolean Greaterthan(Object ob); boolean Lessthan(Object ob); boolean Equal(Object ob); } class Book implements Mycomparable { private String title; private double price; public void setTitle(String t){title=t;} public void setPrice(double p){price=p;} public boolean Greaterthan(Object ob){ Book b=(Book) ob; if(title.compareTo(b.title)>0)return true; else return false; }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public boolean Lessthan(Object ob){ Book b=(Book) ob; if(price<b.price) return true; else return false; } public boolean Equal(Object ob){ Book b=(Book) ob; if(price==b.price)return true; else return false; } public String toString(){ return title+"\t"+price; } public Book() { title="Java"; price=4.9; } public Book(String t,double p){title=t;price=p;} }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class TestBook { public static void main (String[] args) { String str=""; Book b[]=new Book[5]; b[0]=new Book("Java Pro",14.5); b[1]=new Book("Networ",5.0); b[2]=new Book("Linux",6.0); b[3]=new Book("ASP",10.0); b[4]=new Book("PHP",12.0); for(int i=0;i<b.length-1;i++) for(int j=i+1;j<b.length;j++) if(b[i].Greaterthan(b[j])){ Book t=b[i]; b[i]=b[j]; b[j]=t; } for(int i=0;i<b.length;i++) str=str+b[i].toString()+"\n"; System.out.println(str); } } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 9 :Collections
Introduction to Collections
A collection sometimes called a container is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. All Collection such as:

ArrayList Vector

LinkedList
Hashtable StringBuffered Iterator

ListIterator
Enumeration
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

1. ArrayList
ArrayList is a class that we can store data unlimited size.

Constructor:

ArrayList(); ArrayList(initialize); ArrayList(<Collection e>);

Method:

boolean add(object); //add by series void add(index,object); // add by index E set(index,object); // edit by index E get(index); // get value by index void remove(index); // remove by index
2011

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

Object[] toArray(); // get all data of array Iterator iterator(); // get all data to Iterator class

Example :
import javax.swing.*; public class MyIO { String readString(String m){ return JOptionPane.showInputDialog(m); } int readInt(String m){ return Integer.parseInt(readString(m)); } double readDouble(String m){ return Double.parseDouble(readString(m)); } void ToString(String m){ JTextArea dis=new JTextArea(m); JOptionPane.showMessageDialog(null,dis); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public class Book { String isbn,title; double price; public Book(String isbn,String title,double price) { this.isbn=isbn; this.title=title; this.price=price; } public String toString(){ return isbn+"\t"+title+"\t"+price; } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

import java.util.*; import java.io.*; public class TestArrayList { private ArrayList <Book> list; private MyIO io=new MyIO(); void intput(){ do{ String isbn=io.readString("ISBN:"); String title=io.readString("Title:"); double price=io.readDouble("Price:"); list.add(new Book(isbn,title,price)); }while(io.readString("One more ? yes/no").equalsIgnoreCase("yes")); } /* void output(){ Object []ob=list.toArray(); String result="\n"; for(Object b : ob) result=result+b.toString(); io.ToString(result); } ____________________________________________________________ */ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

void output(){ Iterator iter=list.iterator(); String str="\n"; while(iter.hasNext()){ Book b=(Book)iter.next(); str=str+b.toString(); System.out.println(str); } } void add(){ list.add(1,new Book("aa11","JsP",100)); } void RemovedItem(int n){ list.remove(1); } void EditItem(int n){ list.set(n,new Book("001","Java programmin",100)); } void getItem(int n){ Object b=list.get(n); System.out.println(b.toString()); }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

public TestArrayList() { list=new ArrayList<Book>(); intput(); EditItem(0); //add(); //RemovedItem(1); // getItem(1); output(); } public static void main (String[] args) { new TestArrayList(); }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

2. Vector
Constructor:
- Vector(); - Vector(initialize); - Vector(Collection <e>);

Methods:
- boolean add(object); - void add(index,object); - void addElement(object); - E set(int,object); - E get(int); - object []toArray(); - String toString();
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

- Iterator iterator(); - Enumeration elements(); - void remove(index);

- void remove(object);

Example:
import java.util.*; public class TestVector { public static void main (String[] args) { Vector<String>list=new Vector<String>(); list.add("Dara"); list.add("Sok"); list.add(0,"Thy"); String data=list.get(1); Enumeration e=list.elements(); while(e.hasMoreElements()){ String name=(String)e.nextElement(); System.out.println(name+"\n");} } }

Example2:
import java.util.*; public class VectorBook { public static void main (String[] args) { Vector <Book>list=new Vector<Book>(); list.add(new Book("002","java",12.11)); list.add(0,new Book("003","VB.net",100)); list.set(0,new Book("00","new",10)); Enumeration e=list.elements(); while(e.hasMoreElements()){ String str=e.nextElement()+"\n"; System.out.println(str); } } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

3. String
String is a class that can make string and store string. Syntax: String name; Or String name=new String(); Or String name=new String(Message);

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import java.util.*; public class TestString { public static void main (String[] args) { Vector <String>list=new Vector<String>(); String str1="name1"; String str2=new String(); str2="name2"; String str3=new String("name3"); list.add(str1); list.add(str2); list.add(str3); list.add(0,"to Firt Line"); Enumeration e=list.elements(); while(e.hasMoreElements()){ String report=(String)e.nextElement()+"\n"; System.out.println(report); } } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

4 . StringBuffer
StringBuffer is a class that we use for edit or update string.

Syntax: StringBuffer obj=new StringBuffer(Message); Methods: - append(String); - delete(index,value); // delete by index - insert(index,String);

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import java.util.*; public class TestStringBuffer { public static void main (String[] args) { String sms=new String("Hello"); StringBuffer mydt=new StringBuffer(sms); mydt.append("Sina"); mydt.insert(0,"Vothy"); mydt.delete(0,2); System.out.println(mydt); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

5 . StringTokenizer
StringTokenizer is a class that we use for cut string . Syntax: StringTokenizer mycut=new StringTokenizer(String);

Methods: - hasMoreTokens(); // - nextToken(); // get value - countTokens();


____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import java.util.*; public class TestStringTokenizer { public static void main (String[] args) { String ms=new String("Hello Dara and Vuthy"); StringTokenizer mycut=new StringTokenizer(ms); String []x=new String[mycut.countTokens()]; int i=0; while(mycut.hasMoreTokens()){ String str=mycut.nextToken(); x[i]=str; i++; } for(int j=0;j<x.length;j++) System.out.println(x[j]); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

6 . Hashtable
Constructor:
- Hashtable(); - Hashtable(initialize);

Methods:
- void put(object_key, object_value); - object get(object_key); - object get(object); - Enumeration keys(); - object[] value();

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import java.util.*; public class TestHashtable { public static void main (String[] args) { Hashtable<Integer,String>data=new Hashtable<Integer,String>(); data.put(new Integer(101),"Sina"); data.put(new Integer(102),"Sok"); data.put(new Integer(1),"Seng"); data.put(new Integer(99),"on"); data.put(new Integer(103),"Vuthy"); data.put(new Integer(2000),"chan"); Enumeration e=data.keys(); while(e.hasMoreElements()){ int x=(Integer)e.nextElement(); System.out.println(x+"\t"+data.get(x)+"\n"); } } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 10 :
Toolkit) and Swing.

GUI(Graphic User Interface)

This chapter is study about components of AWT(Abstract Window

Objective : to make interface such as VB of Microsoft.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Syntax:
class ClassName extends JFrame/Frame{ Declaration components; public ClassName(){ setLayoutofComponents; add Components to panel; add panel to Frame; event Components; setSizeofWindow; } public static void main(String []args){ new ClassName(); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example:
import java.awt.*; import java.awt.event.*; public class TestFrame extends Frame { public TestFrame() { setTitle("My Form"); setSize(300,200); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0);}}); setVisible(true); } public static void main (String[] args) { new TestFrame(); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Result:

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example2:
import java.awt.*; import java.awt.event.*; public class TestForm extends Frame{ Panel p; Button btr,btb,btg,bte; public TestForm() { p=new Panel(); p.setLayout(new FlowLayout()); p.add(btr=new Button("Red")); p.add(btb=new Button("Blue")); p.add(btg=new Button("Grean")); p.add(bte=new Button("Exit")); add(p); btr.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ p.setBackground(Color.red); }});
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

btb.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ p.setBackground(Color.blue); } }); btg.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ p.setBackground(Color.green);} }); bte.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){System.exit(0);} }); setSize(800,600); setVisible(true); } public static void main (String[] args) { new TestForm(); }
}
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Result:

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Example3:
import java.util.*; import java.awt.*; import java.awt.event.*; public class TestInsert extends Frame implements ActionListener { TextField tfid,tfname,tfsalary; Button btinsert,btclear,btsort,btexit; TextArea taout; Panel p1,p2,p3,p4,p5; ArrayList <Employee> list=new ArrayList<Employee>();; Employee e; public TestInsert() { p1=new Panel(); p1.setLayout(new GridLayout(3,2)); p1.add(new Label("ID:")); p1.add(tfid=new TextField(12)); p1.add(new Label("Name:"));
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

p1.add(tfname=new TextField(12)); p1.add(new Label("Salary:")); p1.add(tfsalary=new TextField(12)); p2=new Panel(); p2.setLayout(new FlowLayout()); p2.add(btinsert=new Button("Insert")); p2.add(btclear=new Button("Clear")); p2.add(btsort=new Button("Sort")); p2.add(btexit=new Button("Exit")); p3=new Panel(); p3.setLayout(new GridLayout(3,1)); p3.add(p1); p3.add(p2); p3.add(taout=new TextArea()); add(p3); setTitle("Management Employee"); setBounds(450,300,300,300); setVisible(true);
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

btinsert.addActionListener(this); btclear.addActionListener(this); btsort.addActionListener(this); btexit.addActionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent w){ System.exit(0);}}); }
public void actionPerformed(ActionEvent ae){ if(ae.getSource()==btexit){System.exit(0);} else if(ae.getSource()==btinsert){ String id=tfid.getText().trim(); String name=tfname.getText().trim(); double salary=Double.parseDouble(tfsalary.getText().trim()); e=new Employee(id,name,salary); list.add(e); taout.append(e.toString()); } ____________________________________________________________ Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950 2011

else if(ae.getSource()==btclear){ tfid.setText(""); tfname.setText(""); tfsalary.setText(""); } else if(ae.getSource()==btsort){ Object []ee=list.toArray(); Arrays.sort(ee); String str="\n"; for(Object meymey:ee)str=str+meymey.toString(); taout.setText(""); taout.setText(str); } } public static void main (String[] args) { new TestInsert(); } }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Result:

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter11: File IO
This lesson covers the Java platform classes used for basic I/O. It first focuses on I/O Streams, a powerful concept that greatly simplifies I/O operations. The lesson also looks at serialization, which lets a program write whole objects out to streams and read them back again. Then the lesson looks at file I/O and file system operations, including random access files. Most of the classes covered in the I/O Streams section are in the java.io package. Most of the classes covered in the File I/O section are in the java.io.file package.

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

I. FileOutputStream/FileInputStream: 1. FileOutputStream:
The FileOutputStream class is a subclass of OutputStream.

You can construct a FileOutputStream object by passing a string

containing a path name or a File object. You can also specify whether you want to append the output to an existing file. Constructor: FileOutputStream(File filename); FileOutputStrame(String filename); FileOutputStream(File filename,boolean b); FileOutputStream(String filename,boolean b);
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Method: void write(int); void close();

2.FileInputStream:
A FileInputStream obtains input bytes from a file in a file system. What

files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Constructor: FileInputStream(File filename); FileInputStream(String filename);
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Method: int read(); void close(); Example: import java.io.*; classs TestFile{
public static void main(String args[])throws FileNotFoundException, IOException{
FileOutputStream out=new FileOutputStream(mydata.dat); int x[]=new int[10]; for(int i=0;i<10;i++){ x[i]=(int)(1+Math.random()*100); out.write(x[i]); } out.close();
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

FileInputStream in=new FileInputStream(mydata.dat); int a; while((a=in.read())!=-1){ System.out.println(a+\t); } in.close(); } }

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

II. DataOutputStream/DataInputStream: 1. DataOutpuStream:


DataOutputStream and DataInputStream give us the power to write and read primitive data type to a media such as file. Both of this class have the corresponding method to write primitive data and read it back.

Constructor:
DataOutputSteam(new FileOutputStream(...)); DataOutputStream(new FileOutputStream(...),boolean b);

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Method: void writeBoolean(boolean b); void writeInt(int x); void writeFloat(float y); void writeDouble(double x); void writeChar(char c); void writeByte(byte b); void writeLong(long l); 2. DataInputStream: Constructor: DataInputStream(new FileInputStream(...));
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Method: int readInt(); boolean readBoolean(): char readChar(); float readFloat(); long readLong(); double readDouble(); String readString(); byte readByte(); void close(); Example: import java.io.*; class Test{ public static void main(String []args){ try{ DataOutputStream out=new DataOutputStream(new FileOutputStream(mydata.dat));
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

int x=12;

boolean b=true;

String message=hello; double y=20.3; out.writeBoolean(b); out.writeInt(x); out.writeString(message); out.writeDouble(y); out.close(); DataInputStream in=new DataInputStream(new FileInputStream(mydata.dat)); boolean bb=in.readBoolean(); int xx=in.readInt(); double yy=in.readDouble(); long ll=in.readLong(); String str=in.readString(); in.close(); System.out.println(bb+\t+xx+\t+yy+\t+ll+\t+str);

} }
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

III. ObjectOutputStream/ObjectInputStream
1. ObjectOutputStream:
You can use the ObjectOutputStream class to write objects to an underlying stream. In this code example we use it to write objects to a file using the FileOutputStream class as argument to the ObjectOutputStream constructor. The class from which we create objects to write is a simple java class with three attributes, first name, last name and age. The important thing here is that it implements the Serializable interface. Any object that is written on an ObjectOutputStream is serialized and therefore has to implement either the java.io.Serializable interface or the java.io.Externalizable interface.

Constructor:
ObjectOutputStream(new File(...)); ObjectOutputStream(new FileOutputStream(...)); ObjectOutputStream(new File(...),boolean b); ObjectOutputStream(new FileOutputStream(...),boolean b);
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Method:
viod writeObject(Object); void close();

2. ObjectInputStream:
This example shows how to read objects that has been serialized to a file with an ObjectOutputStream. We simply create an instance of ObjectOuputStream and loop for as long as there are objects in the file.

The while condition could be argued since the readObject method will never return null, instead it will throw an EOFException when the end of the file is reached. One could as well write 'while (true)' but as that is not good practice we won't do it here either. This example presumes that the number of objects in the file is unknown and therefore we cannot use a fixed number of iterations in the loop. What this code example does instead is to catch the EOFException and just print out that the end of file is reached. The file contains instances of the class Person and it was used in the corresponding example when an ObjectOutputStream was used to write objects to a file.
____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Constructor:
ObjectInputStream(new File(...)); ObjectInputStream(new FileInputStream(...)); Method: Object readObject(); void close();

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

Chapter 12: Database with Data Source(ODBC)


What Is the JDBC-ODBC Bridge?
The JDBC-ODBC Bridge is a JDBC driver that implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which an ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC.

ODBC Compatibility and ODBC Versions Supported


On Solaris, the JDBC 2.0 bridge must be used with an ODBC 3.x driver manager. The bridge supports both ODBC 2.x and ODBC 3.x drivers, but has been tested with only ODBC 3.x drivers. On NT, the JDBC 2.0 bridge supports the ODBC 2.x and ODBC 3.x driver manager and drivers. The JDBC 2.0 bridge has been tested only with an ODBC 3.x driver manager and with both ODBC 2.x and 3.x drivers. Merant recommends that the JDBC 2.0 bridge be used with version 3.5 or higher of Merant's DataDirect ODBC drivers

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

The Bridge Implementation


The Bridge is implemented in Java and uses Java native methods to call ODBC.

Using the Bridge:


The Bridge is used by opening a JDBC connection using a URL with the

odbc subprotocol. See below for URL examples. Before a connection can be established, the bridge driver class, sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System property named jdbc.drivers, or it must be explicitly loaded using the Java class loader. Explicit loading is done with the following line of code: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

____________________________________________________________

Java Programming prepare by Phach Sina e-mail:sina_phach@yahoo.com Tel: 092892950

2011

You might also like