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 1, Basics, I/O, Data Type

2017-05-18

Intro

Inheritance

class Person{
    int age;
    String name;
    void sayHi() {...}
}

class Student extends Person {
    String school;
    double score;
    void meetTeacher() {...}
}

Polymorphism

Different objects with the same method can produce different outcomes.

foo(Person p) { p.sayHi();}
foo(new Student();)
foo(new Teacher();)

Type of applications and Components

Types

  • Application
    • Independent
    • Conducted by JVM
  • Applet
    • Embedded in HTML
    • Dependent
    • Conducted by appletViewer or Web browser (JVM)
public class HelloWorldApp{
    public static void main (String args[]) }
        System.out.println("Hello")
    }
}
  • System.print
  • System.println: output and newline
  • System.printf: format

Components

Hello.java

  • package statement (0 or 1)
  • import (0 or multi)
    • Import other classes
  • class def (1 or multi)
    • only one public class in a file (name should be the same as file)

Class

  • Class = class header + body
  • Class member = field + method
    • field: properties, represented by variables
    • method: by functions
  • method = method header + body
package edu.pku.tds.ch02;

import java.util.*;

public class Hello{}

Compile and run

javac Hello.java
javac *.java    // compile all
java Hello      // run class

// applet
javac HelloApplet.java
appletViewer helloApplet.html

Path and classpath

  • path : the path to commands (javac, java)
  • classpath: the path to quoted classes

Set:

  • cmd
    set path = .;c\jdk\bin;...
    
  • In system environment variables

Use classpath in CLI:

javac -cp libxx.jar Name.java
java -cp libxx.jar Name

Other tools

  • javaw: graphic interface
  • jar: archive tool
  • javadoc: generate doc
  • javap: look up class info and back-compile

Archive

javac A.java
jar cvfm A.jar A.man A.class

Doc

javadoc -d dir xxx.java

In code, put:

/**
* ... put comments here
*/
  • @author
  • @version
  • @see :other class
  • @param
  • @return
  • @exception

Java doc

javap

javap ClassName
// back-compile
javap -c ClassName

I/O

Scanner class

Use java.util.Scanner class

  • nextInt()
  • nextDouble()
  • next() get next word
import java.util.Scanner;
class ScannerTest{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please type an integer:");
        int a = scanner.nextInt();
        System.out.printf("The square of %d is %d \n",a,a*a);
    }
}

Previous solution

char c = ' ';
System.out.print("Please type a char:");
try{
    c = (char) System.in.read();
}catch(IOException e){}
System.out.println("You entered: "+ c);

Input a line:

try{
    BufferedReader in = new BufferedReader(
        new InputStreamReader( System.in)
    );
    s = in.readLine();
}catch(IOException e){}

Parse input to number:

BufferedReader in = new BufferedReader(
        new InputStreamReader( System.in)
    );
System.out.print("Please input an int: ");
s = in.readLine();
n = Integer.parseInt(s);
d = Double.parseDouble(s);

Graphic Interface I/O

  • Textfield: get data
  • Label: output data
  • Button: conduct cmd
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AppGraphInOut
{
    public static void main( String args[])
    {
        new AppFrame();
    }
}

class AppFrame extends JFrame
{
    JTextField in = new JTextField(10);
    JButton btn = new JButton("Action submit");
    JLabel out = new JLabel("label for output");

    public AppFrame()
    {
        setLayout( new FlowLayout() );
        getContentPane().add ( in );
        getContentPane().add( btn );
        getContentPane().add( out );
        btn.addActionListener( new BtnActionAdapter() );
        // will conduct the action
        setSize( 400,100 );
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);     //close the window
        setVisible(true);
    }

    class BtnActionAdapter implements ActionListener
    {
        public void actionPerformed( ActionEvent e )
        {
            String s = in.getText();
            double d = Double.parseDouble( s );
            double sq = Math.sqrt(d);
            out.setText( d+ "'s sqrt is: " + sq );
        }
    }

In Java 8, it can be simplified.

// e->{...}

btn.addActionListener( e->{
    String s = in.getText();
    double d = Double.parseDouble( s );
    double sq = Math.sqrt(d);
    out.setText( d+ "'s sqrt is: " + sq );
});

IDE

Snipplet

Eclipse:

  • main, then Alt+/, get main func
  • sysout, then Alt+/, get `System.out.println(“”);

Data type

  • Primitive types
    • num
      • int: byte(1b), short(2b), int(4b), long(8b, long lo = 3L;)
        • int a=0b1100; binary
      • float: float(4b), double(8b), must have .
    • char: (2b),Unicode, char c = 'A';, char c = '\n';
    • boolean: cannot use number for true or false
  • Reference types
    • class
    • interface
    • array
  • Primitive types
    • variables in stack
    • copy value double d2 = d;
  • Reference types
    • variables in heap (like pointer)
    • copy reference Person p2 = p;

Identifier

  • Case sensitive
  • Class name should be capitalized (Pascal)
  • other (package, method, variable) (camel)
  • less _
  • Variables are defined upon usage, not all on top.

Operator

  • Arithmetic: +, -, *, /, %, ++, -- (^ is not power)
  • Relation: >, <, >=, !=,..
  • Logic: !, &, |, ^, &&, || (^: XOR)
  • Bit: &, |, ^, ~, >>, <<, >>> (byte, short, int, char, long)
    • a<<b: (like *2) move binary number a to the left by b bits; low bits are compensated with 0
    • a>>b: (like /2) move binary number a to the right by b bits; high bits are compensated with original sign
      • For int, first get mod(b,32)
      • For long, get mod(b,64)
    • a>>>b: (like unsigned number) move binary number a to the right by b bits; high bits are compensated with 0
  • Assign: =, +=, -=, *=, /=
    • casting: long l = 100; int i = (int) l;
  • str cat: +

Control flow

If, switch

if (...)
    ...;
else
    ...;
  • variable type should be int, char or string
  • case + const variable
  • break;
switch(exp){
    case const1:
        statement1;
        break;
    ...
    [default:
        statement_default;
        break;]
}

Loop

For loop

for (init_statement; test_exp; alter_statement) {
    body_statement
}

int result = 0;
for (int i = 0; i<= 100; i++) {
    result += i;
}

While

int result = 0;
int i = 1;
while (i<=100) {
    result += i;
    i++;
}

Do while

int result = 0, int i = 1;
do {
    result += i;
    i++;
} while(i<=100);

Break & Continue

label1: {...
    label2: {...
        label3: {...
                        break label2; (stop executing label2)
        }
    }
}


outer: for (int i = 101; i<200, i+=2) {
    for (int j = 2; j<i; j++){
        if (i%j==0)
            continue outer;
    }
}

Array

int[] a, b, c;
int a[],b;  // b is not array
double []b;
Mydate []c;

Need to separate definition and allocation

int []a = new int[3];
// all elements will be assigned to be zero; reference type will be null
a[0] = 3;
a[1] = 1;
a[2] = 4;

//
int[] a = {3,9,8};
// or
int[] a = new int[]{3,9,8};

Mydate []dates = new MyDate[3];
dates[0] = new MyDate(22,7,1964);
//...

Length of array

int[] ages = new int[10];
for (int i=0; i<ages.length; i++)
{
    //
}

Enhanced for, read-only

// enhanced for, read-only
for (int age : ages) {
    ...
}

Array copy

int[] source = {1,2,3,4};
int []dest = {1,2,3,4,5,6};
// copy source array from index 0, source.Length elements to destination array
// store starting from index 1
Array.Copy(source,0,dest,1,source.Length)

2D array

int [][] t = new int [3][];
t[0] = new int[2];
t[1] = new int[4];
t[2] = new int[3];

// illegal
int t1[][] = new int[][4];

Example

class Pick7from36 {
    public static void main(String[] args) {
        int n = 7;
        int t = 36;
        int a[] = new int[n];
        for (int i = 0; i < n; i++){
            one_num:
            while (true)
            {
                a[i] = (int)(Math.random()*36) + 1;
                for (int j = 0; j < i; j++) {
                    if (a[i] == a[j])
                        continue one_num;
                }
                break;
            }
        }
        for (int num : a) System.print( num+" ");
        System.out.println();
    }
}
class Prime10000
{
    public static void main(String [] args)
    {   
        int start = 2;
        int end = 10000;
        int len = end - start + 1;
        int[] a = new int[len];
        for (int i = 0; i<len; i++) a[i] = i+start;
        int divideEnd = (int)(Math.sqrt(end)) + 1;
        int[] divisors = new int[divideEnd - start + 1];
        for (int i = 0; i < divideEnd - start + 1; i++)
        {
            divisors[i] = i + start;
        }
        for (int divisor : divisors)
        {
            for (int i = 0; i<a.length; i++) {
                if ( a[i] != -1 && a[i] != divisor && a[i]%divisor == 0)
                {
                    a[i] = -1;
                }
            }
        }
        for (int num : a)
        {
            if (num != -1)
                System.out.println(num);
        }
    }
}

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