java吧 关注:1,241,706贴子:12,713,287

Java 不完全教程

只看楼主收藏回复


第一章Java预备知识
常用DOS命令
help,dir,md,cd,rd,del,copy,move,start,type,cls,attrib
配置环境变量
JAVA_HOME C:\soft\Java\jdk1.6.0_37
Path %JAVA_HOME%\bin
第一个程序
public class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}
Java三种注释
文档注释 /***/
多行注释 /**/
单行注释 //
启动记事本程序 - DEMO
public static void main(String[] args) throws IOException {
Runtime.getRuntime().exec("notepad");
}


IP属地:北京1楼2013-03-01 08:44回复


    2楼2013-03-01 08:44
    收起回复

      第二章 Java基本语法
      Java常量 - 固定不变值
      Java变量 - 在内存中分配一块内存,用于保存数据
      空:      null
      基本数据类型
      布尔值:  boolean
      字符:    char
      整形:    byte,short,int,long
      浮点型:  float,double
      引用数据类型
      类:      String
      数组:    int[]
      类型转换
      自动转换 - 低字节类型数据和高字节类型数据参与运算会自动提升类型
      强制转换 - 将高字节数据强制转换成低字节数据,会丢失精度或者结果错误


      IP属地:北京3楼2013-03-01 08:45
      回复

        第三章 运算符与逻辑判断循环
        算数运算符 + - * / % ++ --
        赋值运算符 = += -= *= /= %=
        比较运算符 == != < > <= >= instanceof
        逻辑运算符 & | ^ ! && ||
        位运算符 & | ^ << >> >>>
        三元运算符 boolean?"":"";
        选择结构 if…else switch
        循环结构 for while do…while
        控制循环 continue break return
        在不知道x和y值的情况下,交换这个两个变量中的值
        int x=10, y=6; x+=y; y-=x; x+=y; y*=(-1); System.out.println(x+" "+y);
        int a=10, b=6; a+=b; b=a-b; a-=b; System.out.println(a+" "+b);
        int i=10, j=6; i^=j; j=i^j; i^=j; System.out.println(i+" "+j);
        在三个数中找到最大的那个数
        int x=10,y=20,z=30;
        int max = x>y?(x>z?x:z):(y>z?y:z);
        System.out.println(max);
        计算1+2+3+…+100的和
        int sum=0,i=0;
        for(;i<=100;sum+=i++);
        System.out.println(sum);
        sum=0;i=0;
        while(i<=100)sum+=i++;
        System.out.println(sum);
        sum=0;i=0;
        do{sum+=i++;}while(i<=100);
        System.out.println(sum);
        public static int sum = sum(100);
        public static int sum(int num) {return num==1?1:num+sum(num-1);}
        将十进制转换成二进制
        StringBuilder sb = new StringBuilder();
        System.out.println("请输入一个10进制数: ");
        int num = new Scanner(System.in).nextInt();
        while (num>0) {
        sb.append(num%2);
        num/=2;
        }
        sb.reverse();
        System.out.println(sb);


        IP属地:北京4楼2013-03-01 08:45
        回复

          第四章 函数和数组
          函数 - 代码在程序中需要多次使用,就可以定义成函数,在需要使用的时候调用
          函数的重载 - 函数名称相同,参数列表不同,返回值不同
          数组 - 类型一致长度不可变通过索引操作元素的容器
          数组相关函数
          Arrays.toString() 数组转换成字符串
          System.arraycopy() 数组深拷贝
          将数组中所有元素打印成一行并以逗号分割
          private static String arrayToString(int[] array) {
          if (array!=null && array.length>0) {
          String s = array[0]+"";
          for (int i = 1; i < array.length; i++) {
          s+=", "+array[i];
          }
          return s;
          }
          return "";
          }
          对数组进行排序 – 冒泡/选择
          private static int[] bubbleSort(int[] array) {
          int temp = 0;
          for (int i = 0; i < array.length-1; i++) {
          for (int j = i; 0 < j+1; j--) {
          if (array[j]<array[j+1]) {
          temp = array[j];
          array[j] = array[j+1];
          array[j+1] = temp;
          }
          }
          }
          return array;
          }
          private static int[] selectSort(int[] array) {
          int temp = 0;
          for (int i = 0; i < array.length-1; i++) {
          for (int j = i+1; j < array.length; j++) {
          if (array[i]<array[j]) {
          temp = array[i];
          array[i] = array[j];
          array[j] = temp;
          }
          }
          }
          return array;
          }
          对有序数组进行二分查找
          private static int binarySearch(int[] array, int key) {
          int start = 0;
          int end = array.length - 1;
          while (start <= end) {
          int middle = (start+end)/2;
          if (key > array[middle]) {
          start = middle + 1;
          }else if (key < array[middle]) {
          end = middle - 1;
          }else {
          return middle;
          }
          }
          return -1;
          }
          获取键盘输入的最大数
          public static void main(String[] args) throws Exception {
          int number = 0;
          System.out.println("请输入三个数字: ");
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          for (int i = 0; i < 3; i++) {
          int line = Integer.parseInt(br.readLine());
          number = line>number?line:number;
          }
          System.out.println(number);
          }
          递归求1+2+...
          public static int getSum(int n) {
          return n==1?1:getSum(n-1)+n;
          }


          IP属地:北京5楼2013-03-01 08:45
          回复

            第五章 面向对象
            封装 – 对内部变量私有化,对外部提供公有方法
            代码块 - 在创建对象时代码块会自动运行
            构造函数 – 函数名与类名相同没有返回值类型
            this - 那个对象调用该方法,this就代表那个对象
            static - 内存中对象是唯一的
            extends - 子类继承父类的方法和属性
            super - 子类调用父类的方法和属性
            向上转型 - 子类当做父类使用,不能调用子类特有的方法
            向下转型 - 子类当做父类使用,需要调用子类特有的方法,需要将父类强制转化成子类
            方法重写 - 子类必须与父类具有相同函数名,参数列表和返回值
            多态 – 将函数的形参定义为父类类型,传入不同的子类而实现不同的功能
            abstract – 父类定义抽象方法,需要在子类实现该方法
            final – 对象不能继承,方法不能重写,变量不能修改
            interface – 接口中所有的方法都需要在子类中实现
            implements – 一个类实现接口
            内部类 – 在一个类中嵌套另一个类
            package – 定义类所属的包
            import – 导入包中的类
            定义对象
            public class Person {
            private String name;
            private Integer age;
            }
            创建对象
            public static void main(String[] args) {
            Person p = new Person();
            }


            IP属地:北京6楼2013-03-01 08:47
            回复

              模拟电脑开/关机
              public class ComputerDemo {
              private static class Computer {
              private String name;
              private MainBoard mainBoard;
              private Boolean state;
              public Computer(){}
              public Computer(String name, MainBoard mainBoard) {
              this.name = name;
              this.mainBoard = mainBoard;
              this.state = false;
              }
              public void trunOn(){
              if(mainBoard==null){
              System.out.println(name+" 没有安装主板不能开机");
              }else{
              if (state) {
              return;
              }
              mainBoard.run();
              System.out.println(name+" 开机成功");
              state = true;
              }
              }
              public void trunOff(){
              if (state) {
              mainBoard.stop();
              System.out.println(name+" 关机成功");
              state = false;
              }else {
              System.out.println("电脑还没有开机");
              }
              }
              }
              private static class MainBoard {
              private String name;
              public MainBoard(){}
              public MainBoard(String name) {
              this.name = name;
              }
              public void run(){
              System.out.println(name+" 已启动");
              }
              public void stop() {
              System.out.println(name+" 停止运行");
              }
              }
              public static void main(String[] args) {
              Computer c = new Computer("ThinkPad T420", new MainBoard("华硕主板"));
              c.trunOn();
              c.trunOff();
              }
              }


              IP属地:北京7楼2013-03-01 08:47
              回复
                感觉就是生硬的 写 demo 没一点 自己 独特的东西


                IP属地:北京8楼2013-03-01 08:47
                回复
                  new Demo2().test();
                  }
                  }
                  装饰模式 - 对某个对象功能进行增强
                  public class Wrapper {
                  private interface Person {
                  void run();
                  void eat();
                  void sleep();
                  }
                  private static class Man implements Person {
                  public void run() {
                  System.out.print("男人跑步!");
                  }
                  public void eat() {
                  System.out.print("男人吃饭!");
                  }
                  public void sleep() {
                  System.out.print("男人睡觉!");
                  }
                  }
                  private static class SuperMan implements Person {
                  private Man man;
                  public SuperMan(Man man) {
                  this.man = man;
                  }
                  public void run() {
                  man.run();
                  System.out.println("健步如飞!");
                  }
                  public void eat() {
                  man.eat();
                  System.out.println("狼吞虎咽!");
                  }
                  public void sleep() {
                  man.sleep();
                  System.out.println("鼾声如雷!");
                  }
                  }
                  public static void main(String[] args) {
                  Person person = new SuperMan(new Man());
                  person.run();
                  person.eat();
                  person.sleep();
                  }
                  }
                  适配器模式
                  public class Adapter {
                  public interface A {
                  void a();
                  void b();
                  }
                  public abstract static class B implements A {
                  public void a() {}
                  public void b() {}
                  }
                  public static void main(String[] args) {
                  B b = new B(){
                  public void a() {
                  System.out.println("Adapter");
                  }
                  };
                  b.a();
                  }
                  }


                  IP属地:北京12楼2013-03-01 08:48
                  回复
                    顶啊~


                    IP属地:四川13楼2013-03-01 08:49
                    回复
                      ----------------------------->顶


                      IP属地:广东14楼2013-03-01 08:50
                      回复

                        线程间的通信 – 同步代码块
                        public class Notify {
                        private static class Printer {
                        private boolean flag = false;
                        public synchronized void print1() {
                        while (flag) {
                        try {
                        this.wait();
                        } catch (InterruptedException e) {
                        throw new RuntimeException(e.getMessage(),e);
                        }
                        }
                        System.out.println("好好学习!");
                        flag = true;
                        this.notify();
                        }
                        public synchronized void print2() {
                        while (!flag) {
                        try {
                        this.wait();
                        } catch (InterruptedException e) {
                        throw new RuntimeException(e.getMessage(),e);
                        }
                        }
                        System.out.println("天天向上!");
                        flag = false;
                        this.notify();
                        }
                        }
                        public static void main(String[] args) {
                        final Printer s = new Printer();
                        new Thread() {
                        public void run() {
                        while (true) {
                        s.print1();
                        }
                        }
                        }.start();
                        new Thread(new Runnable() {
                        public void run() {
                        while (true) {
                        s.print2();
                        }
                        }
                        }).start();
                        }
                        }
                        JDK5线程间的通信 – 锁 – 互斥锁 – 同一时间只能有一个线程执行
                        import java.util.concurrent.locks.Condition;
                        import java.util.concurrent.locks.ReentrantLock;
                        public class NotifyByJDK5 {
                        private static class Printer {
                        private boolean flag = false;
                        private ReentrantLock lock = new ReentrantLock();
                        private Condition c1 = lock.newCondition();
                        private Condition c2 = lock.newCondition();
                        public void print1() {
                        lock.lock();
                        while (flag) {
                        try {
                        c1.await();
                        } catch (InterruptedException e) {
                        throw new RuntimeException(e.getMessage(), e);
                        }
                        }
                        System.out.println("好好学习!");
                        flag = true;
                        c2.signal();
                        lock.unlock();
                        }
                        public void print2() {
                        lock.lock();
                        while (!flag) {
                        try {
                        c2.await();
                        } catch (InterruptedException e) {
                        throw new RuntimeException(e.getMessage(), e);
                        }
                        }
                        System.out.println("天天向上!");
                        flag = false;
                        c1.signal();
                        lock.unlock();
                        }
                        }
                        public static void main(String[] args) {
                        final Printer s = new Printer();
                        new Thread() {
                        public void run() {
                        while (true) {
                        s.print1();
                        }
                        }
                        }.start();
                        new Thread(new Runnable() {
                        public void run() {
                        while (true) {
                        s.print2();
                        }
                        }
                        }).start();
                        }
                        }


                        IP属地:北京17楼2013-03-01 08:50
                        回复
                          马克


                          IP属地:四川来自Android客户端18楼2013-03-01 08:51
                          回复

                            原子类型 – 数据在操作的过程中不会执行其他线程
                            import java.util.concurrent.atomic.AtomicInteger;
                            public class Exercise {
                            private static class Service {
                            private AtomicInteger integer = new AtomicInteger();
                            public void increment() {
                            System.out.println(Thread.currentThread().getName()+" incr,x = "+integer.addAndGet(3));
                            }
                            public void decrement() {
                            System.out.println(Thread.currentThread().getName()+" decr,x = "+integer.addAndGet(-3));
                            }
                            }
                            public static void main(String[] args) {
                            final Service service = new Service();
                            for (int i = 0; i < 2; i++) {
                            new Thread(){
                            public void run() {
                            while (true) {
                            service.increment();
                            }
                            }
                            }.start();
                            }
                            for (int i = 0; i < 2; i++) {
                            new Thread(){
                            public void run() {
                            while (true) {
                            service.decrement();
                            }
                            }
                            }.start();
                            }
                            }
                            }
                            线程池
                            import java.util.concurrent.ExecutorService;
                            import java.util.concurrent.Executors;
                            import java.util.concurrent.ScheduledExecutorService;
                            import java.util.concurrent.TimeUnit;
                            public class ThreadPool{
                            public static void main(String[] args) {
                            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
                            ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
                            ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
                            ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
                            scheduledThreadPool.schedule(new Runnable() {
                            public void run() {
                            System.out.println("计时器线程开始");
                            }
                            }, 3000, TimeUnit.MILLISECONDS);
                            for (int i = 0; i < 10; i++) {
                            final int task = i;
                            fixedThreadPool.execute(new Runnable() {
                            public void run() {
                            for (int i = 0; i < 3; i++) {
                            System.out.println(Thread.currentThread().getName()+": 任务"+task+", 循环"+i);
                            try {
                            Thread.sleep(1000);
                            } catch (Exception e) {
                            throw new RuntimeException(e.getMessage(),e);
                            }
                            }
                            }
                            });
                            }
                            fixedThreadPool.shutdown();
                            }
                            }


                            IP属地:北京20楼2013-03-01 08:51
                            回复

                              线程未完成,阻塞线程等待线程完成
                              import java.util.concurrent.Callable;
                              import java.util.concurrent.ExecutionException;
                              import java.util.concurrent.ExecutorService;
                              import java.util.concurrent.Executors;
                              import java.util.concurrent.Future;
                              public class ThreadPool {
                              public static void main(String[] args) throws Exception {
                              ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
                              final Future<String> submit = cachedThreadPool.submit(new Callable<String>() {
                              public String call() throws Exception {
                              System.out.println("任务开始");
                              Thread.sleep(3000);
                              System.out.println("任务结束");
                              return "result";
                              }
                              });
                              cachedThreadPool.execute(new Runnable() {
                              public void run() {
                              try {
                              System.out.println("等待结果");
                              System.out.println("执行成功:"+submit.get());
                              } catch (InterruptedException e) {
                              e.printStackTrace();
                              } catch (ExecutionException e) {
                              e.printStackTrace();
                              }
                              }
                              });
                              cachedThreadPool.shutdown();
                              System.out.println("执行其他任务");
                              }
                              }
                              批量添加任务之后获取最先完成的任务的返回结果
                              import java.util.Random;
                              import java.util.concurrent.Callable;
                              import java.util.concurrent.ExecutorCompletionService;
                              import java.util.concurrent.ExecutorService;
                              import java.util.concurrent.Executors;
                              public class ThreadPool {
                              public static void main(String[] args) throws Exception {
                              ExecutorService executorService = Executors.newCachedThreadPool();
                              ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
                              for (int i = 0; i < 10; i++) {
                              final int task = i;
                              completionService.submit(new Callable<String>() {
                              public String call() throws Exception {
                              int ms = new Random().nextInt(3000);
                              System.out.println("任务"+task+", 需要"+ms+"毫秒");
                              Thread.sleep(ms);
                              return "任务"+task+"已完成";
                              }
                              });
                              }
                              for (int i = 0; i < 10; i++) {
                              System.out.println(completionService.take().get());
                              }
                              }
                              }
                              读取和写入锁
                              import java.util.concurrent.locks.ReadWriteLock;
                              import java.util.concurrent.locks.ReentrantReadWriteLock;
                              public class ReadWriteLockDemo {
                              private static class PWLService {
                              private ReadWriteLock rw = new ReentrantReadWriteLock();
                              public void read() {
                              rw.readLock().lock();
                              System.out.println("读取操作");
                              rw.readLock().unlock();
                              }
                              public void write() {
                              rw.writeLock().lock();
                              System.out.println("写入操作");
                              rw.writeLock().unlock();
                              }
                              }
                              }
                              数据缓存 – 模拟hibernate获取元素的方法
                              import java.util.concurrent.locks.ReadWriteLock;
                              import java.util.concurrent.locks.ReentrantReadWriteLock;
                              public class CacheContainer {
                              private ThreadLocal<Object> tl = new ThreadLocal<Object>();
                              private ReadWriteLock rw = new ReentrantReadWriteLock();
                              public Object get() {
                              rw.readLock().lock();
                              Object obj = tl.get();
                              rw.readLock().unlock();
                              if (obj==null) {
                              rw.writeLock().lock();
                              obj = tl.get();
                              if (obj==null) {
                              obj = new Object();
                              tl.set(obj);
                              }
                              rw.writeLock().unlock();
                              }
                              return obj;
                              }
                              }


                              IP属地:北京21楼2013-03-01 08:52
                              回复