Block 1

Basic Java

  1. how to use command line

    • step1: complete a java file that named “xxx.java”

    • step2: use “javac” command to compile

      1
      ...>aDict>javac -d example/bin example/hello.java 

      then a java file in “…/aDict/example” called “hello.java” is compiled and saved in “…/aDict/example/bin/example”

      Note: “example” is a package

    • step3: use “java” command to run

      1
      ...>aDict>java -cp example/bin example.hello

      then “hello.java” runs.

  2. Java comments

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // single line comment

    /*
    many line comments
    */

    /**
    * This is a javadoc comment
    * use "javadoc" cmd to generate a javadoc file that offers an API documentation.
    */
  3. main method

    1
    2
    3
    4
    5
    6
    public class hello{
    public static void main(String[] srgs){
    System.out.println("hello");
    System.out.println(args[0]);//throws an exception when there is no argument.
    }//a pair of curly brackets means a code block
    }
  4. variables & primitive type

  5. type cast

  6. Operator Precedence

  7. important statements

    if-else, while, do-while, for, switch-case, break, continue

Object-Oriented

  1. Object

    a thing. is neither an attribute, nor an operation.

    • exists at compile time
  2. Class

    define objects containing attributes and operations

    • exists at runtime.
  3. Object vs Class

    • class is the template of objects
    • objects are instances of the class
  4. Constructor

    • same name as the class name
    • no return type
    • no-argument constructor is provided if no constructor is given
    • constructor can be overridden
    • if you give a constructor with arguments, then no no-argument constructor will be provided
  5. Encapsulation

    hiding data, secure, reusable

  6. Access Modifiers

    • public: all can access only if importing them
    • protected: package member & subclasses of it
    • “default”: package member
    • private: class only
  7. Accessor & Mutator

    getter & setter

  8. Instance variable & Local variable

    • Instance variable: initialised to the default value(0, 0.0, false, null)
    • Local variable: no initialisation. If it is used with no value, there will be an error.
      • method parameters can be seen as local variables. Notice that method parameters are always initialised.
  9. reuse

    1
    2
    3
    4
    5
    6
    7
    8
    9
    private double radius;

    public circle(double radius){
    this.setRadius(radius);
    }

    public void setRadius(double radius){
    this.radius=radius;
    }
  10. Overloading

    • same name
    • different parameters
    • signature: name + type of parameter + parameters

Block 2

Arrays

  1. create an array

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    int[] nums= new int[5];
    int[] nums2= {0,1,2,3,4};
    int[] nums3= new int[]{1,2,3,4,5};
    Object[] objects= new Objects[5];

    System.out.println(nums[0]);
    System.out.println(nums[5]);//ArrayIndexOutOfBounds

    for(int i=0;i<nums.length;i++){
    System.out.println(nums[i]);
    }
  2. copy arrays

    • loop
    • System.arraycopy() method
    • clone method
  3. vs ArrayList

    ArrayList: a resizable array

    • ArrayList doesn’t need to know its size-- resizable
    • you can use add method to assign an object without provide index
    • parameterised: you need give the type of the objects to be stored
  4. API

    Java library

    • main packages in JDK: java.lang, java.util, java.io, java.awt
    • Math is in java.lang
    • ArrayList, Scanner , Random are in java.util

Inheritance

  1. overriding

    • same name as superclass method name
    • same parameters as superclass’
    • private, final, static methods can not be overridden
  2. Access Modifiers

    • private are not inherited
  3. super

    invoke variables, methods and constructors in superclass

Polymorphism

an object variable can refer to multiple actual types(upcasting)

  • you can use it in generics. eg. ArrayList<>
  • you can also use it when passing an argument
  • when there is an overriding method, invoking it instead of the method in superclass
  • Only variables in superclass can be invoked. static methods are also like this.
  • downcasting

Abstract class

an class with abstract methods

  • abstract method: no implement
  • abstract class cannot be initialisation
  • can not be modified by private, final or static
  • if there is no abstract method, a class can also be declared “abstract”
  • can have constructors

Object

the mega class that all classes extend it

  1. equals

    not only comparing references

  2. toString

  3. hashCode

  4. getClass

Block 3

Interface

  1. vs abstract class

    • differences:
      • no instant variables, only constant(public final static)
      • all methods must be abstract except default and static
      • a kind of multiple inheritance
    • similarities:
      • no initialization
      • can contain constants
      • both have abstract methods
  2. name conflicts

    • same methods:

      • different parameters: overloading
      • differ by return type: error
      • identical: keep one
    • same constants:

      • contain both: use “Interface. variable” to refer to them
  3. default & static

    • default:

      • give one implement method which can be overridden. --> when call the method which has the same name with other methods, use “Interface. super. method” to invoke it.
      • no private, no final, no static
      • has to be overridden when there are more than 1 default method with the same name
    • static:

      • similar to default, but cannot be overridden.
      • invoke just like the way constants do

Garbage Collection

  1. Heap & Stack

    • Stack: Method at the top is always the method being executed
    • Instance variables & Local variables -> declared in a class & declared in a method/ method parameters
    • Object & Object reference
      • Object reference: refers to an object. non-primitive
  2. Constructor Chaining

    • a new object is created, all constructors in its heritance tree must be run.
    • if no super() constructor is given, compiler will provide one.
    • super() /this() should be the first statement in the constructor
    • super() and this() cannot be invoked at the same time
  3. Life of objects and variables

    • object: depends only on the reference variable referring to it

      • memory for object is allocated at runtime dynamically.
      • if there is no alive reference variable referring to the object, the object will be eligible for GC.
      • get rid of references: reference goes out of scope, assigned to another object or set to null
    • local variable: lives only within the method that declared it

      • in scope: within the method that declared it. A variable can only be used when it is in scope.
    • instance variable: live for as long as objects they belong to live

Numbers

  1. final

    • no change, no overriding, no inheritance
    • variables: must either be initialized when declared or in the constructor
  2. static

    • static modifier: declare a class variable or class method

    • use class name to refer to them

    • variables:

      • static variables are created when class is created
      • all objects of the same class have the same static variables
      • non-initialized static variables will have default value
    • methods:

      • static method is available when the class is created
      • all objects of the same class have the same copy of methods
      • static methods can only reference static variables
  3. Math

    • no instance variables
    • cannot make an instance of class –private constructor
    • eg. Math. min(), Math. max(), Math. cos()…
    1
    System.out.println(Math.round(-0.5) + " " + Math.round(0.5));

    output: “0 1”

  4. Initialization

    • static: before any object of the class is created. when the variable is declared, or in a static initializer(static block)
  5. Random

  6. Wrapper class

    • used when a variable of a primitive type need to be treated as an object
  • final class

  • wrapping:

    1
    Integer a = new Integer(10);
  • unwrapping

    1
    int una = a.intValue();
  • autoboxing: automatic wrapping

  • usage:

    • method arguments
    • return values
    • boolean expressions
    • operations
    • assignments
  • parse methods

    • parseInt(), parseDouble(), .booleanValue()
  1. Recursion

    • base case
    • call itself

Strings

  1. Strings are immutable

  2. String Pool

    • where String literals are put

      • GC doesn’t cleanup the String Pool
  3. String Buffer & String Builder

    • used for variable strings

      • String Builder: not synchronous
  4. StringTokenizer

    • breaks string into several pieces

      • default delimiter: space, tab, new line, carriage return

      • if you set a delimiter parameter “au”, “a” and “u” are two separate delimiters.

      • token: the substring that a string splits into.

      • delimiter: the character that used to separate a string

  5. Scanner

    • useDelimiter(String str) will take whole str as a delimiter which is different from split
  6. Format Specifier

Block 4

GUI

  1. what is GUI?

    • Method for interacting with a computer
    • Widgets: Things you can put in a window(Component)
  2. 3 main concepts?

    • Component: the thing user interacts with
    • Container: the thing holds all components(Containers may contain containers)
    • Event: the action user triggers
  3. how to create a basic GUI?

    extending the “JFrame” class is more common

    eg1.

    1
    2
    3
    4
    5
    6
    7
    JFrame aFrame= new JFrame("a Title");
    aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    aFrame.setTitle("Some Name");
    JButton aButton= new JButton("Click!");
    aFrame.getContentPane().add(aButton);
    aFrame.setSize(100,100);
    aFrame.setVisible(true);

    eg2.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    public class GUIex1 implements ActionListener {
    JButton myButton;
    public static void main(String[] args) {
    GUIex1 a=new GUIex1();
    a.createAGUI();
    }

    public void createAGUI(){
    JFrame jFrame=new JFrame("aGUI");
    jFrame.setSize(300,300);
    myButton=new JButton("Hello");
    myButton.addActionListener(this);
    jFrame.add(myButton);
    jFrame.setLocationRelativeTo(null);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
    if(e.getSource()==myButton) {
    if(myButton.getText()=="Hello"){
    myButton.setText("Bye");
    }else {
    myButton.setText("Hello");
    }
    }

    }
    }
  4. write an event handler

    1
    2
    3
    4
    5
    6
    public class MyClass implements ActionListener {
    someComponent.addActionListener(instanceOfMyClass);
    public void actionPerformed(ActionEvent e) {
    // code that reacts to the action ...
    }
    }
  5. Layout manager

    allow to format components on the screen

    • FlowLayOut
      • When you add components to the screen, they flow left to right (centered), based on the order added and the width of the screen.
      • If the screen is resized, the components’ flow will change based on the new width and height.
    • GridLayOutt
      • arranges components in rows or columns.
    • BorderLayOut
      • divides the screen into five fields. You can places containers or components at these fields.
    • JFrame default: BorderLayOut
    • JPanel default: FlowLayOut

Exception Handling

handle unusual conditions

  1. Exception Class Hierarchy

    Throwable{ Exception{ IOException, InterruptedException, RuntimeException{ ClassCastException, NullPointerException, …}}}

  2. try/catch, finally

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    try{
    //codes--protect statements
    //(1)may throw Exception1
    //(2)may throw Exception2
    //(3)may throw Exception3
    //(4)
    }catch(Exception1 e){
    //codes--report and recover the exception
    }catch(Exception2 e){
    //
    }finally{
    //codes--regardless of an exception is thrown
    }
    • if (2) throws an exception, (3)(4) will be skipped.

      the program will execute the second catch clause, and “finally” will be executed as well.

    • if no one throws an exception, catch clauses will be skipped.

      “finally” will be executed.

    • if codes in try block throws an exception that not declared in catch field, JVM will stop the execution.

    • Exception2 cannot be a subclass of Exception1

  3. Exception class

    • your own exception must extend “Exception”
  4. throws/throw

    • “throws” means a method wants client code to handle them. when there is a checked exception, “throws” tells user must handle this exception.
    • “throw” means the code throw an exception in this case
  5. Stack Trace Messages

  6. RuntimeException

    • unchecked type-- not be checked by compiler
    • eg. NullPointerException, IndexOutOfBoundsException, ArithmeticException
  7. Assertions

    expression that must be true

    1
    2
    assert i==1;
    assert (a>0) : "a<=0";//if expression is false, an exception will be thrown with an message
    • cmd:

      -ea: enable your program to run with assertions

      -da: disable your program from running with assertions

    • assert throws AssertionError(extends Error)

File I/O

saving data permanently.

  1. I/O

    input/output-- bring in/ send out, reading/ writing

  2. Streams

    connection to source or destination of data

    • byte

      machine-formatted data

      • InputStream
      • OutputStream
    • character

      human-readable data

      • Reader
      • Writer
  3. Read a text file

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import java.io.*

    String aFile= "hello.txt";
    String contents="";
    try{
    FileReader fileReader = new FileReader(aFile);//a lot of methods in these two class has checked exception to be thrown.
    BufferedReader bufferedReader = new BufferedReader(fileReader);//efficient, useful methods
    String aLine = bufferedReader.readLine();
    while (aLine != null) {
    contents = contents + aLine;
    aLine = bufferedReader.readLine();
    }
    bufferedReader.close();
    fileReader.close();
    }catch (IOException e) {
    System.out.println("Errors occured");
    System.exit(1);
    }
  4. Write a text file

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    import java.io.*

    String[] str=new String[3];
    for(int i=0;i<str.length;i++){
    str[i]=""+i;
    }
    File file=new File("hello.txt");
    try{
    FileWriter fileWriter=new FileWriter(file);
    BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
    for (int i=0;i< str.length;i++){
    bufferedWriter.write(str[i]);
    bufferedWriter.newLine();
    }
    bufferedWriter.close();
    fileWriter.close();
    }catch (IOException e){y
    System.out.println("there is an error");
    System.exit(1);
    }

Collections & Sorting

collection of data

  1. Set/ List/ Map

    • Set: no duplicate elements
    • List: elements can be accessed by position
    • Map: no duplicate keys, each key has only one value
  2. Enumerations

  3. Iterator

    • boolean hasNext()
    • Object next()
  4. 2-dimensional Arrays

    • how to create a 2D arrays

      1
      2
      3
      4
      int[][] matrix1=new int[3][3];
      //int[][] matrix2=new int[][]; illegal
      int[][] matrix3=new int[3][];// column can be omitted
      Object[][] matrix4=new Object[3][3]// an matrix of objects
  5. sorting

    • bubble sort
  6. comparable

    • int compareTo(Object)
      • 0 --equal
      • <0 --less
      • >0 --greater