Java Programming
Java Programming
Chapter 1: Introduction
Objective:
Introduction about java and model application structure of java application for edit, compile and run java.
____________________________________________________________
2011
Java Overview:
Java object oriented programming 100% that development by Sun Microsoft System company.
____________________________________________________________
2011
companion text)
____________________________________________________________
2011
____________________________________________________________
2011
Jdk1.6.0
____________________________________________________________
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
____________________________________________________________
2011
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
____________________________________________________________
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]
____________________________________________________________
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
____________________________________________________________
2011
Structure
import PackageName.*; class ClassName{ public static void main(String []args){ statement1; statement2; . . statementn; } }
____________________________________________________________
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);
} }
____________________________________________________________
2011
: 32 bit long : 64 bit short : 16 bit byte : 8 bit double : 64 bit float : 32 bit
point number : ( ex: 12.22)
____________________________________________________________
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
____________________________________________________________
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.
____________________________________________________________
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
____________________________________________________________
____________________________________________________________
2011
Chapter 3: Operator
Algorithm : + , - , * , / , % ,... o Cooperation : > , < , >= , <= ,... o Relation : && , || , ! , != , == Example:
o
____________________________________________________________
2011
____________________________________________________________
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); }}
____________________________________________________________
2011
Assign Operator
____________________________________________________________
2011
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); } }
____________________________________________________________
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 }
____________________________________________________________
2011
2011
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:"));
____________________________________________________________
2011
if(a>b){
____________________________________________________________
2011
____________________________________________________________
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.
____________________________________________________________
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(); } }
____________________________________________________________
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.
____________________________________________________________
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 }
____________________________________________________________
2011
Example:
public class hello { static int i=0; public static void main (String[] args) { while(i<=5){ System.out.println(i+"\n"); i++; } } }
____________________________________________________________
2011
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); } }
____________________________________________________________
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(); } }
____________________________________________________________
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.
____________________________________________________________
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(); } }
____________________________________________________________
2011
Syntax 1:
class ClassName{ type instance-variable1; type instance-variable2; type method1(.....){ ....} type method2(.....){.....} //........ }
____________________________________________________________
2011
Syntax 2:
Class ClassName{ constructor1; constructor2; . . . datafield1; datafield2; method1; method1; }
____________________________________________________________
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()); } }
____________________________________________________________
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; }
____________________________________________________________
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()); } }
____________________________________________________________
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.
____________________________________________________________
2011
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;}
____________________________________________________________
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); }}
____________________________________________________________
____________________________________________________________
2011
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
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); } }
____________________________________________________________
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; }
____________________________________________________________
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() {
}
____________________________________________________________
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
____________________________________________________________
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).
____________________________________________________________
2011
This picture is want to show about Employee class is a derived class that extended from the Person class.
Person: (name,sex)
2011
Example 1:
class A{ .... public A(){ .......... } } class B extends A{ .... public B(){ .... } }
____________________________________________________________
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; } }
____________________________________________________________
2011
2011
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()); } }
____________________________________________________________
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(); }
____________________________________________________________
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:............
____________________________________________________________
2011
Chapter 7: Polimorphism
Group of object reference to other class in the same
Book
Dictionary
____________________________________________________________
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; }
____________________________________________________________
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); } }
____________________________________________________________
2011
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.
____________________________________________________________
2011
Syntax:
abstract class ClassName{ . . . abstract return-type MethodName(...); . . . }
Example 1:
Famer
Triangle
Circle
Rectangle 2011
____________________________________________________________
//---------- 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 --------------____________________________________________________________
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 -----------------
____________________________________________________________
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 ------------------____________________________________________________________
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 ------------
____________________________________________________________
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(); }
____________________________________________________________
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; } }
____________________________________________________________
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); ........................... }
____________________________________________________________
2011
Example 1 :
public interface Relatable { public int isLargerThan(Object ob); }
____________________________________________________________
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; } }
____________________________________________________________
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; }
____________________________________________________________
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;} }
____________________________________________________________
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
____________________________________________________________
2011
1. ArrayList
ArrayList is a class that we can store data unlimited size.
Constructor:
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
____________________________________________________________
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); } }
____________________________________________________________
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; } }
____________________________________________________________
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()); }
____________________________________________________________
2011
public TestArrayList() { list=new ArrayList<Book>(); intput(); EditItem(0); //add(); //RemovedItem(1); // getItem(1); output(); } public static void main (String[] args) { new TestArrayList(); }
____________________________________________________________
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();
____________________________________________________________
2011
- 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); } } }
____________________________________________________________
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);
____________________________________________________________
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); } } }
____________________________________________________________
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);
____________________________________________________________
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); } }
____________________________________________________________
2011
5 . StringTokenizer
StringTokenizer is a class that we use for cut string . Syntax: StringTokenizer mycut=new StringTokenizer(String);
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]); } }
____________________________________________________________
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();
____________________________________________________________
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"); } } }
____________________________________________________________
2011
Chapter 10 :
Toolkit) and Swing.
____________________________________________________________
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(); } }
____________________________________________________________
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(); } }
____________________________________________________________
2011
Result:
____________________________________________________________
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); }});
____________________________________________________________
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(); }
}
____________________________________________________________
2011
Result:
____________________________________________________________
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:"));
____________________________________________________________
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);
____________________________________________________________
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(); } }
____________________________________________________________
2011
Result:
____________________________________________________________
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.
____________________________________________________________
2011
I. FileOutputStream/FileInputStream: 1. FileOutputStream:
The FileOutputStream class is a subclass of OutputStream.
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);
____________________________________________________________
2011
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);
____________________________________________________________
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();
____________________________________________________________
2011
____________________________________________________________
2011
Constructor:
DataOutputSteam(new FileOutputStream(...)); DataOutputStream(new FileOutputStream(...),boolean b);
____________________________________________________________
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(...));
____________________________________________________________
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));
____________________________________________________________
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);
} }
____________________________________________________________
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);
____________________________________________________________
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.
____________________________________________________________
2011
Constructor:
ObjectInputStream(new File(...)); ObjectInputStream(new FileInputStream(...)); Method: Object readObject(); void close();
____________________________________________________________
2011
____________________________________________________________
2011
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");
____________________________________________________________
2011