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 newlineSystem.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
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
, thenAlt+/
, get main funcsysout
, thenAlt+/
, 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
.
- int: byte(1b), short(2b), int(4b), long(8b,
- char: (2b),Unicode,
char c = 'A';
,char c = '\n';
- boolean: cannot use number for true or false
- num
- 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 0a>>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;
- casting:
- str cat:
+
Control flow
If, switch
if (...)
...;
else
...;
- variable type should be int, char or string
case
+ const variablebreak;
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);
}
}
}