Public speaking course notes Read "Dynamo, Amazon’s Highly Available Key-value Store" Read "Bigtable, A Distributed Storage System for Structured Data" Read "Streaming Systems" 3, Watermarks Read "Streaming Systems" 1&2, Streaming 101 Read "F1, a distributed SQL database that scales" Read "Zanzibar, Google’s Consistent, Global Authorization System" Read "Spanner, Google's Globally-Distributed Database" Read "Designing Data-intensive applications" 12, The Future of Data Systems IOS development with Swift Read "Designing Data-intensive applications" 10&11, Batch and Stream Processing Read "Designing Data-intensive applications" 9, Consistency and Consensus Read "Designing Data-intensive applications" 8, Distributed System Troubles Read "Designing Data-intensive applications" 7, Transactions Read "Designing Data-intensive applications" 6, Partitioning Read "Designing Data-intensive applications" 5, Replication Read "Designing Data-intensive applications" 3&4, Storage, Retrieval, Encoding Read "Designing Data-intensive applications" 1&2, Foundation of Data Systems Three cases of binary search TAMU Operating System 2 Memory Management TAMU Operating System 1 Introduction Overview in cloud computing 2 TAMU Operating System 7 Virtualization TAMU Operating System 6 File System TAMU Operating System 5 I/O and Disk Management TAMU Operating System 4 Synchronization TAMU Operating System 3 Concurrency and Threading TAMU Computer Networks 5 Data Link Layer TAMU Computer Networks 4 Network Layer TAMU Computer Networks 3 Transport Layer TAMU Computer Networks 2 Application Layer TAMU Computer Networks 1 Introduction Overview in distributed systems and cloud computing 1 A well-optimized Union-Find implementation, in Java A heap implementation supporting deletion TAMU Advanced Algorithms 3, Maximum Bandwidth Path (Dijkstra, MST, Linear) TAMU Advanced Algorithms 2, B+ tree and Segment Intersection TAMU Advanced Algorithms 1, BST, 2-3 Tree and Heap TAMU AI, Searching problems Factorization Machine and Field-aware Factorization Machine for CTR prediction TAMU Neural Network 10 Information-Theoretic Models TAMU Neural Network 9 Principal Component Analysis TAMU Neural Network 8 Neurodynamics TAMU Neural Network 7 Self-Organizing Maps TAMU Neural Network 6 Deep Learning Overview TAMU Neural Network 5 Radial-Basis Function Networks TAMU Neural Network 4 Multi-Layer Perceptrons TAMU Neural Network 3 Single-Layer Perceptrons Princeton Algorithms P1W6 Hash Tables & Symbol Table Applications Stanford ML 11 Application Example Photo OCR Stanford ML 10 Large Scale Machine Learning Stanford ML 9 Anomaly Detection and Recommender Systems Stanford ML 8 Clustering & Principal Component Analysis Princeton Algorithms P1W5 Balanced Search Trees TAMU Neural Network 2 Learning Processes TAMU Neural Network 1 Introduction Stanford ML 7 Support Vector Machine Stanford ML 6 Evaluate Algorithms Princeton Algorithms P1W4 Priority Queues and Symbol Tables Stanford ML 5 Neural Networks Learning Princeton Algorithms P1W3 Mergesort and Quicksort Stanford ML 4 Neural Networks Basics Princeton Algorithms P1W2 Stack and Queue, Basic Sorts Stanford ML 3 Classification Problems Stanford ML 2 Multivariate Regression and Normal Equation Princeton Algorithms P1W1 Union and Find Stanford ML 1 Introduction and Parameter Learning

Java Programming 3, Deeper Understanding, Exception

2017-05-20

Deeper understanding

Variable

  • field:
    • a part of object,
    • saved in heap
    • assigned value automatically
    • public, private, static, final
  • local var:
    • in method
    • stored in stack
    • must be assigned value explicitly
    • cannot use access modifiers and static
    • can be final
  • primitive type
    • int, String
    • pass value
  • reference type
    • class, interface, array
    • pass ref

Return

  • Return primitive type
  • Return ref type
Object getNewObject()
{
    Object obj = new Object();
    return obj;
}

Object p = getNewObject();

Polymorphism

  • While compiling
    • overload (different methods with the same name)
    • e.g. p.sayHello() and p.sayHello("Wang")
  • While running
    • override (subclass overrides the superclass method)
    • dynamic binding, or called virtual method invoking
      • For all non final methods
    • Program will use subclass method correctly
    • Will call the method belonging to that instance (Student instead of Person)

Upcasting

  • Treat subclass as superclass
  • Person p = new Student();
  • void fun(Person p){...} and fun(new Student());

instanceof

  • instanceof determines whether an object is an instance of a class
  • Return a boolean
  • if a instanceof Integer

non-virtual methods

  • normal methods are virtual methods (depending on the objects)
  • static, private are not virtual method
    • static is class method, not instance
    • Subclass cannot see private methods
  • static: based on the declared type, unrelated to the object type
    • Shape s = new Circle()
    • s.draw(); will call the static method draw of class Shape
  • private: Subclass cannot see.
  • final: Subclass cannot override it.

Constructor and initialization

  • this call the constructor of this class
  • super call the constructor of superclass
  • this or super must be the first statement, and only one
    • If none, compiler will add super() automatically

Initialization

p = new Person(){
    {
        age = 18; name = "Jack";
    }
};
  • Assign values to fields
  • Double { { } }

Instance Initializers

  • {...} in class will be conducted before constructor {...}
  • static {...} in class will be conducted before {...}

Constructor

  1. Call this or super constructor until the highest (Object)
  2. Assign values to fields
  3. Conduct following statements in constructor

Garbage deletion and collection

  • Do the garbage collection: System.gc()
  • finalize() will release system resources
    • protected void finalize() throw Throwable{}
    • Subclass finalize() should call superclass finalized()

Close file and clean

For java.lang.AutoCloseable object, will call close()

try (Scanner scanner = new Scanner(...)){
    ...
}

Inner class and anonymous class

  • Inner class
    • put class definition inside a class
    • Name must be different with outer class
    • Simple usage inside the outer class
    • Other place: outerClassName.innerClassName xx = outerObjectName.new innerClassName
    • Inside inner class outerClassName.this.field
  • Anonymous class

Lambda expression

  • Like an interface
  • (params) ->(result)
  • An instance of anonymous class
  • only one function inside
  • Interface
    • @FunctionalInterface
    • interface Fun {double fun( double x);}

Example

  • (String s) -> s.length()
  • x -> x*x
  • () -> {System.out.println("aaa");}
  • new Thread(()-> System.out.println("aaa")).start();
  • Integral: double d = Integral(x->Math.sin(x),0,Math.PI,1e-5);
    • interface Fun {double fun( double x);}
    • double d = Integral(new Fun(){public double fun(double x){return Math.sin(x);}},0,Math.PI,1e-5);
  • Sort: Comparator<Person> compareAge = (p1,p2) -> p1.age-p2.age; Array.sort(people,compareAge);
    • Array.sort(people, (p1,p2)->(int) (p1.score-p2.score));
    • Array.sort(people, (p1,p2)-> p1.name.compareTo(p2.name));

New syntax

primitive type to Object (ref type)

  • int to Integer
  • 8 in total
    • Boolean
    • Byte, Short, Integer, Long, Float, Double
    • Character
  • Integer I = new Integer(10);

Easier

  • Boxing: Integer I = 10;
  • Unboxing: int i = I;
  • For array: Object[] ary = {1,"aaa"};
    • 1 will be automatically converted.

enum

Can add fields, methods, constructor

Example

  • enum Light {R,L,Y};
  • Light l = Light.R;
enum Direction
{
    EAST("E",1), SOUTH("S",2),
    WEST("W",3), NORTH("N",4);
    private Direction(String desc, int num){
    this.desc=desc; this.num=num;
    }
    private String desc;
    private int num;
    public String getDesc(){ return desc; }
    public int getNum(){ return num; }
}

Annotation

  • Not comment
  • Subclass of java.lang.annotation.Annotation

Example

  • @override
  • @Deprecated: outdated method
  • @SuppressWarnings: No warning while compiling

Reference and pointer

References are safe pointers

  1. Pass address -> object (ref type)
  2. Pointer operation -> array
  3. Function pointer -> interface, Lambda expression
  4. Pointer to node -> reference of objects
  5. Use JNI
    • Interface with other lang

Equal or not equal

  • Primitive: value
    • Compare after conversion (int and float)
    • Don’t use == for float
      • Double.NAN == Double.NAN is false
    • Cannot compare boolean with int
    • -128 to 127: 2 boxing int will equal to each other
  • enum
    • Do single instantiation inside, can estimate directly
  • Reference: ref
    • Whether two ref are the same
    • If need to estimate whether contents are the same: override equals method
    • If need to override equals method: better override hashCode()
  • String (ref type)
    • Need to use equals method, not ==
    • Constant String literal can use ==
      • String hello = "Hello";: true
        • hello == new String("Hello");: false
      • "String lo = "lo";
        • "Hel"+lo is not constant
        • "Hel"+"lo" is a constant
        • ("Hel"+lo).intern()) is constant

Exception

throw exceptionObject;

try{

} catch(ExceptionClassName FormParamsName){

}catch(IndexOutOfBoundsException ex){

}catch(IOException ex){

}catch(NumberFormatException ex){

}finally {

}

Exception class

Constructor

  • public Exception();
  • public Exception(String message);
  • Exception(String message, Throwable cause);

Method

  • getMessage()
  • getCause()
  • printStackTrace()

Checked exception

  • RuntimeException and subclass don’t need to be dealt with.
    • IndexOutOfBoundsException
  • Checked exception must be dealt with
    • catch or
    • throws
    • If a method in superclass declared throws exception, the subclass overriding that method must throws exception (a more specific one)
public static void readFile()throws IOException {

}

A compiler sugar:

try(Type varName = new Type()){

}
// finally{var.close();} will be added automatically

Pass exception

  • Throw it again: throw e;
  • Generate a new exception and throw it
    • throw new Exception("some msg");
  • Generate a new exception and throw it with current exception
    • throw new Exception("some msg",e);
    • get inner exception with e.getCause()

User-defined exception

class DataHouseException extends Exception {
    public DataHouseException( String message){
        super(message);
    }
}

class AppException extends Exception {
    public AppException( String message){
        super(message);
    }
    public AppException( String message, Exception cause){
        super(message,cause);
    }
}

Assertion and Test

assert expression;
assert expression: msg;

Example:

class Assertion {
    public static void main(String[] args) {
        assert hypotenuse(3,4) == 5 : "incorrect";
    }

    static double hypotenuse(double x, double y) {
        return Math.sqrt( x*x +y*y);
    }
}

Usage

java -ea -classpath .Assertion

Test

Use JUnit

Eclipse:

  • project, right click __ new __ Junit Test case
  • project, right click __ Run as __ Junit Test

In test file

public class testHello1 {

    @Test
    public void testSum1() {
        HelloWorld a = new HelloWorld();
        assertEquals(a.sum(1,2), 3);
        assertNull(params);
        fail("message");
    }
}

Error

  • Syntax error
  • Runtime error
  • Logic error
    • debug
    • unit test

In IDE, right click project, debug as to debug perspective

3 tools

  • breakpoint, Ctrl+Shift+B
  • trace
    • conduct line by line: F5
    • conduct step over (not into functions): F6
    • jump out functions: F7
    • conduct to cursor: Ctrl + R
  • watch
    • Mouse
    • Quick: right click, Inspector
    • Add: right click, Watch

Creative Commons License
Melon blog is created by melonskin. This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
© 2016-2024. All rights reserved by melonskin. Powered by Jekyll.