Topic(s)Suggested Readings
Abstraction, Inheritance, PolymorphismChap. 10
Exceptions and Advanced File IOChap. 11
Java Gui's – Swing / JavaFXChap. 12-14 (plus supplements)
GenericsChap. 17
Collections (maps, sets, lists)Chap. 18
Linked ListsChaps. 19
Stacks, QueuesChap. 21
Databases - JDBCChap. 22 (supplemented)
+ Regular Expressions from notes, source examples and links(supplemented)1

# Study guide part 1

  1. What SQL operator can be used to perform a search for a substring?

    • STR
    • SUB
    • WHERE
    • LIKE
  2. What must you have installed on a system before you can use JDBC to access a database on the system?

    • Java
    • A DBMS
    • Both A and B
    • Neither A nor B
  3. What term refers to data that describes other data?

    • meta data
    • abstract data
    • micro data
    • pseudo-data
  4. Which of the following is NOT a part of JDBC URL?

    • <protocol>
    • <subprotocol>
    • <subname>
    • <tablename>
  5. package contains classes that help in connecting to a database

    • sql.java
    • mysql.java
    • java.sql
    • java.mysql
  6. Two main interfaces that directly use the Collection interface are and .

    • AbstractList, LinkedList
    • Set, List
    • List, Vector
    • HashSet, LinkedHashSet
  7. The function below can be rewritten how?

    addButton.setOnAction((ActionEvent e) {
        data.add(new Person("Z","X"));
    }
    • addButton.setOnAction((ActionEvent e()) -> { data.add(new Person("Z","X")); });
    • addButton.setOnAction((ActionEvent e() -> { data.add(new Person("Z","X"))); });
    • addButton.setOnAction((ActionEvent e) -> { data.add(new Person("Z","X")); });
    • addButton.setOnAction((ActionEvent e -> { data.add(new Person("Z","X")); });
  8. Which is not a solid example of encapsulation?

    • A Car class having a has-a relation with class Parts
    • Taking for granted a wikipedia definition
    • A washing machine and its use of a power Button
    • A Touring machine

    哪个不是封装的可靠示例

  9. Given the generic following method, what can be passed in as a parameter value?

    public static <E extends Number> 
    void displayArray(E[] array) {
        for (E element : array)
        System.out.println(element); 
    }
    • an array whose element type is E
    • an array whose element type is Object
    • an array whose element type is Integer
    • an array whose type is any superclass of Number
  10. Variable result below has what action performed on it?

    newMain(){
        Integer i = new Integer(-8);
        int result = newValue(i);
    }
    public static int newValue(int i) {
        return (i < 0) ? -i : i;
    }
    • boxing
    • autoboxing
    • casting
    • unboxing
  11. Write a create table statement below to create the tickets table (my_Ticket) for your project given the information listed below.

    Field nameField TypeField SizePrimary Key?Nulll?
    idAuto_incrementYN
    ticketNumIntegerNY
    ticketDecscvarchar100
    String sql = "CREATE TABLE my_Ticket " +
                       "(id INTEGER not NULL AUTO_INCREMENT, " +
                       " ticketNum INTEGER, " +
                       " ticketDesc VARCHAR(100), " +
                       " PRIMARY KEY ( id ))";
  12. Create an insert statement below to insert a record into the above table that contains the data below.

    Variable (Field) nameData
    Id
    ticketNum1001
    ticketDecscPC Virus
    String sql = "INSERT INTO my_Ticket(ticketNum, ticketDesc) " +
                              "VALUES ('"+ticket_num+"','"+ticket_desc+"')";
  13. Write a statement that will update all ticketNum fields > 200 and whose
    ticketDesc field has the containment Bootstrapped virus found to a ticketDesc value of Bootsector virus found from the table above.

    String sql = "update my_Ticket set ticketDesc = 'Bootsector virus found' where ticketDesc like 'Bootstrapped virus found' and ticketNum > 200";
  14. Assume a file called data.dat is opened for reading and contains the following record data. Assume records begin with a number:

    1 Puppy 2 Catnap 3 plaintiff 4 CoolCat 5 Cat and mouse 6 Catburgler.  
    

    Fill in the underline to complete the statement for variable REGEX below to allow for the displaying any data containing the letters cat.

    while((line = bufferedReader.readLine()) != null) {
        String REGEX = "cat+";
        Pattern p = Pattern.compile(REGEX,Pattern.CASE_INSENSITIVE);
        String phrase = line.substring(2);
        Matcher m = p.matcher(phrase); 
        while(m.find()) {
            System.out.println(phrase);
        }
    }
  15. Given a button named btnCancel , in FX an alert can verify if the cancel button has been pressed how?

    • Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == btnCancel){}
    • Optional<Button> result = alert.showAndWait();
        if (result.get() == btnCancel){}
    • Optional result = alert.showAndWait();
        if (result.get() == btnCancel){}
    • Optional<ButtonType> result = alert.showAndWait();
        if (result == btnCancel){}

# Study guide part 2

  1. Can we call a non-static method from inside a static method?

    我们可以从静态方法内部调用非静态方法吗?
    Non-Static methods are owned and called by objects of a class and have object level scope so in order to call the non-static methods from a static block (like the main method), an object of the class needs to be created first.
    非静态方法由类的对象拥有和调用,并且具有对象级别的范围,因此为了从静态块(如 main 方法)调用非静态方法,需要首先创建类的对象 。

  2. What are some differences between a JDBC statement object and prepared statement object?

    JDBC 语句对象和预准备语句对象之间有什么区别?
    Primarily the differences between a standard JDBC statement and a PreparedStatement are best viewed by the benefits that a PreparedStatement gives you and your application.
    首先,通过 PreparedStatement 给您和您的应用程序带来的好处,可以最好地查看标准 JDBC 语句和 PreparedStatement 之间的差异。

    Some core advantages include the following:
    一些核心优势包括:

    • SQL Injection Prevention SQL 注入预防
    • Pre-Compilation 预编译
    • Ease of coding 易于编码
  3. Explain how an Iterator can be beneficial when traversing elements of a data structure.

    解释遍历数据结构的元素时,迭代器如何有益。
    The Iterator pattern enables you to traverse through all the elements in a data structure without knowing or caring how those elements are stored or represented. The iterator provides methods for fetching the elements of the collection, one at a time, in some order.
    迭代器模式使您可以遍历数据结构中的所有元素,而无需知道或关心如何存储或表示这些元素。 迭代器提供了一些以某种顺序一次获取集合元素的方法。
    Ex.

    import java.util.ArrayList;
    import java.util.Iterator; 
    ::
    ArrayList names = new ArrayList();
    names.add("Thomas");
    names.add("Betty");
    names.add("Pritesh");
     
    Iterator it = names.iterator();
     
    while(it.hasNext()) {
        String obj = (String)it.next();
        System.out.println(obj);
    }
  4. Can we override any static methods in an Interface? Explain.

    我们可以覆盖接口中的任何静态方法吗? 说明。
    No. The interface static method helps provide security by not allowing implementation classes to override them. Note a compiler error will occur if you attempt to override any static method – ex. The method whateEver() of type someClass must override or implement a supertype method.
    不能。接口静态方法通过不允许实现类覆盖,来帮助提供安全性。 请注意,如果您尝试覆盖任何静态方法,则会发生编译器错误。
    例如,someClass 类型的 whateEver() 方法必须重写或实现超类型方法。

  5. Compare and contrast HashMaps vs. HashTables. Which of the types allow nulls? Which allow duplicates? Which are thread safe? How are orders retained upon insertion? What are access time capabilites?

    比较和对比 HashMaps 与 HashTables。 哪种类型允许空值? 哪些允许重复? 哪些是线程安全的? 插入后如何保留线程? 什么是访问时间功能?

    • HT: It does not allow nulls for both key any value. It will throw a NullPointerException.
      不允许两个键的任何值都为 null。 它将抛出 NullPointerException。
      Hashtable does not maintain insertion order. The order is defined by the Hash function. So only use this if you do not need data in order.
      哈希表不保持插入顺序。 顺序由哈希函数定义。 因此,仅在不需要顺序数据时才使用它。
      It is synchronized. It is slow. Only one thread can access it at a time.
      同步。 太慢了。一次只能有一个线程访问它。
      Thread safe.
      线程安全。

    • HM: Does not maintain insertion order.
      不保持插入顺序。
      It is not synchronized. It will have better performance.
      不同步。 它将具有更好的性能。
      HashMap are not thread safe
      HashMap 不是线程安全的
      Allows for nulls for both K,V
      允许 K,V 都为空

  6. Describe all the relationships shown below.

    1.png

    描述下面显示的所有关系。
    Order and Customer have a 1:1 relationship.
    订单与客户具有 1:1 关系。
    Order and OrderLine have a 1:0:Many relationship.
    Order 和 OrderLine 具有 1:0:Many 关系。
    OrderLine and Profduct have a 1:1 relationship.
    OrderLine 和 Profduct 具有 1:1 关系。
    Crowsfeet guidelines follow…
    遵循 Crowsfeet 准则...

  7. Write code to “cleanse” the list below from dups. Hint- a quick way would be to make use of ArrayList's addAll() and clear() methods along with a Set interface.

    List<String> result = new ArrayList<>();
    result.add("Skype");
    result.add("Skype1");
    result.add("Skype");
    result.add("Ln");

    编写代码以 “清理” dump 中的以下列表。 提示 - 一种快速的方法是利用 ArrayList 的 addAll () 和 clear () 方法以及 Set 接口。

    Set cleanser = new HashSet<String>(result);
    result.clear();
    result.addAll(cleanser);
  8. Use a “for enhanced” loop to show results of the rebuilt list from question #7 above.

    使用 “增强” 循环显示上述问题 7 的重建列表的结果。

    for (String results : result) {
        System.out.println(results);
    }
  9. Given the following initializations for the hashmap object students and the container list of type ArrayList to hold student data, display students in alpha order along with their respective scores.

    students.put("Thomas" , 60);
    students.put("Betty" , 99);
    students.put("Pritesh", 77);
    ArrayList<String> list = new ArrayList<String>();
    for (Entry<String, Integer> entry : students.entrySet()){
        String key = (String) entry.getKey();
        Integer value = (Integer) entry.getValue();
        list.add(key + " " + value);
    }

    给定以下哈希表对象学生的初始化以及用于保存学生数据的 ArrayList 类型的容器列表,按字母顺序显示学生及其各自的分数。

    Collections.sort(list);
    for (String str : list) {
        System.out.println(str);
    }
  10. Given the desired number of rows entered by a user number write a program to display in a triangle like pattern that follows based on user input.

    Ex.
    1
    2 3
    4 5 6
    7 8 9 10
    etc.
    

    给定用户编号输入的所需行数,编写一个程序,以基于用户输入的三角形图案显示。

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of rows which you want in your Triangle: ");
        int r = in.nextInt();
        int n=0;
        for(int i=0; i<r; i++) {
            for(int j=0; j<=i; j++)
                System.out.print((++n)+" ");
            System.out.println();
        }//end outer for
    }//end main
  11. Consider an interface that defines how to compare the size of objects.

    public interface Relatable {
       /* define function from an instance to return 1, 0, -1 if
          instance is greater than, equal to, or less than other */
        public int isLessThan(Relatable other);
    }

    Finish coding the method below to return an either a 1, 0 or -1. The method defined for this example is in a class called Rectangle which implements the Relatable interface. Use the Rectangle class' getArea() method to detemine if one object is greater than, equal to or less than another object.

    定义比较对象大小的接口。

    public int isLessThan(Relatable other) {
    /*hint- cast Relatable object passed as Rectangle type*/
        Rectangle otherRect = (Rectangle)other;
        //ans.
        if (this.getArea() < otherRect.getArea())
            return -1;
        else if (this.getArea() > otherRect.getArea())
            return 1;
        else
            return 0;     
    }
  12. Write a generalized algorithm in plain wording how to accomplish the following scenario.
    Given a stack of integers, check whether each successive pair of numbers in the stack is consecutive or not. The pairs can be increasing or decreasing and if the stack has an odd numbers of elements, the elements at the top is left out of pair.

    For example, if the stack of elements are [4, 5, -2,-3,11,10, 5, 6, 20] , then the output should be true because each of the pairs (4, 5) , (-2, -3) , (11, 10) , and (5, 6) consist of consecutive numbers.

    用通俗易懂的语言编写一个通用算法,以完成以下方案。
    给定一个整数堆栈,请检查堆栈中每个连续的数字对是否连续。 元素对可以增加或减少,如果堆栈中元素的数量为奇数,则顶部的元素不成对。
    例如,如果元素堆栈为 [4, 5, -2,-3, 11, 10, 5, 6, 20] ,则输出应为 true,因为每对对 (4, 5) , (-2, -3) , (11, 10) , and (5, 6) 由连续数字组成。

    Create method called CheckStack
        Perform housekeeping:
        Set a test array to hold 2 int values
        Set a boolean flag to denote any if compared values match or not
        Pop last element in an odd stack to disregard it
        Create for loop to loop 4x
            Pop 2 elements to test successive values
            Store results in test array at positions 0, 1
            Create inner for loop to see if array positions are successive
                If values are successive set flag to true
    Exit method
    
    //Actual code solution of algorithm: assume stack is built
    public boolean CheckStack(Stack<Integer> st){
        int[] test = new int[2];
        boolean flag=false;
        st.pop();//disregard last element in odd stack
        for(int i = 0; i < 4; i++) {
            System.out.println("i = " + i);
            if (!st.empty()) {
                //test 2 elements at a time
                test[0]=st.pop();
                test[1]=st.pop();
                System.out.println(test[0] + " " + test[1]);
                Arrays.sort(test);
                for (int x = 0; x < test.length - 1; x++) {
                    System.out.println(test[x] + " " + test[x+1]);
                    if ((test[x] + 1) == (test[x + 1]))  
                        // Is sequential
                        flag = true;
                    else 
                        return false; // Not sequential
                }
            }
        }
        return flag;
    }
  13. Code a method called MidVal that accepts an arraylist and returns the middle integer data value in the arraylist.

    This can be done two ways:

    1. They can just grab the integer value in the middle of the array (watch for odd number vs. even number element count) –this is the best way
    2. Sort the array to find the median value (alternative poss. way)
      Make sure arryalist is passed properly through parameter
      Ex. ArrayList<Integer> arr

    编写一个名为 MidVal 的方法,该方法接受一个数组列表并返回该数组列表中的中间整数数据值。

    public int MidVal (ArrayList<Integer> arr) throws Exception { 
        if (arr== null) { 
            throw new Exception ("null input arraylist, so MidVal is undefined"); 
        }
        if (arr.size() == 0) { 
            throw new Exception ("input arraylist is empty, so MidVal is undefined"); 
        }
        int size = arr.size(); 
        int midIndex = size / 2; // auto-truncation 
        if (size % 2 == 0) { // arraylist has even number of elements 
            // return average of middle two index values 
            return (arr.get(midIndex) + arr.get(midIndex - 1))/2; 
        } else { // arraylist has odd number of elements 
            return arr.get(midIndex); 
        }
    }
  14. How would you sort mutliple fields within an Arraylist of type BankRecords?

    Depending on which fields you wish to sort we can set up a class to implement a Comparator interface and choose which fields to compare with for the major sort.

    您如何在 BankRecords 类型的 Arraylist 中对多个字段进行排序?
    根据您希望排序的字段,我们可以设置一个类来实现 Comparator 接口,并选择要与主要字段进行比较的字段。
    Ex. Uber clients for Chicago follows

    import java.util.ArrayList;
    import java.util.Collections;
    public class Chicago {
        String name;
        int distance;
        public Chicago(String name, int dist) {
            this.name=name;
            distance = dist;
        }
        public static void main(String[] args) {
            ArrayList<Chicago> ar = 
                    new ArrayList<Chicago>();
            ar.add(new Chicago("Joe Cool " , 10));
            ar.add(new Chicago("Charlie B " , 52));
            ar.add(new Chicago("I Trump " ,13 ));
            //sort 
            Collections.sort(ar,new sortByName());
            //display
            for(Chicago clients: ar) {
                System.out.println("Client name: " +
                                   clients.name +  "Distance : " +   clients.distance);
            }
        }
    }
    import java.util.Comparator;
    //comparator sorts multiple members (fields)
    public class sortByName implements Comparator<Chicago>{
        @Override
        public int compare(Chicago t, Chicago t1) {
            return t1.distance - t.distance;
        }
    }
  15. Explain how or code the following method to merge the two arrays sent through the parameter list.

    说明以下方法如何或编码以合并通过参数列表发送的两个数组。

    public static int[] mergeArray(int[]arrayX, int[]arrayY) {
        //  The size of the new array will be the sum of arrayA and arrayB
        int[] arrayM = new int[arrayX.length + arrayY.length];
        int i = 0, j = 0, k = 0;
        //  Loop to sort
        while (i < arrayX.length && j < arrayY.length)  {
            if (arrayX[i] < arrayY[j])
                arrayM[k++] = arrayX[i++];
            else
                arrayM[k++] = arrayY[j++];
            
        }  //  end  while loop 1
        
        //  loop that will copy the remainder of arrayA into new array, if necessary
        while (i < arrayX.length)   {
            arrayM[k++] = arrayX[i++];
        } // End while loop 2
        //  loop that will copy the remainder of arrayB into new array, if necessary
        while (j < arrayY.length)   {
            arrayM[k++] = arrayY[j++];
        }  //  end while 3
        
        return arrayM;
    }
  16. Tracing the code! You have a queue with 10 integers Q = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } . The expected output is Q = { 1, 6, 2, 7, 3, 8, 4, 9, 5, 10 } . Fill in any blanks alongside comments where shown to show trace results of the stack or queue.

    跟踪代码! 您有一个包含 10 个整数的队列 Q = {1,2,3,4,5,6,7,8,8,9,10}。 预期输出为 Q = {1,6,2,7,3,8,4,9,5,10}。 填写注释旁边的所有空白,以显示堆栈或队列的跟踪结果。

    public class InterleavingElements {
        public static void main(String[] args) {
            Queue<Integer> q = new LinkedList<Integer>();
            //Adding integers from 1 to 10
            for (int i = 1; i <= 10; i++) {
                q.add(i);     //1,2,3,4,5,6,7,8,9,10
            }
            InterleavingElements ii = new InterleavingElements();
                  System.out.println("this is queue " + q.toString());
            ii.InterchangingInterleaving(q);
            System.out.println("this is queue " + q.toString());
        }
        public Queue<Integer> InterchangingInterleaving(Queue<Integer> q) {
            Stack<Integer> st = new Stack<Integer>();
            int size = q.size()/2;
            for(int i = 1; i <= size; i++){
                st.push(q.remove());    //1,2,3,4,5
            }
            while(!st.isEmpty()){
                q.add(st.pop());            //6,7,8,9,10,5,4,3,2,1
            }
            for(int i = 1; i <= size; i++){
                q.add(q.remove());      //5,4,3,2,1,6,7,8,9,10
            }
            for(int i = 1; i <= size; i++){
                st.push(q.remove());  //5,4,3,2,1
            }
            while(!st.isEmpty()){
                q.add(st.pop());           //1, 2, 3, 4, 5
                q.add(q.remove());    //6, 7, 8, 9, 10
            }    
            return q;
        }
    }
  17. Describe some best practices when coding so no mistakes are made logically/syntactically. Back up your answers with some proper reasoning.

    描述编码时的一些最佳做法,这样就不会在逻辑 / 语法上犯错误。 用适当的理由备份您的答案。
    Best practices

    • Write the test before writing the implementation code
      在编写实现代码之前先编写测试
    • Include proper naming Conventions
      包括适当的命名约定
    • Use try / catch / finally blocks
      使用 try /catch/finally 块
    • Close any DB connections / IO streams
      关闭所有数据库连接 / IO 流
    • Avoid any null pointer exceptions
      避免任何空指针异常
    • Make use of Regex
      使用正则表达式
    • Make use of Collections
      利用 Collections
    • Keep code clean and organized
      保持代码整洁有序
    • Avoidance of unecessary objects
      避免不必要的对象
      Best practices
      • Write the test before writing the implementation code
      • Include proper naming Conventions
      • Use try / catch / finally blocks
      • Close any DB connections / IO streams
      • Avoid any null pointer exceptions
      • Make use of Regex
      • Make use of Collections
      • Keep code clean and organized
      • Avoidance of unecessary objects