Java Application Java Application j 301 java public
Java Application程序 案例名称:Java Application程序 程序名称:j 3_01. java public class j 3_01 { public static void main (String args[]) { System. out. println("Hello World!"); }
Java Applet程序 案例名称:调用Java Applet的 程序名称:j 3_02. java HTML程序 import java. awt. Graphics; 程序名称:j 3_03. html import java. applet. Applet; <HTML> public class j 3_02 extends Applet { <applet code=“j 3_02. class” String hw_text ; width=300 height=50> public void init () { </applet> hw_text = "Hello World"; </HTML> } public void paint(Graphics g) { g. draw. String (hw_text , 25) ; } }
Java Applet程序 n 用JDK自带的命令行 具appletviewer打开HTML文件,语 法是“appletviewer j 3_03. html”,将j 3_03. html文件拷贝到 C盘根目录
关键字 n 所有Java关键字都是小写的,TURE、FALSE、NULL等都不是Java关键字;goto和 const 虽然从未使用,但也作被为Java关键字保留;true、false、null虽用做专门用途, 但不是Java关键字。Java语言的关键字包括 9大类: n n n n n 1、原始数据类型:byte、short、int、long、float、double、char、 boolean 2、循环关键字:do、while、for、break、continue 3、分支关键字:if、else、switch、case、default、break 4、方法、变量和类修饰符:private、public、protected、final、static、 abstract、synchronized、volatile、strictfp 5、异常处理:try、catch、finally、throws 6、对象相关关键字:new、extends、implements、class、 instanceof、this、super 7、字面值常量:false、true、null 8、方法相关关键字:return、void 9、包相关关键字:package、import
Java浮点类型 类型 float 占用存储空间 4字� 表数范围 -3. 403 E 38~3. 403 E 38 - double 8字� 1. 798 E 308~1. 798 E 308
基本数据类型的使用 案例名称:基本数据类型的使用 程序名称:j 3_04. java public class j 3_04 { public static void main (String args []) { boolean b = true; //声明boolean型变量并赋值 int x, y=8; // 声明int型变量 float f = 4. 5 f; // 声明float型变量并赋值 double d = 3. 1415; //声明double型变量并赋值 char c; //声明char型变量 c = 'u 0031'; //为char型变量赋值 x = 12; //为int型变量赋值 System. out. print(c + "n"); char z = '中'; System. out. print(z); } }
数组的使用 案例名称:数组的使用 程序名称:j 3_05. java public class j 3_05{ public static void main(String args[]){ int[] s; s = new int[10]; for ( int i=0; i<10; i++ ) { s[i] =2*i+1; System. out. println(s[i]); } } }
默认初始化的使用 案例名称:默认初始化的使用 程序名称:j 3_06. java public class j 3_06{ public static void main(String argv[]){ int a[]= new int[5]; System. out. println(a[3]); } }
使用String提供的方法 n n n n 案例名称:使用String提供的方法 程序名称:j 3_07. java public class j 3_07{ public static void main(String argv[]){ String str = "abcdefg"; System. out. print(str. char. At(2)); //返回字符串中下标为 2的字符 System. out. print(str. substring(1, 2)); //从下标1开始到 2截取 字符串 System. out. print(str. index. Of(“bc”)); //返回字符串中bc首次出 现的位置 if ( str. equals(“abcdefg”)){//判断str对象中字符串与参数字符 串是否相等 System. out. print("相等n"); } } }
使用自定义的类 案例名称:使用自定义的类 程序名称:j 3_08. java public class j 3_08 { private int day = 12; private int month = 6; private int year = 1900; public j 3_08(int d, int m, int y) { year = y; month = m; day = d; } public void display() { System. out. print(year + " / " + month + " / " +day); } public static void main(String[] args) { j 3_08 m; m = new j 3_08(22, 9, 2005); m. display(); } }
逻辑运算符用法 a b !a a&b a|b a^b a&&b a||b true true false true true false false true false false
Instanceof 运算符 案例名称:Instanceof 运算符 程序名称:j 3_09. java class Instance. Of. Demo { public static void main (String args []) { Instance. Of. Demo t = new Instance. Of. Demo( ); if (t instanceof Instance. Of. Demo) { System. out. println ("T是Instance. Of. Demo 的实例"); } else { System. out. println ("T不是Instance. Of. Demo 的实例!"); } } }
使用构造函数 class My. Class { private int day; private int month; private int year; public My. Class(){ day = 1; month = 1; year = 1900; } public My. Class(int d, int m, int y){ day = d; month = m; year = y; } public void display(){ System. out. println(day + "-" + month + "-" + year); } public static void main(String args[]){ My. Class m 1 = new My. Class(); My. Class m 2 = new My. Class(25, 12, 2005); m 1. display(); m 2. display(); } }
使用包 案例名称:使用包 程序名称:j 3_12. java package com. sun; class hello { public static void main (String args[]) { System. out. println("Hello World!"); }
类的继承 import java. util. *; class Person { public String name; public int age; public Date birth. Date; public String get. Info() { return "name: " + name + "nage: " + age ; } } class Student extends Person{ public String school; } class Test{ public static void main(String args[]){ Student s = new Student(); s. name = "bily"; s. age = 18; System. out. println(s. get. Info()); } }
方法的重写 class Person { protected String name; protected int age; public String get. Info() { return "Name: "+ name + "n" +"age: "+ age; } } class Student extends Person { protected String school; public String get. Info() { return "name: "+ name + "nage: "+ age + "nschool: "+ school; } } class Test{ public static void main(String args[]){ Person p = new Person(); p. name = "Tom"; p. age = 22; System. out. println(p. get. Info()); Student s = new Student(); s. name = "bily"; s. age = 18; s. school = "Tsinghua university"; System. out. println(s. get. Info()); } } 案例名称:方法的重写 程序名称:j 3_14. java
方法的重写 案例名称:方法的重写 程序名称:j 3_15. java class A{ int value = 3; int get. Value(){return value; } } class B extends A{ int value = 6; int get. Value() {return value; } int get. Value 2(){return super. value; } int get. Value 3(){return get. Value(); } int get. Value 4(){return super. get. Value(); } } class Test{ public static void main(String args[]){ B b = new B(); System. out. println(b. get. Value()); System. out. println(b. get. Value 2()); System. out. println(b. get. Value 3()); System. out. println(b. get. Value 4()); } }
关键字static 案例名称:使用static关键字 程序名称:j 3_16. java class Person { private int id; public static int total = 0; public Person() { total++; id = total; } } class Other. Class { public static void main(String args[]) { Person. total = 100; System. out. println(Person. total); Person c = new Person(); System. out. println(Person. total); } }
使用静态方法 案例名称:使用静态方法 程序名称:j 3_17. java class Person { private int id; private static int total = 0; public static int get. Total. Person() { return total; } public Person() { total++; id = total; } } class Test. Person { public static void main(String[] args) { System. out. println(Person. get. Total. Person()); Person p 1 = new Person(); System. out. println(Person. get. Total. Person()); } }
使用final关键字 案例名称:使用final关键字 程序名称:j 3_18. java final class Test{ public static int total. Number= 5 ; public final int id; public Test(){ id = ++total. Number; } public static void main(String[] args) { final Test t = new Test(); final int i = 10; final int j; j = 20; j = 30; //非法,对final变量进行二次赋值 } }
使用抽象类 案例名称:使用抽象类 程序名称:j 3_19. java abstract class A{ abstract void m 1( ); public void m 2( ){ System. out. println("A类中定义的m 2方法"); } } class B extends A{ void m 1( ){ System. out. println("B类中定义的m 1方法"); } } class Test{ public static void main( String args[ ] ){ A c = new B( ); c. m 1( ); c. m 2( ); } }
接口 n 定义接口的语法格式 如下。 <modifer> interface <interface_name> { [<attribute_declarations>] [<abstrct method_declarations>] } 案例名称:使用接口实现多重继承 程序名称:j 3_20. java
向量Vector n 不要求每个元 素的类型相同, 向量中可以混 合多种数据类 型。向量可以 在增加元素时 动态增大。 案例名称:使用向量 程序名称:j 3_21. java import java. util. *; class Test { public static void main(String args[]) { String names[] = {"Mercury", "Venus", "Earth", "Mars"}; int names. Len = names. length; Vector planets = new Vector(); for(int i=0; i<names. Len; i++){ planets. add. Element(names[i]); } int planets. Len = planets. size(); for(int i=0; i<planets. Len; i++){ System. out. println(planets. element. At(i)); } } }
枚举Enumeration n 枚举也可以存放许多元素,两个常用的方法为, has. More. Elements()和next. Element() 案例名称:使用枚举 程序名称:j 3_22. java import java. util. *; class Test { public static void main(String args[]) { String names[] = {"Mercury", "Venus", "Earth", "Mars"}; int names. Len = names. length; Vector planets = new Vector(); for(int i=0; i<names. Len; i++){ planets. add. Element(names[i]); } Enumeration enum = planets. elements(); //返回enum对象中的值 String name = null; while(enum. has. More. Elements()) { name = (String)enum. next. Element(); System. out. println(name); } } }
使用散列表 n n n n n n 案例名称:使用散列表 程序名称:j 3_23. java import java. util. *; class Test { public static void main(String args[]) { String names[] = {"beijing", "shanghai", "nanchang", "sichuan"}; String person[] = {"北方", "南部沿海", "中部", "西部"}; Hashtable hash = new Hashtable(); for(int i=0; i<names. length; i++){ hash. put(names[i], person[i]); } Enumeration enum = hash. keys(); //返回hash对象中关键字的值 Object obj; while(enum. has. More. Elements()){ obj = enum. next. Element(); System. out. println(obj + ": " +hash. get(obj)); } } }
Set接口 n 一种不含重复元素的、无序的收集,也称集合,是数学集合的抽象模型。Set 集合接口中的元素不重复,且至多包含一个null元素。 案例名称:使用Set接口 程序名称:j 3_24. java import java. util. *; class Test. Set { public static void main(String[] args) { Hash. Set h = new Hash. Set(); h. add("1 st"); h. add("2 nd"); h. add(new Integer(3)); h. add(new Double(4. 0)); h. add("2 nd"); // 重复元素, 未被加入 h. add(new Integer(3)); // 重复元素, 未被加入 m 1(h); } public static void m 1(Set s){ System. out. println(s); } }
使用List接口 n n n n n 案例名称:使用List接口 程序名称:j 3_25. java import java. util. *; class Test. List{ public static void main(String[] args) { Array. List h = new Array. List(); h. add("1 st"); h. add("2 nd"); h. add(new Integer(3)); h. add(new Double(4. 0)); h. add("2 nd"); // 重复元素, 加入 h. add(new Integer(3)); // 重复元素, 加入 m 1(h); } public static void m 1(List s){ System. out. println(s); } }
Iterator接口 n 可以通过Collection接口中定义的iterator()方法获得一个对应的 Iterator对象。Set对象对应的Iterator仍然是无序的 案例名称:使用Iterator接口 程序名称:j 3_26. java import java. util. *; class Test. Iterator { public static void main(String[] args) { Array. List h = new Array. List(); h. add("1 st"); h. add("2 nd"); h. add(new Integer(3)); h. add(new Double(4. 0)); Iterator it = h. iterator(); while ( it. has. Next() ) { System. out. println(it. next()); } } }
数组下标越界异常 案例名称:数组下标越界异常 程序名称:j 3_27. java class Test{ public static void main(String[] args) { String friends[]={"lisa", "bily", "kessy"}; for(int i=0; i<5; i++) { System. out. println(friends[i]); } System. out. println("nthis is the end"); } }
捕捉异常 案例名称:捕捉异常 程序名称:j 3_28. java class Test{ public static void main(String[] args){ try{ String friends[]={"lisa", "bily", "kessy"}; for(int i=0; i<5; i++) { System. out. println(friends[i]); } }catch (Exception e) { System. out. println(e); }finally { System. out. println(" It's ok!"); } System. out. println(" Out of Try!"); } }
声明抛出异常 案例名称:声明抛出异常 程序名称:j 3_29. java import java. io. *; class Test{ public static void main(String[] args){ Test t = new Test (); try{ t. read. File(); }catch(IOException e){ System. out. println(e); System. out. println("退出!"); } } public void read. File()throws IOException { File. Input. Stream in=new File. Input. Stream("myfile. txt"); int b; b = in. read(); while(b!= -1) { System. out. print((char)b); b = in. read(); } in. close(); } }
声明抛出异常 案例名称:声明抛出异常 程序名称:j 3_30. java class My. Exception extends Exception { private int idnumber; public My. Exception(String message, int id) { super(message); this. idnumber = id; } public int get. Id() { return idnumber; } } class Test{ public void regist(int num) throws My. Exception { if (num < 0) { throw new My. Exception("人数为负值,不合理", 3); } System. out. println("登记人数"+ num); } public void manager() { try { regist(-100); } catch (My. Exception e) { System. out. print("登记失败,出错种类:"+e. get. Id()); } System. out. print("本次登记操作结束"); } public static void main(String args[]){ Test t = new Test(); t. manager(); } }
标准的IO操作 案例名称:标准的IO操作 程序名称:j 3_31. java import java. io. *; class Test{ public static void main (String args[]) { String s; // 创建一个Buffered. Reader对象从键盘逐行读入数据 Input. Stream. Reader isr = new Input. Stream. Reader (System. in); Buffered. Reader br = new Buffered. Reader(isr); try {// 每读入一行后向显示器输出 s = br. read. Line(); while (!s. equals("")) { System. out. println("Read: " + s); s = br. read. Line(); } br. close(); // 关闭输入流 } catch (IOException e) { // 捕获可能的IOException. e. print. Stack. Trace(); } } }
读取文件 n n n n n n 案例名称:读取文件 程序名称:j 3_32. java import java. io. *; class Read. File { public static void main (String[] args) { String fname = "j 3_32. java"; File f = new File(fname); try { File. Reader fr = new File. Reader(f); Buffered. Reader br = new Buffered. Reader(fr); String s = br. read. Line(); while ( s != null ) { System. out. println("读入: " + s); s = br. read. Line(); } br. close(); // 关闭缓冲读入流及文件读入流的连接. } catch (File. Not. Found. Exception e 1) { System. err. println("File not found: " + fname); } catch (IOException e 2) { e 2. print. Stack. Trace(); } } }
写入文件 案例名称:写入文件 程序名称:j 3_33. java import java. io. *; class Write. File { public static void main (String[] args) { File file = new File("tt. txt"); try { Input. Stream. Reader is = new Input. Stream. Reader (System. in); Buffered. Reader in=new Buffered. Reader(is); File. Writer fw = new File. Writer(file); Print. Writer out = new Print. Writer(fw); String s = in. read. Line(); // 从键盘逐行读入数据输出到文件 while (!s. equals("")) { out. println(s); s = in. read. Line(); } in. close(); // 关闭Buffered. Reader输入流. out. close(); // 关闭连接文件的Print. Writer输出流. }catch (IOException e) { System. out. println(e); } } }
URL编程 n URL(统一资源定位器,Uniform Resource Locator)用于表示 Internet上资源的地址。这里所说的资源,可以是文件、目录或 更为复杂的对象的引用。java. net包定义了对应的URL类。其常用 构造方法及用法举例如下: n n n n public URL(String spec); 比如:URL u 1 = new URL("http: //home. netscape. com/home/"); public URL(URL context, String spec); 比如:URL u 2 = new URL(u 1, "welcome. html"); public URL(String protocol, String host, String file); 比如:URL u 3 = new URL("http", "www. sun. com", "index. html"); public URL (String protocol, String host, int port, String file); 比如:URL u 4 = new URL("http", "www. sun. com", 80, "index. html");
写入文件 案例名称:写入文件 程序名称:j 3_34. java import java. io. *; import java. net. *; class URLReader{ public static void main(String args[]){ try{ URL tirc = new URL("http: //www. tsinghua. edu. cn/"); Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(tirc. open. Stream())); String s; while((s = in. read. Line())!=null) System. out. println(s); in. close(); }catch(Malformed. URLException e) { System. out. println(e); }catch(IOException e){ System. out. println(e); } } }
Socket通信模型
java. net包 n java. net包中定义了两个类Socket和 Server. Socket,分别用来表示双向连接的客户 端和服务器端。其常用的构造方法有: n n n Socket(Inet. Address address, int port); Socket(Inet. Address address, int port, boolean stream); Socket(String host, int port, boolean stream); Server. Socket(int port, int count);
服务器端程序 案例名称:服务器端程序 程序名称:j 3_35. java import java. net. *; import java. io. *; class Test. Server { public static void main(String args[]) { try { Server. Socket s = new Server. Socket(8888); while (true) { Socket s 1 = s. accept(); Output. Stream os = s 1. get. Output. Stream(); Data. Output. Stream dos =new Data. Output. Stream(os); dos. write. UTF("Hello, " +s 1. get. Inet. Address() + "port#" + s 1. get. Port() + "nbye!"); dos. close(); s 1. close(); } }catch (IOException e) { System. out. println("程序运行出错: " + e); } } }
客户器端程序 案例名称:客户器端程序 程序名称:j 3_36. java import java. net. *; import java. io. *; class Test. Client { public static void main(String args[]) { try { Socket s 1 = new Socket("127. 0. 0. 1", 8888); Input. Stream is = s 1. get. Input. Stream(); Data. Input. Stream dis = new Data. Input. Stream(is); System. out. println(dis. read. UTF()); dis. close(); s 1. close(); } catch (Connect. Exception conn. Exc) { System. err. println("服务器连接失败!"); } catch (IOException e) { } } }
线程的创建和使用 案例名称:线程的创建和使用 程序名称:j 3_37. java class Test. Thread 1 { public static void main(String args[]) { Runner 1 r = new Runner 1(); Thread t = new Thread(r); t. start(); } } class Runner 1 implements Runnable { public void run() { for(int i=0; i<30; i++) { System. out. println("No. " + i); } } }
多线程 案例名称:多线程 程序名称:j 3_38. java class Test. Thread 2 { public static void main(String args[]) { Runner 2 r = new Runner 2(); Thread t 1 = new Thread(r); Thread t 2 = new Thread(r); t 1. start(); t 2. start(); } } class Runner 2 implements Runnable { public void run() { for(int i=0; i<20; i++) { String s = Thread. current. Thread(). get. Name(); System. out. println(s + ": " + i); } } }
创建线程的第二种方式 案例名称:多线程 程序名称:j 3_39. java class Test. Thread 3 { public static void main(String args[]){ Thread t = new Runner 3(); t. start(); } } class Runner 3 extends Thread { public void run() { for(int i=0; i<30; i++) { System. out. println("No. " + i); } } }
线程状态的转换 案例名称:线程状态的转换 程序名称:j 3_40. java class Test. Thread 3{ public static void main(String args[]) { Runner 3 r = new Runner 3(); Thread t = new Thread(r); t. start(); } } class Runner 3 implements Runnable { public void run() { for(int i=0; i<30; i++) { if(i%10==0 && i!=0) { try{ Thread. sleep(2000); }catch(Interrupted. Exception e){} } System. out. println("No. " + i); } } }
使用AWT编程 案例名称:使用AWT编程 程序名称:j 3_41. java import java. awt. *; class Test. Frame { public static void main( String args[]) { Frame f = new Frame("My First Test"); f. set. Size( 170, 100); f. set. Background( Color. blue); f. set. Visible( true); } }
Swing编程基础 案例名称:使用Swing编程 程序名称:j 3_42. java import java. awt. *; import java. awt. event. *; import javax. swing. *; class Hello. World. JFC extends JComponent { public void paint(Graphics g){ g. set. Color(Color. black); g. draw. String ("Hello. World", 20, 15); } public static void main(String args[]){ JFrame my. Frame = new JFrame("Hello World!"); Hello. World. JFC jt = new Hello. World. JFC(); my. Frame. get. Content. Pane(). add("Center", jt); my. Frame. set. Size(100, 50); my. Frame. set. Visible(true); } }
Applet编程基础 案例名称:给Applet传递参数 程序名称:j 3_43. java import java. awt. Graphics; import java. applet. Applet; public class j 3_43 extends Applet { String topic = "abcdefg" ; public void init () { topic = get. Parameter("topic"); } public void paint(Graphics g) { g. draw. String (topic, 25) ; } }
给Applet传递参数 案例名称:给Applet传递参数 程序名称:j 3_44. html <html> <applet code="j 3_43. class" width=300 height=300> <param name=topic value="Computer Science" /> <param name=var 2 value="456" /> </applet> </html>
- Slides: 105