JavaExam

Contents.png

Java基本编译操作

$ javac HelloWorld.java
$ java HelloWorld

类,对象

  • What is a Java class?
    ➢ A template for a new data type (一种数据类型,即对象类型)
      – If you write a class, objects of that class’s type can be constructed and used.
    ➢ A code module(模块)
        - Class是面相对象程序设计中 最基本的程序单元。
      – A module is a unit of program code.
      – Putting code in separate classes separates your program’s functionality.
    ➢ Arrays in Java
      – Not pointers, like C, but first-class objects 
        – Checked at run-time for safety
      – Covered later
    
  • Object

    Everything is an Object.
    
  • Literals

    - Boolean Literals
    ➢ There are only two: true 、 false
    
    - Underscores (_) in Numeric Literals
    ➢ any number of underscore characters (_) can appear anywhere between digits in a numerical literal
      – cannotplaceunderscoresinthefollowingplaces:
      ➢ At the beginning or end of a number
      ➢ Adjacent to a decimal point in a floating point literal ➢ Prior to an F or L suffix
      ➢ In positions where a string of digits is expected
      
    - Binary Literals
    ➢ the integral types (byte, short, int, and long) can also be expressed using the binary number system.   – Java SE 7
    ➢ add the prefix 0b or 0B to the number
    
  • static Method

    ➢ What if you want a method that can be called for the class, without an object? (“class method”)
        
        class StaticFun {
           static void incr() {       WithStaticData.x++;     }   // 不可被重写,不能是抽象方法
         }
         StaticFun.incr();
    
  • Annotations

    ➢ @Override:限定重写父类
    ➢ @Deprecated:标记已过时
    ➢ @SuppressWarning:抑制编译器警告 
    ➢......
    
  • Overloading 重载

    - Unique combinations of argument types distinguish overloaded methods
    ➢ One word, many meanings: overloaded
    
    - Overloading with primitives
    ➢ if you have a data type that is smaller than the argument in the method, that data type is promoted 
    ➢ if your argument is bigger than the argument expected by the overloaded method, you must cast to the necessary type by placing the type name inside parentheses.
      – If you don’t do this, the compiler will issue an error message
      – narrowing conversion
    
    - no Overloading on return values
    
    - Default constructors: Takes no Arguments
    ➢ Compiler automatically creates one for you if you write no constructors
    if you define any constructors (with or without arguments), the compiler will not synthesize(合成) one for you
    
  • The meaning of static

    ➢ there is no this for that particular method // 不支持this
    ➢ cannot call non-static methods from inside static methods   // psvm
    ➢ you can call a static method for the class itself, without any object 类名调用static方法
    
    if you find yourself using a lot of static methods, you should probably rethink your strategy // 尽可能少地使用static方法
    
  • finalize()

    ➢ Using finalize() to detect an object that hasn't been properly cleaned up.
    ➢ finalize() is only useful for obscure memory cleanup that most programmers will never use. // 善后
    

包 Package

➢ A package is a collection of functionally related 'classes' and 'interfaces' providing access protection and namespace management.    (定义)

➢ Managing “name spaces”
– Class members are already hidden inside class
– Class names could clash(类名冲突)
– Need completely unique name even over the Internet(名称唯一)

➢ Creating unique package names (独一无二的包名)
– Location on disk encoded into package name
– bruceeckel.com (Note change to lowercase 'com') 
    package com.bruceeckel.util;
    
➢ Legalizing Package Names  ('域名'与'包名'完全逆序)
    Domain Name → Package Name Prefix
    hyphenated-name.example.org → org.example.hyphenated_name
    example.int → int_.example

➢ 'import' the constants and static methods
    – do not need to prefix the name of their class (无需重写包名as前缀)

➢ “Friendly”  (同一个包内,任意调用类方法或类成员)
    - Default access, has no keyword (Also referred to as "package access")
    - public to other members of the same package, private to anyone outside the package
 ➢ AccessControl
 public: Interface Access
 private: Can’t Touch That!
 protected: deals with inheritance
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

继承 inheritance

继承是子类利用父类中定义的方法和变量就像它们属于子类本身一样。
方法的覆盖:在子类中重新定义父类中已有的方法。

通过在类的声明中加入extends子句来创建一个类的子类. 
如果缺省extends子句,则该类为java.lang.Object的子类。

子类可以继承父类中访问权限设定为public、 protected、 default的成员变量和方法。
但是不能继承访问权限为private的成员变量和方法。

方法覆盖(overriding)指子类对 父类的方法进行改写
子类覆盖的方法同父类的方法要保持名称、返回值类型、 参数列表的统一。
• 改写后的方法不能比被覆盖的方法 有更严格的访问权限
• 改写后的方法不能比被覆盖的方法 产生更多的异常
  • Upcasting ("向上"类型转换)

  • The final Keyword

    ➢ "This cannot be changed"
        
    ➢ A bit confusing: two reasons for using it 
      – Design
      – Efficiency
    
    ➢ final data ➢ 修饰变量,变量就变成了常量;
    ➢ final methods ➢ 修饰方法,方法就'不'能再'覆盖'; 
    ➢ final class ➢ 修饰类,类就'不'能再'继承'.
    
    ➢ final arguments
      void f(final int i) { // ...
        - Primitives can’t be changed inside method
              void g(final Bob b) {
                    b = new Bob(); (错 × ) // 不可更改
                }
        - References can’t be rebound inside method
        - Generally, neither one is used
    
  • Pure Inheritance vs. Extension

    -  Pure Inheritance  “Is a” 
      •Cannot extend the interface (不扩展)
           
    - Extension
      • Extending the interface (扩展,加入新方法)
    

多态 polymorphism

➢ Dynamic Binding in Java
binding occurs at run time, based on the type of object. Late binding is also called dynamic binding or run-time binding.
    
    
 * 隐式调用 super() 时,radius为0  (父类调用重写方法,子类成员变量还未初始化)
 * 子类重写后,new子类对象--调用子类重写后的方法
 
     
➢ 执行顺序
1. 主函数所在类中的static字段\代码块(而非static 方法),若该类为子类,则先执行父类中的static字段,再执行该类的static字段
2. main()主函数
3. new Cat()  
     3.1> 隐含调用 Animal() 父类构造方法 (先加载父类成员\代码块(先static后non-static);后加载构造函数)
     3.2> 加载 Cat类的成员变量、代码块 (先static后non-static)
     3.3> 顺序执行 Cat() 的构造方法  // 构造函数总是类的最后被调用,类中的方法不加载

抽象类 abstract class

 definition: Java classes that cannot be instantiated! 
  //抽象类不能被实例化,如果被实例化,就会报错,编译无法通过。只有抽象类的非抽象子类可以创建对象
 conceptually: a hybrid(混合) of a Java class and interface  

* 一个类只能继承一个抽象类,而一个类却可以实现多个接口
  • 抽象方法
- bstract关键字同样可以用来声明抽象方法,抽象方法只包含一个方法名,而没有方法体。
- 抽象方法没有定义,方法名后面直接跟一个分号,而不是花括号

声明抽象方法会造成以下两个结果:
- 如果一个类包含抽象方法,那么该类'必须是抽象类'
- 任何子类必须重写父类的抽象方法,或者声明自身为抽象类

- 抽象类的非抽象子类必须实现抽象类中的抽象方法
  • Summary
1. 抽象类不能被实例化,如果被实例化,就会报错,编译无法通过。只有抽象类的非抽象子类可以创建对象。
2. 抽象类中不一定包含抽象方法,但是有抽象方法的类必定是抽象类。
3. 抽象类中的抽象方法只是声明,不包含方法体,就是不给出方法的具体实现也就是方法的具体功能。
4. 构造方法,类方法(用static修饰的方法)不能声明为抽象方法。 // important
5. 抽象类的子类必须给出抽象类中的抽象方法的具体实现,除非该子类也是抽象类。

接口 Interface

- 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是'抽象方法'的集合,接口通常以interface来声明。一个类通过实现接口的方式,从而来继承接口的抽象方法 
    
- 一个实现接口的类,必须实现接口内所描述的'所有方法',否则就必须声明为'抽象类'.

- 接口特性
    - 接口'无法实例化对象'.
    - 接口'没有构造方法'.
    - 接口中所有的方法必须是'抽象方法'.(方法'隐式抽象'为 public abstract,不能在接口中实现)
        and default and static methods (需实现)
    - 接口'不能包含成员变量',除了 static 和 final 变量.(隐式指定为 public static final members)
    - 接口不是被类继承了,而是要被类'实现'.
    - 接口支持'多“继承”'(via 'implements'关键字). (补充:一个接口能继承另一个接口(使用'extends'关键字))
   
- Using an Interface as a Type
    public static void t(CanFight x) { x.fight(); }     // CanFight is interface

- 接口可以嵌套在类中,也可以嵌套在其他接口中
  • Default Methods (可以被重写)

  • Static Methods (不可被继承)

Generic

class NewPair {   // Notice!(class)
        private S first;
        private T second;

        public NewPair(S a, T b) {
            first = a;
            second = b;
        }

        public S getFirst() {
            return first;
        }

        public T getSecond() {
            return second;
        }
    }

------------------------------------------------------------
    public static >   
        int countGreaterThan(T[] anArray, T elem) {    //  > (method)
        int count = 0;
        for (T e : anArray)
            if (e.compareTo(elem) > 0)      // e.compareTo(elem)
                ++count;
        return count;
    }
------------------------------------------------------------
-  >

Inner Classes

/** 内部类其实严重破坏了良好的代码结构,但为什么还要使用内部类呢?
因为内部类可以随意使用外部类的成员变量(包括私有)而不用生成外部类的对象,这也是内部类的唯一优点。
如同心脏可以直接访问身体的血液,而不是通过医生来抽血。**/

Out.In in = new Out().new In(); //class Out{ class In{ } }  // 内部类的基本结构
Out.In in = new Out.In();   //class Out{ static class In{ } }   // 静态内部类
Out out = new Out(); out.outPrint();    // 私有内部类
/*class Out{ 
    private class In{ 
        public void print() {
            System.out.println(age);
        } 
    }  
    public void outPrint() {
        new In().print();
    }
}*/
Out out = new Out();  out.Print(3);     // 方法内部类
//class Out{ public void Print(final int x) { class In{ } } }

Exception机制

  • Exception 类是 Throwable 类的子类。除了Exception类外,Throwable还有一个子类Error

    异常类有两个主要的子类:IOException 类和 RuntimeException 类.

img
  • finally关键字

    无论是否发生异常,finally 代码块中的代码总会被执行。
    
    - 在 try/catch 后面添加 finally 块并非强制性要求的。
    - try 代码后不能既没 catch 块也没 finally 块
    
  • try-with-resources

    try-with-resources语句是一个声明了1到多个资源的try语句。资源是指这个try执行完成后必需close掉的对象,比如connection, resultset等。
    
    try-with-resources 语句会确保在try语句结束时关闭所有资源。实现了java.lang.AutoCloseable或java.io.Closeable的对象都可以做为资源。
    

Java数据结构

Arrays

// 声明数组  - Null reference
double[] myList;         // 首选的方法 
或
double myList[];         //  效果相同,但不是首选方法

// 创建数组
dataType[] arrayRefVar = new dataType[arraySize];
或
dataType[] arrayRefVar = {value0, value1, ..., valuek};

//Variable Size Array:
     int x[][] = new int[3][];
     x[0] = new int[2];
     x[1] = new int[4];
     x[2] = new int[3];

// wrong example
int table[][]={0,0,0,1,1,1};    (×)
int table[2][3]={0,0,0,1,1,1};  (×)
// Right example
int table[ ][ ]={{0,0,0},{1,1,1}}; (√)

//- Once initialized, the array size is fixed
- Arrays.equals(int[] a, int[] a2): compare two arrays for equality  "比较值相等"
– Arrays.copyOf(int[] original, int newLength): copy specified array
- Arrays.asList((T... a): takes any array and turns it into a List container
- Arrays.fill(int[] a, int val) 
- Arrays.sort(int[] a)
- Arrays.binarySearch(int[] a, int key)     // array must be sorted ; return the index of key

String

- Strings → Numbers
    float a = (Float.valueOf("1")).floatValue();
    float b = Float.parseFloat("1");    // a == b (1.0)
- Numbers → Strings
    String s1 = "" + i;
    String s2 = String.valueOf(i);
    String s3 = Integer.toString(i);
String.equal.png

Collection

img
- Java集合框架为程序员提供了预先包装的数据结构和算法来操纵他们。
- 集合是一个对象,可容纳其他对象的引用。集合接口声明对每一种类型的集合可以执行的操作。
- 集合框架的类和接口均在java.util包中。
- 任何对象加入集合类后,自动转变为Object类型,所以在取出的时候,需要进行强制类型转换。
Container taxonomy - simplified.png
Implementation-style.png
  • 遍历 ArrayList

    public class Test{
     public static void main(String[] args) {
         List list=new ArrayList();
         list.add("Hello");
         list.add("World");
         list.add("HAHAHAHA");
         //第一种遍历方法使用foreach遍历List
         for (String str : list) {  //或 for(inti=0;i ite = list.iterator();
         while(ite.hasNext())//判断下一个元素之后有值
         {
             System.out.println(ite.next());
         }
     }
    }
    
  • 遍历 Map

    public class Test{
         public static void main(String[] args) {
          Map map = new HashMap();
          map.put("1", "value1");
          map.put("2", "value2");
          map.put("3", "value3");
          
          //第一种:普遍使用,二次取值
          System.out.println("通过Map.keySet遍历key和value:");
          for (String key : map.keySet()) {
           System.out.println("key= "+ key + " and value= " + map.get(key));
          }
          
          //第二种
          System.out.println("通过Map.entrySet使用iterator遍历key和value:");
          Iterator> it= map.entrySet().iterator();
          while (it.hasNext()) {
           Map.Entry entry = it.next();
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
          
          //第三种:推荐,尤其是容量大时
          System.out.println("通过Map.entrySet遍历key和value");
          for (Map.Entry entry : map.entrySet()) {
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
        
          //第四种
          System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
          for (String v : map.values()) {
           System.out.println("value= " + v);
          }
         }
    }
    

Java IO系统

// InputStreamReader
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in); 
    int c;
        try {
            while ((c = isr.read()) != -1)
                System.out.println((char) c);
        } catch(IOException e) {
            //... 
        }
}

// BufferedReader
public static void main(String[] args) { 
    BufferedReader br =
new BufferedReader(new InputStreamReader(System.in)); 
    String s;
    try {
        while ((s = br.readLine()).length() != 0) 
        System.out.println(s);
         } catch(IOException e) {
               //...
        }
}

对象序列化

// Serialization Example - Reading
try {
    InputStream is = new FileInputStream(“file.txt”);
    ObjectInputStream ois = new ObjectInputStream(is);
    ArrayList someList = (ArrayList)ois.readObject();
    is.close();
  } catch (Exception e) { ... }


// Serialization Example - Writing
try {
    OutputStream os = new FileOutputStream(“file.txt”);
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(someList); 
    oos.flush();
    os.close();
  } catch (IOException ioe) { ... }

NIO

AWT, Swing

public class FrameTester {      //  JFrame Example
            public static void main(String args[]) {
                JFrame f = new JFrame("JFrame Example");
                Container c = f.getContentPane();   
                c.setLayout(new FlowLayout());  // default BorderLayout
                for (int i = 0; i < 5; i++) {
                    c.add(new JButton("No"));
                    c.add(new Button("Batter"));
                }
                c.add(new JLabel("Swing"));
                f.setSize(300, 200);
                f.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        }
//JOptionPane
class Addition {

    public static void main(String args[]) {

// obtain user input from JOptionPane input dialogs

        String firstNumber =
                JOptionPane.showInputDialog("Enter first integer");

        String secondNumber =
                JOptionPane.showInputDialog("Enter second integer");

        // convert String inputs to int values for use in a calculation
        int number1 = Integer.parseInt(firstNumber);
        int number2 = Integer.parseInt(secondNumber);

        int sum = number1 + number2; // add numbers


        // display result in a JOptionPane message dialog
        JOptionPane.showMessageDialog(null, "The sum is " + sum,
                "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
    } // end method main

}

JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbUtil {   // conn.createStatement()

    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";

    public static void main(String[] args) throws Exception {
        //1.加载驱动程序 load database driver class
        Class.forName("com.mysql.jdbc.Driver");
        //2. 获得数据库连接 connect to database
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        //3.Create a SQL statement object)
        Statement stmt = conn.createStatement();
        // 4. Getting data from a table
        ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
        //5. Use methods of ResultSet (如果有数据,rs.next()返回true)
        while(rs.next()){
            System.out.println(rs.getString("user_name")+" 年龄:"+rs.getInt("age"));  // rs.getString("user_name") / rs.getInt("age")
        }
    }
}
-------------------------------------------------
public class TestDB {   // conn.preparedStatement(sql)

    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";
    
    public static void main(String[] args) throws Exception {

        //1.加载驱动程序 load database driver class
        Class.forName("com.mysql.jdbc.Driver");

        //2. 获得数据库连接 connect to database
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);

        //3.Create a SQL statement object)
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM TODO");

        // 4. Getting data from a table
        ResultSet resultSet = preparedStatement.executeQuery();

        //5. Use methods of ResultSet (如果有数据,rs.next()返回true)
        while (resultSet.next()) {
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
        }
    }
}

java多线程

class Thread implements Runnable{}
- 实现 Runnable 接口来创建线程 
new Thread(Runnable threadOb,String threadName).start;
--------------------------------------
Talker talker = new Talker(); 
Thread t = new Thread(talker); 
t.start();
---
     class Talker implements Runnable {
       public void run() {
         while (true) {
           System.out.println(“Talker”);
            } 
       }
}

--------------------------------------------------------
- 继承Thread来创建线程
ThreadDemo T1 = new ThreadDemo( );
T1.setName("Thread-1");
T1.start();

void start()
    – Creates a new thread and makes it runnable (包含于Thread,继承的类亦可重写)
void run()
    – The new thread begins its life inside this method (继承的类必须实现)
- synchronized methods

class Account {
        private int balance;

        public synchronized void deposit(int val) {
            int newBal;
            newBal = balance + val;
            balance = newBal;
        }

        public void withdraw(int val) {
            synchronized(this) {
            int newBal;
            newBal = balance - val;
            balance = newBal;
            }
        }
    }
Deadlock
- Four Conditions of Deadlock
- Avoiding Deadlock
    - The easiest way to prevent deadlock is to break the fourth condition.
- Wait/Notify Sequence  (均在Object中定义)

1. synchronized(lock){
2.      lock.wait();
9.      consumeResource();
10. }

3. produceResource()
4. synchronized(lock){
5.      lock.notify(); 
6.}

7. Reacquire lock // 重新唤醒锁
8. Return from wait()
//  ForkJoin Framework
    ForkJoinPool pool = new ForkJoinPool();

    RecursiveTask> recursiveTaskInstance = CountByForkJoin.getInstance(list, 5);   // 实例化

    ForkJoinTask> future = pool.submit(recursiveTaskInstance);     // 提交可分解的ForkJoinTask任务

        // do something

    pool.shutdown(); 

java网络编程

TCP Socket

protocol localAddr,localPort remoteAddr, remotePort
conn-oriented server ServerSocket() accept()
conn-oriented client Socket()
connectionless server DatagramSocket() receive()
connectionless client DatagramSocket() send()
conn-oriented server
// 1. Create ServerSocket object
ServerSocket serverSocket = new ServerSocket(port);  

// 2. Server listens for client connection  (多于client的步骤)
Socket server = serverSocket.accept();
System.out.println("远程主机地址:" + server.getRemoteSocketAddress());

// 3. Sending and receiving data    (先read后write)
DataInputStream in = new DataInputStream(server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());

// 4. Server and Client communicate via streams
System.out.println(in.readUTF());   // in.readUTF()
out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!");     //out.writeUTF("something")  


// 5. Close streams and connections
server.close();
conn-oriented client
// 1. Create a Socket to connect to server
Socket client = new Socket(serverName, port);   
System.out.println("远程主机地址:" + client.getRemoteSocketAddress());

// 2. Obtain Socket’s InputStream and Outputstream (先write后read)
OutputStream outToServer = client.getOutputStream();
InputStream inFromServer = client.getInputStream();
DataOutputStream out = new DataOutputStream(outToServer);
DataInputStream in = new DataInputStream(inFromServer);

// 3. Process information communicated
out.writeUTF("Hello from " + client.getLocalSocketAddress());   //out.writeUTF("something")
System.out.println("服务器响应: " + in.readUTF()); // in.readUTF()

// 4. Close streams and connection
client.close();

Lambda 表达式

public void printSighting(Sighting record){System.out.println(record.getDetails()); }
等价于                          
(Sighting record) ->
{ System.out.println(record.getDetails()); }      

for(Sighting record : sightings) { printSighting(record);}
等价于
sightings.forEach((Sighting record) ->                               {System.out.println(record.getDetails()); }
 );

➢ infer type (缺省type)
sightings.forEach((record) ->
    {System.out.println(record.getDetails()); }
);
➢ single parameter (缺省参数括号)
sightings.forEach(record ->
    {System.out.println(record.getDetails()); }
);
➢ single statement (缺省body大括号)
sightings.forEach(record -> System.out.println(record.getDetails()));
➢ Aggregate Operations 
roster
    .stream()
    .filter(
        p -> p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25) 
    .map(p -> p.getEmailAddress())
    .forEach(email -> System.out.println(email));

STREAMS

There are three common types of operation:
– Filter: select items from the input stream to pass on to the output stream
– Map: replace items from the input stream with different items in the output stream
– Reduce: collapse the multiple elements of the input stream into a single element
A stream pipeline .png

Summary

  • Summary of Initialization & Cleanup

    ➢ Initialization is critical for objects, thus Java guarantees it with the constructor
    ➢ Knowing when to clean up can be difficult in complex systems
    ➢ Java GC releases memory only: any other cleanup must be done explicitly!
    ➢ Arrays also have Java-style safety
    

  • Summary of Hiding the Implementation

    ➢ Access control tells users what they can & can‟t use (shows the area of interest)
    ➢ Also separates interface & implementation
    ➢ Allows the class creator to change the implementation later without disturbing client code
    ➢ An important design & implementation flexibility
    ➢ Design guideline: always make elements “as private as possible”
    
  • Summary of Reusing Classes

    ➢ Easy to think that OOP is only about inheritance
    ➢ Often easier and more flexible to start with composition. Remember to say “has-a” and “is-a”
    ➢ Use inheritance when it’s clear that a new type is a kind of a base type
    ➢ ... and especially when you discover a need for polymorphism (next chapter)
    
  • Summary: The Key to OOP

OOP_key.png
  • AbstractClass & Interfaces

    ➢ abstract类定义方法,实现公共的方法。
    ➢ 接口(interface)就是'方法声明'和'常量值'的集合。 
    – An interface defines a protocol of communication between two objects.
    – 从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量的定义( public static final members)和方法的声明(public abstract),而没有变量和方法的实现。
    – (Java 8: default and static methods)
    ➢ 不相关的类可以实现(implement)同一个接口, 同一个类可以实现多个不相关的接口。
    
  • Inner Classes

    ➢ 允许一个类的定义在另一个类/方法里
    ➢ 集中使用某些共同特性 → GUI event handlers
    
  • Arrays

    ➢ An array associates numerical indices to objects – most efficient choice
    ➢ Arrays in Java are objects which belongs to class Array.
    ➢ Array objects implements only static arrays
    ➢ Java follows strict bound checking for referencing array elements.
    ➢ Array elements can be referenced from 0 to length-1.
    ➢ Java also follows strict type checking for Array elements.
    ➢ length is the attribute of each array which can be referenced by arrayreference.length
    
  • Collections Of Objects

    • An array associates numerical indices toobjects

      • A Collection holds single elements, anda Map holds associated pairs

      • Like an array, a List also associates numerical indices to objects

      – Use an ArrayList if you’re doing a lot of random accesses

      – but a LinkedList if you will be doing a lot of insertions and removals in the middle of the list

      • The behavior of queues, deques, and stacks can be provided via the LinkedList

      • A Map is a way to associate not numbers, but objects with other objects

      • HashMap is focused on rapid access

      • TreeMap keeps its keys in sorted order, and thus is not as fast as a HashMap.

      • – A LinkedHashMap keeps its elements in insertion order, but may also reorder them with its LRUalgorithm

      • A Set only accepts one of each type ofobject.

      • HashSets provide maximally fast lookups

      • TreeSets keep the elements in sorted order

      • LinkedHashSets keep elements in insertion order

  • IO

    ➢ Stream
    – 输入流只能读不能写,输出流只能写不能读;
    – 程序通过输入流读入数据,输出流写数据;
    
    ➢ I/O is hard
      – deals with real world beyond programmers control 
      – Output easier than input (programmer knows more) 
        – System.out.println() is straightforward
      – Juno Terminal wraps hard to use System.in
    ➢ java.io package provides lots of useful classes
    ➢ I/O programs may throw many Exceptions
    ➢ Even good tools are hard to use when materials are recalcitrant
    ➢ Count on borrowing from code that works
    
  • NIO

     Useful and long awaited addition to Java
     New I/O has been widely hailed as an important step forward in getting serious performance out of the Java platform.
     Besides raw performance, it provides the most critical I/O and networking functionalities that were absent in earlier versions of Java.
    

补充:

  • .next()

    • random.nextInt(int bound )

      int x = rd.nextInt(36) + 1;  //  Random rd = new Random(); 
      

    • iterator

     List list = new ArrayList<>();
            Iterator iterator = list.iterator();
            while (iterator.hasNext())  // hasNext()
                System.out.println(iterator.next());    // next()
    

    • 数据库resultSet.next()

      while (resultSet.next()) {
                  System.out.println(resultSet.getInt(1));
                  System.out.println(resultSet.getString(2));
              }
      

  • keyword: 不包含sizeof、status

  • FileOutPutStream

     public static void main(String[] args) {
            try {
                String s = "ABCDE";
                byte b[] = s.getBytes();
                FileOutputStream file = new FileOutputStream("test.txt",true);
                file.write(b);
                file.close();
            }catch (IOException e)
            {
                System.out.println(e.toString());
            }
        }
    

  • BufferedReader、FileReader、PrintWriter、FileWriter

     public static void main(String[] args)
        {
            File file = new File("./src/Exam/in.txt");
            File file1 = new File("./src/Exam/out.txt");
            System.out.println(file.exists());
            try (BufferedReader br = new BufferedReader(new FileReader(file));    // 
                 PrintWriter pw = new PrintWriter(new FileWriter(file1)))
            {
                int i = 0;
                String line;
                while ((line = br.readLine()) != null)      // br.readLine()
                {
                    pw.println("line " + (++i) + "=" + line);  // pw.println()
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    

 new ObjectOutputStream(new FileOutputStream(“file.txt”))

DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("something") // 网络编程
     
    
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());

 new BufferedReader(new FilerReader(“file.txt”));     
 new BufferedReader(new InputStreamReader(System.in)); 

你可能感兴趣的:(JavaExam)