JAVA NOTE

[TOC]

Teaching Block1

1.phase of java program

phase1: Edit(by editor ): Every java program have the extensing .java

phase2: Compile(编译器):

translates your program into bytecode so that the Java interpreter can read the program(MyProgram.class)

javac Myprogram.java

Phase 3: Load + Phase 4: Verify

loading into memory

java MyProgram

Phase 5: Execute

The file name and the class name must be the same.

MyProgram.java

To compile the program, type (with file extension编译时加后缀):

javac MyProgram.java

To run the program, type (without file extension运行不加后缀):

java MyProgram

The interpreter executes main first.

JVM包括:

javac: compiler

java: launcher for Java applications

javadoc: API documentation generator

jar: manages JAR files

jdb: Java debugger

1.1.补充1.常见dos命令

1.2.补充2.main method

2.Basic data types(基本数据类型、引用数据类型)

2.1.introduction

Java is strongly typed and strongly classed– Only variables with the same types or classes can be used together.

Every data type in Java has a default value

long类型在数字后面加L否则整数默认为int类型

float 加F 否则小数默认为 double类型

2.2.补充1.变量命名规则

2.3.补充2.类型转换

自动类型转换:范围小的数赋值给范围大的数

强制类型转化(type cast operator.) :范围大的数赋值给范围小的数

int k=(int)88.8

Conversion between numeric types:

byte => short => int => long => float => double

3.Operators

3.1.introduction

  • Increments and Decrements

java1/image-20220602155541419

– A post operation causes the variable to first be used in the current statement, and then it is incremented or decremented afterwards.

– A pre operation causes the variable to first be incremented or decremented, and then it is used in the current statement.

Post incrementing

int a = 4;
int result = a++ + a;
System.out.println("result = " + result + ", a = " + a ); 
OUTPUT:
result=9 a=5

a = 4;
result = a + a++;
System.out.println("result = " + result + ", a = " + a );
OUTPUT:
result=8 a=5

Pre incrementing

int a = 4;
int result = ++a + a;
System.out.println("result = " + result + ", a = " + a ); 
OUTPUT:
result=10 a=5

a = 4;
result = a + ++a;
System.out.println("result = " + result + ", a = " + a ); 
OUTPUT:
result=9 a=5
  • Operator Precedence(优先级)

java1/image-20220602155603848

  • Relational Operations

  • Logical operators

image-20220602155715737

– binary operators (except assignment) are evaluated from left to right

– assignment operators are evaluated right to left

int a = 4;
int b = 1;
int c = 3;
int result = a = b = c;
a/b/c都为3
  • if-else statement

    Relational expression must evaluate to a boolean value

    java1/image-20220602155736411

  • switch statement

java1/image-20220602155809690

break – causes the remainder of the **switch **statement to be skipped

default – action in case none of the cases match

  • Conditional Operator

image-20221226201632395

  • The break and continue statements

​ break——quitting the loop

​ continue——skipping the current iteration

​ 补充:Using labelled statement blocks with break and continue

outer:
    for (int i=1; i<5; i++) {
      System.out.println("Begin outer for i=" + i); 
inner:
      for (int j=1; j<5; j++) {
        if (j == i) break outer;
      }
      }
outer:
   for (int i=1; i<5; i++) {
     System.out.println("Begin outer for i=" + i); 
inner:
     for (int j=1; j<5; j++) {
       if (j == i) continue;
  System.out.println("   inner: i=" + i + " j=" + j);
     }
     System.out.println("End outer for i=" + i); 
   } 

3.2.IDEA使用

  • 项目结构:模块-包-java类

java1/image-20220324132520475

  • 快捷键

java1/image-20220324132751831

java1/image-20220324132830940

4. OO programming and objects

4.1.introduction

  • What is OO programming?

Constructing software systems which are structured collections(or sets) of classes.

These classes produce instances called objects

  • What is object?

    Objects are things or nouns.

  • Attributes (or states) of an object:

    essentially anything that describes or quantifies an object.

  • Operations (or behaviours) of an object:

    they mostly correspond to verbs in a requirements specification.

The class defines the attributes and operations exposed by one or more related objects

  • What is a class?

​ An object is an instance of a particular class, We can split up code between different objects.

  • UML

    Class diagram notation

    UML = Unified Modelling Language

java1/image-20220324140254211

4.2.Methods

java1/image-20220324135119144

  • syntax
modifiers returnType methodName(parameters) {
statements;
}

java1/image-20220602155836944

A method uses parameters=形参(formal parameter), whereas the caller passes arguments=实参(actual parameter).

  • Calling(调用) a method

java1/image-20220324135158712

java1/image-20220602155849492

java1/image-20220324140705081

  • Pass-by-value(Pass-by-copy)

    在方法被调用时,实参通过形参把它的内容副本传入方法内部,此时形参接收到的内容是实参值的一个拷贝,因此在方法内对形参的任何操作,都仅仅是对这个副本的操作,不影响原始值的内容。

  • Method Overloading

    Java allows several methods to be defined with the same name, as long as they have different sets of parameters

    ==The return type is NOT used to differentiate methods==

    java1/image-20220324140852742

只有参数类型有关,与返回值类型无关

4.3.Create a class

instance variable(成员变量)+instance method(成员方法)+constructors(构造方法)

attribute——instance variable , operation——instance method

java1/image-20220324141950832

class XXX{
  int attribute1=1;
  double attribute2=2;
  //instance variable
   XXX(int xxx){   
    }
   //constructors
    
    double opeartion1(){   
    }
    int opeartion2(){  
    }
   //instance method
}
  • create a object
className objectName=new className();

A object is a reference variable.

  • Using instance variables and methods

– to access a (public) instance variable v of an object o, we reference it using the dot notation*:*

o.v

– to invoke a (public) method m of an object o, we also reference it using the dot notation:

o.m()
  • Constructors
    A constructor is a special method, with same name as the class name, used for initialisation.

It does not have a return type, not even void!

An empty no-argument constructor is provided for you by Java(如果没有自定义,系统会自带一个无参构造方法,如果自己写了构造方法,系统将不提供无参构造方法)。

java1/image-20220324143702216

public Cat() {

}
  • Data Encapsulation(对成员变量封装)

This is a good thing! Since objects are only accessible through well defined interfaces, ideally nothing unexpected should happen!

We should NOT allow direct access to an object’s variables.

Any changes to the object’s state (i.e. its variables) should be made ONLY by that object’s methods

把成员变量定义加private,并且添加两个method实现访问和更改变量

accessor(访问器):get方法——getXxx()

mutator(修改器):set方法——setXxx()

All getters and setters should have names that conform to the following:

==variableType getVariableName()==

==void setVariableName(VariableType)==

public void setAge(int age){
       this.age=age;
   }
 
public int getAge(){
       return age;
   }
  • this引用
    this 是指向对象本身的引用名,利用this引用对象的instance variable
public void setAge(int age){
      this.age=age;
  }

不加this指代parameters, 加this指代instance variable

补充:this()可以用来同类的另一个构造方法

Person(String nm) {
        name = nm;
    }
Person(String nm, int a) {
        this(nm);
        age = a;
    }
  • toString() method

    This method returns a String representation of the object.

    public String toString() {
    returnAccount number:+ accNo + “\n” 
    +Account name:+ accName + “\n”
    +Balance:+ balance ;
    }

    它通常只是为了方便输出,在main中需要输出class的变量时,直接使用:

    System.out.println(classname);

    等同于

    System.out.println(classname.toString);

4.4.Method parameters 、 local variables、instance variables

Method parameters are virtually the same as local variables!

– They are declared inside the method.

– They are valid (or in scope) only inside the method.

– They are NOT initialised to the default value, and so must be initialised(by the caller of the method).必须初始化

  • Initialisation(变量初始化)
    Java automatically sets some initial values for you for variables of the class (instance variables), but not for variables in methods(local variable)

java1/image-20220602155920027

class variable 也会自动初始化

Teaching Block2

1.Arrays

Arrays provide fast random access by letting you use an index position to get any element in the array.

Arrays must be given a size!

Standard arrays cannot grow and shrink in size

image-20221226201812505

静态初始化:

int[] arr={1,2,3};

动态初始化:

只指定数组的长度

  • An array is an object, even though it may be an array of primitives.

  • Array elements can be either primitives or objects.

  • The main() method has the Array of Strings.

public static void main(String[] args) 

数组的长度:array.length(是一个整形)

如果length=3 (length/2=1)注意在for循环里出现!

动态初始化一个对象数组时,new后面是类名(只是表示这个reference variable什么类型)并不是构造方法。

1.1.copy array

reference copy: Only copies the reference value!

Rabbit[] racers2;

racers2 = racers;

copy the data type variables:

  1. Use a loop to copy all individual elements.

  2. Use the static arraycopy method in the System class

java1/image-20220328203620636

src is the array to copy from; dest is the array to copy to

srcPos is where in the src array to start copying from.

destPos is where, in the dest array, to start putting the newly copied

elements

1.2.Passing Arrays to Methods

Java uses pass-by-value, to pass arguments to a method(only have pass by value)

Java passes (to the method) a copy of the reference variable to the array object

数组作为方法参数—传递地址

1.3.“Prep code”

A form of pseudocode, to help focus on the logic without the worry of syntax

2.String

java 中的所有双引号中都为字符串。

不是基本的数据类型。

  • string 特点:

    String对象不可变 Strings are immutable

    但是如下代码是可以执行的(因为“java”创建的是对象,“java”内容不能改变,但是下方代码意思是s这个引用类型的变量指向新的对象“html”)

String s="java";
s="html";

不能改变s的值

String Pool: Area of memory where String literals are put by the JVM when created

Garbage Collector doesn’t cleanup the String Pool!

JVM doesn’t create a duplicate if there’s already a String in memory with

the same value; it refers the reference variable to the existing entry

JVM不会创建相同值的string,只会使引用变量指向这个字符串

  • string构造方法:

    java1/image-20220602155938368

  • 两种创建字符串的方法以及内存分析:

    通过new创建对象,每次都会申请一个新的内存空间。

    以”“创建对象如果内容一样,则jvm只会创建一个String对象

    String st1=new String(ch2);
           String st2=new String(ch2);
           System.out.println(st1==st2);
       //new构建时,st1与st2地址不同
      
           String st3="abc";
           String st4="abc";
           System .out .println(st3==st4);
           //直接赋值时,st3与st4的地址相同
   //运行结果为true false
   String s1 = "AB";
   String s2 = "AB";
   String s3 = new String("AB");
    System.out.println(s1 == s2);
    System.out.println(s1 == s3);


由于常量池中不存在两个相同的对象,所以s1和s2都是指向JVM字符串常量池中的"AB"对象。new关键字一定会产生一个对象,并且这个对象存储在堆中。所以String s3 = new String(“AB”);产生了两个对象:保存在栈中的s3和保存堆中的String对象。

java1/image-20220602155952465

这是因为通过构造方法(new)创建字符串对象时,该对象位于heap上

而使用“”创建时,该字符串位于String Pool(通过+组合时也是如此)

java1/image-20220602160005972

GC不会清理String pool,但是可以清理new出的在堆中的string

Methods: String Class

  • 字符串的比较

java1/image-20220331213600524

string1.equals(string2)
  • 字符串相加:

    Java overloads the + operator for string concatenations.

System.out.println("aaa"+1+1);输出 aaa11
System.out.println("aaa"+(1+1));输出 aaa2
  • 字符串转字符

image-20220331214741862

  • 字符串长度

    java1/image-20220331214828665

    • char charAt(int index): returns the character at index

    • int indexOf(ch): returns ch’s first occurrence position; if not found returns -1.

      java1/image-20220511225550273

    • int compareTo(str): compares two strings, returns < ,> , =0 if the compared string is smaller, larger, or equal to str.

    • substring(index1,index2): returns the substring between index1and (excluding) index2.

    • concat(s): concatenates(连接) two strings.

    • toUpperCase() / toLowerCase(): convert all characters in string to upper/lower case

    • toString(): convert input to a string.

    • ```java
      double d = 12.3;
      String dString = Double.toString(d); // dString = “12.3”

      
        **void getChars(i,j,A,k)**: returns characters from **i** to **j** (excluding), and stores them into array* **A** starting from **A[k]**.
      
        
        
      - ```java
        char[] A = new char[4];
        “The rain in Spain”.getChars(4,8,A,0);
      // A = {’r’,’a’,’i’,’n’}

      substring(index): returns substring from index to end.

      String s =Monkeys.substring(3); // s = “keys”
      String s =Monkeys.substring(3,Monkeys.length()-1); 
      

// s = “key”

  
    replace(oldCh,newCh)**: replace **oldCh by **newCh** everywhere in the string.
  
    ```java
String s = “goose”.replace(‘o’,‘e’); //s = “geese”

  • split(String s): splits the string around matches of the given regular expression s and returns an array with those substrings

        public class UsingSplit {
        public static void main(String[] args) {
        String str = "bar:foo:bar";
        String[] splitStr = str.split(":");
        for (int i=0; i < splitStr.length; i++)
        System.out.println(splitStr[i];
    } }

    OUTPUT:

    bar

    foo

    bar

  • void getChars(i,j,A,k): returns characters from i to j (excluding), and stores them into array A starting from A[k]

  • substring(index): returns substring from index to end.

  • replace(oldCh,newCh): replace oldCh by newCh everywhere in the

    string

Format Specifier

The following table shows the format specifiers:

format() 函数与数字,字符结合使用:

^<> 分别是居中、左对齐、右对齐,后面带宽度

: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示数学中的正负号,在正数前显示+,负数前显示-; (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

java1/image-20220502165204192

Format Specifier Conversion Applied
%a %A Floating-point hexadecimal
%b %B Boolean
%c Character
%d Decimal integer
%h %H Hash code of the argument
%e %E Scientific notation
%f Decimal floating-point
%g %G Uses %e or %f, whichever is shorter
%o Octal integer
%n Inserts a newline character
%s %S String
%t %T Time and date
%x %X Integer hexadecimal
%% Inserts a % sign

format() 函数与参数结合使用

格式化字段将会被 format() 中的参数替换

print("我叫{},今年{}!".format("张三",22))
print("我叫{0},今年{1}!".format("张三",22))
print("我叫{1},今年{0}!".format("张三",22))
我叫张三,今年22!
我叫张三,今年22!
我叫22,今年张三!

StringTokenizer Class

The StringTokenizer class is used to extract tokens and process text from a string, and it belongs to the java.util package.

StringTokenizer is a legacy class; should not be used with new code,用 String.split()

3.StringBuilder

可变字符串

  • 构造方法

java1/image-20220331214451117

  • 添加和反转

    java1/image-20220331214902678

    java1/image-20220331214948952

    返回值是本身的类,所以可以链式编程

  • 与String的转换

    image-20220331215055566

4.ArrayList

ArrayList 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素。

ArrayList 类位于 java.util 包中,使用前需要引入它,语法格式如下:

import java.util.ArrayList; // 引入 ArrayList 类

ArrayList<E> objectName =new ArrayList<E>();  // 初始化

E: 泛型数据类型,用于设置 objectName 的数据类型,只能为引用数据类型

4.1.Some ArrayList methods

常用的method:

image-20221226202028926

java1/image-20220331210908240

Find out if it contains something:

boolean inIt = myList.contains(f);

Find out where in the list something is:

int index = myList.indexOf(f);

Find out if the list is empty:

boolean empty = myList.isEmpty();

ArrayList字符串遍历的基本格式:

java1/image-20220331211646251

5.Inheritance and Abstract classes

5.1.two primary types of relationships between classes

– aggregation (referred as has-a)

– inheritance (referred as is-a)

5.2.Inheritance

via the extends keyword

java1/image-20220602160040255

Subclasses inherit the properties (attributes and operations(方法和成员变量)) of their superclass.

java1/image-20220602160049960

To provide specialisations, subclasses ==override== methods that they inherit from the superclass

父类的私有数据域在子类中仍是不能访问的。java中只支持单一继承。

构造方法不会被继承

Access Modifiers(可访问修饰符)

java1/image-20220405151242251

  • public

public instance variables and methods are inherited

protected

protected instance variables and methods are inherited

private

– any private instance variables and methods

are not inherited and cannot be seen by the subclass

default: 不加任何修饰符

方法、变量四种都可以加

普通类(外部类):只能用public、default(不写)、abstract、final修饰。

(成员)内部类:可理解为外部类的成员,所以修饰类成员的public、protected、default、private、static等关键字都能使用。

5.2.1.override

要与父类方法声明一模一样

java1/image-20220405145140022

方法重写时建议加注解@Override以区分是否为重写还是新子类方法

java1/image-20220405145224830

java1/image-20220405145331663

5.2.2.super的使用

Every object holds both its own declared instance variables and everything from its superclasses.

super用于指代父类,可以调用父类中的普通方法和构造方法

调用普通方法类似于this的语法:super.方法名(参数);

调用父类的构造方法

java1/image-20220405153854142

每个子类构造方法执行的==第一步==都为隐式调用(先访问父类的无参构造方法)所以每个父类一定要重载无参构造方法。if no constructor is provided, the compiler adds one that looks like:

public ClassName() { super(); }

this指本类,super指代父类。

java1/image-20220602160107277

5.2.3.成员方法访问的特点

java1/image-20220602160116092

5.2.4.final和static关键字
  • final可以修饰方法、变量、类

java1/image-20220602160124588

Using this keyword will prevent child classes (oranyone else) modifying the variable/method this applies to

final修饰的变量必须初始化(常量),不能被改变。

在使用final修饰基本类型变量的时候,不可以对基本类型变量重新赋值,所以的话,基本类型变量不能被改变,可是对于引用类型变量来说的话,它保存的仅仅是一个引用,final只保证这个引用类型变量所引用的地址不会改变,也就是一直引用同一个对象,但这个对象完全可以发生改变。

如果final修饰数组那么数组的内容可以改变,但是不能重新为这个reference variable分配新数组对象了

final variables must either be initialised when declared or in the constructor

java1/image-20220602160137226

public static int a;

任意一个对象给a赋值之后所有对象共享a的值。

All instances of the same class share one copy of an static variable.

Initialisation of static variables happens before any object of the class

is created

一般对static修饰的变量访问时使用

类名.变量名=xxxx;

类名.方法名()

使用类名对此变量统一赋值。

static修饰方法:(静态方法可以被继承,不能被重写)

java1/image-20220602160147324

Static Imports(调用方法时不用写类名了)

import static java.lang.System.out;

import static java.lang.Math.;

class WithStaticImports {

public static void main(String [] args) {

out.println(“square root is “ + sqrt(4.0));

} 

}
修饰符 修饰变量 修饰方法 修饰类
static 整个类都可以访问,直接用类名访问 静态方法,不可被重写 \
final 不可更改(常量) 不能被重写 最终类,不可被继承

6.polymorphism

Polymorphism :Using a single definition (superclass) with different types (subclass)

(父类变量指向子类对象)

Creature c = new Rabbit();
object o=new student();

其中object是o的声明类,student是o的实际类,o调用方法时由实际类型决定。

访问时要先看左边(声明类)中有无此变量或对象,如果有才可以执行。

执行方法时执行的是右边(实际类)的重写方法,执行变量时是执行声明类中的变量。

多态中的对象转换:

java1/image-20220602160247779

向上转型

object o=new student();

向下转换(强制)– Explicit cast

student b=(student)o;

6.1.java的object类中常用方法:

java.lang.Object is the ultimate parent of EVERY class in java

Some methods of the “object” class

equals() determines when one object is equal to another

未重写:判断两类的地址是否相同

在类中重写equals()判断两个类内容是否相等。

toString() allows objects to be printed

输出:类名@加地址

重写toString()打印类中信息

hashCode() is a unique ID for every object, usually based on its memory address

getClass() returns the class of the object返回类名

7.abstract class

The compiler will not let you instantiate an abstract class.

– The only use it has is in being extended

A non-abstract class is called a concrete class.

abstract in terms of classes that class must be extended, in

order to be instantiated

abstract for methods the method must be overridden in the

child class

subclass must implement ALL abstract methods from its superclass (or be declared abstract).

java1/image-20220602160301686

抽象方法:

public abstract void eat();

java1/image-20220602160309267

java1/image-20220602160318509

8.inner class

  • Inner (or Nested) Class: Standard class declared within the scope of a standard top-level (or enclosing) class

java1/image-20220602160331304

  • An inner class is defined in the scope of an outer class.

(An instance of) it can reference data and methods (even private ones) of the outer class it belongs to.

java1/image-20220602160346623

java1/image-20220602160359496

java1/image-20220602160408113

  • An instance of an inner class (i.e. an inner object) must be associated with a specific outer object on the heap!

java1/image-20220602160422782

java1/image-20220602160435539

An anonymous class is a special kind of class: a local class without a name.

java1/image-20220602160447672

• only one instance of the class can ever be made;

• class can’t be accessed from anywhere else in the program

It allows an object to be created using an expression that combines object creation with the declaration of the class.

An anonymous class is defined as part of a new expression and mustbe a subclass or implement an interface.(必须是子类或者接口的实现)

– The class body can define methods but cannot define any constructors.

java1/image-20220602160513949

匿名内部类,在【创建对象】的时候,只能使⽤唯⼀⼀次。

如果希望多次创建对象,⽽且类的内容⼀样的话,那么就需要使⽤单独定义的实现类了。

匿名对象,在【调⽤⽅法】的时候,只能调⽤唯⼀⼀次。

如果希望同⼀个对象,调⽤多次⽅法,那么必须给对象起个名字。

匿名内部类是省略了【实现类/⼦类名称】,但是匿名对象是省略了【对象名称】

强调:匿名内部类和匿名对象不是⼀回事!!!

9.Debugger

Compilation or syntactical errors: easiest type of error to debug

Logic errors: occur during the program’s execution.

runtime errors & threading errors

Teaching Block3

1.interface

接口是一种与类类似的结构,只能包含常量和抽象方法。

无构造方法

  • Before Java SE8, interfaces could have:
  • static final 位置可换!!

constant fields (public static final可以省略)(引用时使用父类接口作为前缀Father.age)

public static final int x = 10;

abstract methods (public abstract可以省略)

public abstract void doStuff();
  • From Java SE8, interfaces can also have:

default methods Allow developers to add new functionality to interfaces, without impacting any existing classes that are already implementing the interface.用了default关键字修饰方法之后,这个方法是可以有方法体

==Can be overridden in the class that implements the interface.==Provide backward compatibility(向后兼容) for existing interfaces.

static methods Allow developers to define utility methods in the interface也可以具有方法体(不可被重写)与类中加static一样均可用 接口名.方法名 调用

java1/image-20220602160537759

接口中

public interface name(){}

类实现:

public class className implements interfaceName{}

java1/image-20220416114202044

接口不能利用new实例化,所以必须通过类继承接口后,实例化类间接实现接口实例化

java1/image-20220602160610929

Java’s “multiple inheritance” is at interface level only!(可以利用接口实现Java中的多继承)

public class className implements A,B{}

Only interfaces can do multiple inheritance

java1/image-20220602160619631

java1/image-20220602160627123

多继承中如果发生两个父类有相同方法:

  • Same named methods:

    If they have different parameters, then Child interface has both (this is same as overloading).

​ If they differ by only return type, then error.

​ If the two methods are identical, only keep one.

  • Same named constants:

    we keep both constants. To refer to them, use parent interface name as prefix

2.Garbage Collection

  • Two main areas of memory in Java:

– (Garbage-collectible) Heap (where objects live);

– Stack (where local variables and methods, when called, live)

2.1.四种变量的存储位置:

==Local (also known as stack) variables (on the Stack)==

• Variables declared in a method and method parameters.

• Temporary variables, alive only when the method they belong to is on the Stack

==Instance variables (on the Heap)==

• Variables declared in a class (not inside of a method).

• Live inside the object they belong to

==Object reference (non-primitive) variables:==

– Hold a reference to an object, not the actual object.

– A local variable that is a reference to an object goes on the Stack (the object it refers to still goes on the Heap).

==类变量和实例变量:==

A class variable is created when the class is created, rather than when an object is created

To declare a class variable, use the modifier static.

If you declare something as static, it means that all objects have the same copy of that

variable/method(见block2)

• Static is like global variables but applies classwide.

• Static methods become available when the class is loaded (created), not

when you make an instance of it.

java1/image-20220511203936802


2.2.Methods and the Stack

Method goes on top of the Stack when it is called and stays in the Stack until it’s done

Stack frame(栈帧):

– What actually is pushed onto the Stack.

– Contains the state of the method

(which line of code is executing and values of all local variables).

每一个方法从调用开始至执行完成的过程,都对应着一个栈帧在虚拟机里面从入栈到出栈的过程。

java1/image-20220602160643492

2.3.Object References

Object reference (aka non-primitive) variables:

– Hold a reference to an object, not the actual object.

– A local variable that is a reference to an object goes on the Stack (the object it refers to still goes on the Heap).

reference variable是一个局部变量所以就在stack上,但是其指向的对象在heap上

2.4.构造函数链 constructor chaining

When an object is created, that object will have “layers” of itself representing each superclass.

拥有父类的层次和自己的层次

java1/image-20220602160654651

When a new object is created, all the constructors in its inheritance tree must be run.

An object is only completely formed when all the superclass parts of itself are formed

2.5.Life of Objects and Variables

• Life of an object:

depends only on the life of reference variables referring to it.

– Object is alive (or dead) if its reference is alive (or dead).

• Variable lifetime:

– same for primitive and reference variables;

– different for local and instance variables

local variables: live only within the method that declared it

Is alive as long as its Stack frame is on the Stack

instance variables: live for as long as object they belong to lives.

2.6.GC(简单介绍)

Objects in Java are dynamically allocated and created on demand:

– memory space for an object is allocated at runtime, not at compile time;

– the new statement causes the memory for an object to be allocated

(similar to the C malloc() function)

java不会内存泄漏,因为有GC动态调整存储空间

If an object has only one reference to it and the Stack frame holding it gets popped off the Stack, then the object is now abandoned in the Heap.

如果没有引用变量指向一个对象,那么这个对象将被GC回收

Making an Object Eligible for GC

(1) The reference goes out of scope, permanently.

(2) The reference is assigned to another object.

(3) The reference is explicitly set to null.

Setting a reference variable to null (it means no object)

  • finalizer(终结方法):The opposite of a Java constructor is a finalizer; it can sometimes be used for the cleanup of an object.

3.常用类

3.1.Math类

3.1.1方法(全部为类方法)

java1/image-20220511214937944

java1/image-20220420205927974

Math类中成员方法没有意义,所以没有成员方法

Math类不能实例化

Classes that can’t be instantiated:

Abstract classes and interfaces.

– Classes with private constructors.

Only code inside the class can invoke a private constructor!

java1/image-20220602160740267

Math类设计如上:不能实例化

3.1.2利用static final定义变量

– Variables that are static and final cannot be changed.

习惯变量名全大写

Initialisation of static final variables(两种初始化方法):

– When the variable is declared.

– In a static initialiser: block of code that runs when a class is loaded, before any code can use the class.

public class Bar{
public static final double BAR_SIGN;
static {
BAR_SIGN = (double) Math.random();
} 
}

3.2.Random Class

The Random class is part of the java.util package and provides methods that generate random numbers.

import java.util.Random;
public class RandTest {
public static void main(String[] args) {
Random r = new Random();
float aRandomFloat = r.nextFloat();
int aRandomInt = r.nextInt();
System.out.println("A random float is " + aRandomFloat);
System.out.println("A random int is " + aRandomInt);
} 
}

3.3.包装类(Wrapper Classes)

把基本数据类型包装成类

used when a variable of a primitive type needs to be treated as an object.

Wrapper classes are part of java.lang package no need to import them:

java1/image-20220420211438457

注意除了int和char其余均为首字母大写

基本数据类型与字符串的转换:

java1/image-20220602160757574

int a=Integer,parssInt(s)
3.2.1装箱、拆箱(Wrapping versus Unwrapping

java1/image-20220420212052011

int i = 10;
Integer iWrapped = new Integer(i);
int unWrapped = iWrapped.intValue();

Autoboxing自动装箱(包装类和基本数据类型等效使用)

automatic wrapping : conversion from primitive type to wrapper object is automatic!

体现在:

  • Method Arguments

    you can pass either a reference or a matching primitive to a method that takes in a wrapper type; reverse is also true!

  • Return Values

    you can return either a reference or a matching

    primitive on a method with a primitive return type; reverse is also true!

  • Boolean Expressions

    where a boolean value is expected, you can use

    either an expression evaluating to a boolean, a primitive or a matching

    wrapper.

  • Operations on Numbers

    in operations where a primitive type is expected, you can use a wrapper type!

  • Assignments

    a variable declared as a wrapper (or primitive) can be assigned a matching wrapper (or

    primitive)

  • All wrapper classes are subclasses of the Number abstract class (part of the java.lang package)

we can construct a Number object of type Integer:

Number num = new Integer(10);

Often used when manipulating collections of numbers.

  • Subclasses of Number provide constants to, e.g. represent the upper and lower

bounds of the corresponding data type (MIN_VALUE and MAX_VALUE,

respectively)

3.3.Scanner Class

  • Scanner class (of java.util package) allows a word to be specified as a delimiter(分隔符)
String s =Let your heart guide you.;
Scanner myScanner = new Scanner(s);
myScanner.useDelimiter(“you”);
while (myScanner.hasNext())
System.out.println(myScanner.next());

Output is …

Let

r heart guide

  • Scanning primitive type values: several methods can be used to obtain a token with a primitive data type value

    String s = "1 10 100 1000";
    Scanner myScanner = new Scanner(s);
    int sum = 0;
    while (myScanner.hasNext()) { sum += myScanner.nextInt(); }
    System.out.println("Sum = " + sum);
  • Reading console input

    System.out.print("Please enter an int value: ");
    
    Scanner myScanner = new Scanner(System.in);
    
    int i = myScanner.nextInt();

4.Recursion

Methods that call themselves, directly or indirectly

需要Stop condition

  • brings additional overhead to programs:

Everytime a program calls a recursive method, space needs to be assigned for the method’s local variables and parameters. Extra memory required + time to manage the extra space

Teaching Block4

1.GUI

GUI: Method for interacting with a computer via the manipulation of text, images and “widgets”.

使用awt和swing

java.awt
javax.swing//Javax表示扩展包

1.1. 3 main concepts:

– Component: An object that the user can see on the screen and can also interact with.

– Container: A component that can hold other components.

– Event: An action triggered by the user (e.g. pressing a key, clicking a mouse button).

Containers: objects capable of containing other Componentobjects.

Components: single entities with no containment abilities.

二者都是抽象类

1.2.两种容器:

Top-level Containers: At least one of these containers must be present in any Swing application.

顶层容器是进行图形编程的基础,一切图形化的东西都必须包括在顶层容器中。顶层容器是任何图形界面程序都要涉及的主窗口,是显示并承载组件的容器组件。

General-purpose Containers:Found in most Swing applications.

中间容器是容器组件的一种,也可以承载其他组件,但中间容器不能独立显示,必须依附于其他的顶层容器

java1/image-20220602160826785

1.3.awt包:

The java.awt package contains most of the classes needed to create GUI applications and Applets in Java.

几种其中的类:

– Container Classes: Graphical widgets capable of containing collections of other graphical widgets (i.e. Panel, Window, Dialogand Frame).

– Component Classes: Atomic graphical widgets like Button, Menuand List.

– Layout Manager Classes: Control the layout of component objects on/in container objects.

– Primitive Graphics Classes: Control and access primitive graphics like Point, Rectangle and Polygon.

– Event Handling Classes: Deal with events received from the GUI and other system items.

– Listener Classes: Receive events from graphical components and act on them

  • 制作GUI步骤:
  1. Make a frame: create an instance of JFrame
  2. Make a widget (e.g. make a button or text field)
  3. Add the widget to the frame
  4. Display the frame: must give it a size and make it visible

1.4.Containers(主要用swing)

常用的containers包括:JDialog JFrame JPanel ScrollPane等等

1.4.1.JFrame窗体(基础)

JFrame 是 Swing 组件的顶层容器,该类继承了 AWT 的 Frame 类

import javax.swing.JFrame;

public class FrameDemo extends JFrame {

        public FrameDemo() {

        this.setTitle("EBU4201 Demo JFrame");

        this.setSize(250, 100);

        this.setVisible(true);

}

public static void main(String[] args) {

FrameDemo myFrame = new FrameDemo();

} 

}
  • You can extend Frame in your program (more common),or instantiate the Frame class in your own class (less common) to build a basic GUI.

  • 通常在frame类中定义好组件,在main中实例化

  • 未调用方法设置时,JFrame大小为0,且不可见

  • 当创建一个 JFrame 类的实例化对象后,其他组件并不能够直接放到容器上面,需要将组件添加至==内容窗格==,而不是直接添加至 JFrame 对象。示例代码如下:

frame.getContentPane().add(b);

java1/image-20220602160846933

  • 常用的API方法:
方法签名 方法功能
setLocation(int x, int y) 设置组件的位置。
setSize(int width, int height) 设置组件的大小。
setBounds(int x, int y, int width, int height) 同时设置组件的位置、大小。
setVisible(Boolean b): 设置该组件的可见性。
setTitle(String s); 设置标题栏
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 设置窗口关闭
  • 添加组件的方法:
方法签名 方法功能
Component add(Component comp) 向容器中添加其他组件 (该组件既可以是普通组件,也可以是容器) , 并返回被添加的组件 。
Component getComponentAt(int x, int y): 返回指定点的组件 。
int getComponentCount(): 返回该容器内组件的数量 。
Component[] getComponents(): 返回该容器内的所有组件 。

add两次相同的控件后,会把前面的自动取消掉

1.5.Event handle(事件处理)

  • A (user) event is triggered any time when some sort of defined signal is received by the program.

  • An event is generated by external user actions

  • .*表示该包内所有引用类

java.awt.event.*
  • You need an listener(监听器) and a source(源) for each event

​ 一个事件源可以拥有多个事件监听器

  • Listener Interface: the bridge between the listener (the user code) and the event source (e.g. the button).

  • Event source: object that can turn user actions (e.g. click a mouse, close a window) into events.

  • Every event type has a matching listener interface:

java1/image-20220602160922914

  • 创建event handle步骤:

    1.首先创建事件源组件对象(比如按钮);

    2.自定义类,实现XxxListener接口,重写方法;Implement the ActionListener interface:

public class MyClass implements ActionListener {...} 

​ 3.调用事件源组件对象的addXxxListener方法完成==注册监听==Register with the widget:

someComponent.addActionListener(instanceOfMyClass); //通常直接用this代指

​ 4.重写监听接口中的actionPerformed(e)方法 Define the event-handling method:

public void actionPerformed(ActionEvent e) {
// code that reacts to the action ...
}

​ 举例:

  • 方法一:相当于把程序所在类当成了监听类

java1/image-20220602160937169

  • 方法二:使用匿名内部类:

    不用写implement

​ deal with multiple event sources:

  1. Register each widget with the required listener and then determine which widget generated the event.

  2. Use an anonymous inner class for each event source.

  3. Use a specialised inner class for each event source.

minusButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
         label.setText("" + (--number));
    }
  }
);
  • 方法三:使用内部类:在主界面的类中不实现接口,而是在内部类中实现

    someComponent.addActionListener(new innerclassName);

java1/image-20220602161000360

java1/image-20220602161027187

原理:例如,如果鼠标单击了按钮对象 Button,则该按钮 Button 就是事件源,而 Java 运行时系统会自动生成 ActionEvent 类的对象 ActionEvent,该对象中描述了单击事件发生时的一些信息。之后,事件监听器对象将接收由 Java 运行时系统传递过来的事件对象 ActionEvent,并进行相应的处理。

java1/image-20220602161039631

1.6.常用component:

添加component的方式:

myFrame.getContentPane().add(myButton);
1.6.1JLabel:

component that you can put text into.

When creating a label, you can specify the initial value and the alignment (对齐方式)you wish to use within the label.

JLabel myLabel = new JLabel(“text”, JLabel.RIGHT);
1.6.2 JButton

extends Component, displays a string and delivers an ActionEvent for each mouse click.

– Normally buttons are displayed with a border.

– In addition to text, JButtons can also display icons

JButton myButton = new JButton(“text”);

常用组件的介绍

组件名称 定义
JButton 代表Swing按钮,按钮可以带一些图片或文字
JCheckBox 代表Swing中的复选框组件
JComboBox 代表Swing下拉列表框,可以在下拉显示区域显示多个选项
JFrame 代表Swing的框架类
JDialog 代表Swing版本的对话框
JLabel 代表Swing中的标签组件
JRadioButton 代表Swing单选按钮
JList 代表能够在用户界面中显示一系列条目的组件
JTextField 代表文本框
JPasswordField 代表密码框
JTextArea 代表Swing中的文本区域
JOptionPane 代表Swing中的一些对话框

1.6.Layout

Layout Manager: An interface that defines methods for positioning and sizing objects within a container.

在java.awt包中

Java defines several default implementations of LayoutManager.

  • JFrame默认使用BorderLayout管理其内部组件布局;

  • JPanel默认使用FlowLayout管理其内部组件布局;

  • JScrollPane 默认使用 BorderLayout 管理其内部组件布局;

    Geometrical placement in a Container is controlled by a LayoutManager object.

    设置Frame为最佳大小(打开窗口就为这么大不用resize)

    frame.pack();

Layouts allow you to format components on the screen in a platformindependent way.

FlowLayout

GridLayout

BorderLayout

Step 1: Create the layout.

Step 2: Invoke the setLayout() method on the container to use the new layout.

JPanel p = new JPanel();
p.setLayout(new FlowLayout());

or

JPanel p = new JPanel(new FlowLayout());
1.6.1.FlowLayout

is the default layout for the JPanel class.

– If the screen is resized, the components’ flow will change based on the new width and height.

屏幕resize时,每行按钮个数会变,但是按钮大小不会变

When you add components to the screen, they flow left to right(centered), based on the order added and the width of the screen.

– Constructors:

• FlowLayout()

• FlowLayout(int align)

• FlowLayout(int align, int hgap, int vgap)

!

1.6.2.GridLayout
构造方法 方法功能
FlowLayout() 使用默认 的对齐方式及默认的垂直间距、水平间距创建 FlowLayout 布局管理器。
FlowLayout(int align) 使用指定的对齐方式及默认的垂直间距、水平间距创建 FlowLayout 布局管理器。
FlowLayout(int align,int hgap,int vgap) 使用指定的对齐方式及指定的垂直问距、水平间距创建FlowLayout 布局管理器。
  • GridLayout arranges components in rows or columns:

– If number of rows is specified, the number of columns will be the number of components divided by the rows.(组件数除行数)

– If number of columns is specified, the number of rows will be the number of components divided by the columns.(组件数除列数)

GridLayout 布局管理器将容器分割成纵横线分隔的网格 , 每个网格所占的区域大小相同。当向使用 GridLayout 布局管理器的容器中添加组件时, 默认从左向右、 从上向下依次添加到每个网格中 。

与 FlowLayout不同的是,放置在 GridLayout 布局管理器中的各组件的大小由组件所处的区域决定(每个组件将自动占满整个区域) 。

也就是说当窗口resize时,每行每列按钮个数不变,大小会随着屏幕改变

– Constructors:

• GridLayout():default of 1 column per component, in a single row.

• GridLayout(int rows, int cols)

• GridLayout(int rows, int cols, int hgap, int vgap)

1.6.3.BorderLayout
构造方法 方法功能
BorderLayout() 使用默认的水平间距、垂直 间距创建 BorderLayout 布局管理器 。
BorderLayout(int hgap,int vgap): 使用指定的水平间距、垂直间距创建 BorderLayout 布局管理器。

如果不往某个区域中放入组件,那么该区域不会空白出来,而是会被其他区域占用

java1/image-20220602161102960

frame.add(new Button("西侧按钮"), BorderLayout.WEST);
frame.add(new Button("南侧按钮"), BorderLayout.SOUTH);
frame.add(new Button("北侧按钮"), BorderLayout.NORTH);
frame.add(new Button("中间按钮"), BorderLayout.CENTER);

1.7.Three types of graphics in GUI

1.7.1.Graphics class:

Java graphics are based on pixels (small dot on the screen that can be accessed).像素

A pixel is identified by a pair of numbers(coordinates) starting at zero, (x,y):

java1/image-20220602161114516

• x = horizontal position (increases left to right)

• y = vertical position (increases top to bottom)

java1/image-20220515104354341

Step 1: Make a paintable widget.

• Create subclass of JPanel & override the paintComponent() method.

• Put all the graphics code in the paintComponent() method.

• The paintComponent() method is called only by the JVM; the programmer does not call it!

• It takes a Graphics object – drawing canvas for what is displayed on the screen

import java.awt.*;
import javax.swing.*;
class MyDrawingPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.fillRect(50,50,80,50);
} }

java1/image-20220515104815143

java1/image-20220515104825449

java1/image-20220515104942497

1.7.2.Graphics2D Class

java1/image-20220515105324652

1.7.3.Color Class

Java has a Color class.

  • To define the colour of an object, you can directly use the static colour variables of the Colorclass.

java1/image-20220602161131822

public void paintComponent(Graphics g) {
g.setColor(Color.red); // g object becomes red
g.drawLine(10,10,200,200); // draw a red line
}

• You can also set your own colour by choosing an RGB value:

Color myColor = new Color(r,g,b)

java1/image-20220515105915729

2.Exception Handling

  • Some causes of error situations:

– Incorrect implementation

– Inappropriate object request

– Inconsistent or inappropriate object state

  • programming errors

    – Trying to access an array out of bounds

    this throws an ArrayIndexOutOfBoundsException runtime error.

    – Attempting to divide by zero

    this throws an ArithmeticExceptionruntime error

Exception: an object that signals to the calling code, the occurrence of an unusual condition.

Exceptions are objects, subclasses of **java.lang.Exception **class

2.1.Checked versus Unchecked Exceptions

异常的分类:

java1/image-20220602161147594

Throwable类是所有异常的根

异常可以分为:系统错误、异常、运行时异常。

  1. 系统错误(Error)、运行时异常(runtime exception)被称作免检异常(Unchecked exception)Unchecked exceptions:

    – Subclasses of RuntimeException.

    – Used for unanticipated failures.

    – Where recovery is unlikely.

    • Some exceptions thrown by Java class libraries are called run-time exceptions

      当出现这样的异常时,总是由虚拟机接管(提供好现成的异常对象)。

      比如:我们从来没有人去处理过NullPointerException异常,它就是运行时异常,并且这种异常还是最常见的异常之一。

    • Java does not force client code to catch run-time exceptions (also called unchecked exceptions), because:

    • 不强制要求写免检异常的捕获

      – Run-time exceptions can occur so frequently that the cost of checking by the compiler would be very big.

      – You can catch them if you believe there is ever likely to be a problem.

      – Ideally, you should instead check input pre-conditions first!

      java1/image-20220602161203238

  2. 其他异常都为必检异常(checked exception)

    Checked exceptions:

    – Subclasses of Exception.

    – Used for anticipated failures.

    – Where recovery may be possible.

    编译器会强制程序员检查并处理必检异常

2.2.Run-Time Error Handling

Run-time programming errors are the most difficult to deal with

There’s no support given at programming language level for catching and managing errors in most languages.

Using exceptions enables potential run-time problems to be noticed at compile time

java1/image-20220517204741685

  • throws/throw

    抛出异常(不处理)

    1. throw:抛出异常的关键字

      When writing code, we can throw exceptions, and thus force any clients that use it to catch these exceptions.

      throw new XXXXException("错误信息")

      XXXXException必须为系统封装过的类,或者利用自己创建的其子类

    2. throws:声明异常的关键字

      不管这个方法中是否有throw语句,只要这个方法中调用过抛出异常的方法,就要给这个方法加throws(调用链中的每一层都要加)

      表明此方法可能会抛出某个异常(抛没抛还得看throw的条件)

      用于==方法==头:

      public void myMethod() throws XXXExceotion{
          
      }
      public void myMethod() throws XXXExceotion1,XXXExceotion2,XXXExceotion3{
          //多个异常
      }

      Javadoc documentation syntax to indicate that method throws an exception: @throws ExceptionType reason

      you don’t want to catch exceptions, but want client code to handle them

      当编写类的人不打算处理一个异常,只是抛出此异常留给写实现类的人去处理

      in this case, you should declare that your method throws them

java1/image-20220602161223587

  • try/catch Block

    捕获 异常并处理(需要有异常被抛出)

    When a program is run, the JVM will attempt to execute each statement in the try block in turn.

    If any statement throws an exception then either:

    – the catch block corresponding to this exception will be executed;

    – the method in which this code lies will itself throw the exception

    如果使用系统jvm默认异常处理方式时:

    先从try内部开始执行,直到出现异常(此时会自动生成一个默认异常类对象,并提交给系统,而系统运行时接受到异常,从catch中找匹配的异常类,然后进行异常处理)

    如果使用自己建的异常类(try中某个有异常的方法在声明时必须抛出异常)。

    A try/catch section can also have a finally section, usually to tidy up afterwards

    无论是否发生异常,finally 代码块中的代码总会被执行。在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。

try {
// code that can throw exceptions E1, ..., En
// ...protect one or more statements here
}
catch (E1 e1) {
// code to handle exception E1
// ...report and recover from the exception here
}
// ...
catch (En en) {
// code to handle exception En
// ...
}
finally {
// perform any actions here that are common, regardless of whether or not an exception is thrown
}

如果一个方法声明了一个必检异常,则必须使用try-catch中调用处理,或者声明要用用throws抛出

2.3.Creating Exception Classes

Java programmers can create their own exception classes.

构建一些Java不认为是异常的异常

比如:-100岁

User exception classes are like any other class, but they must extend the Exception class.

public class MyException extends Exception {
public MyException() {
     super(); // call constructor of parent Exception
     // other appropriate code
}
public MyException(String s) {
      super(); // call constructor of parent Exception
      // other appropriate code
} }

If a program fails to catch an exception(没捕获只抛出), the JVM interpreter prints information about the exception, and the location where it occurred.

java1/image-20220518161430969

2.4.Assertions in Java

在实现中,assertion就是在程序中的一条语句,它对一个boolean表达式进行检查,一个正确程序必须保证这个boolean表达式的值为true;如果该值为false,说明程序已经处于不正确的状态下,系统将给出警告或退出。

Java statements that enable you to assert (or check) an assumptionabout your program

一般来说,assertion用于保证程序最基本、关键的正确性。

Assertions are used to ensure program correctness and avoid logic errors.

– For internal consistency checks, e.g. to check the object state following mutation (due to a setter method being called).

– During development (to enable debugging) but usually removed in production versions, e.g. via a run-time option.在产品代码中移除

  • Java assertions are declared via an assert statement
assert assertion-expression 
assert assertion-expression : detailMessage

– The assertion-expression(boolean类型) expresses something that should be true at this point.

– The detailMessage is a primitive type or an Object value(是要传入AssertionError构造方法的信息,会打印该错误信息).

– An AssertionError exception is thrown if the assertion is false.(如果assertion是false就抛出一个AssertionError)是Error的子类

  • Assertions are disabled by default, at runtime. But you can always,

    – enable your program to run with assertions by calling it with the

    -enableassertions (or in short form, -ea) switch

    – disable your program from running with assertions by calling it with the

    -disableassertions (or in short form, -da) switch

    – enable/disable assertions at package level and at class level.

java –ea AssertionDemo
java –da Test
java –ea:ClassUsedByTest Test
java –da:ClassUsedByAssertionDemo AssertionDemo
  • 不要使用assertions的情况

– Should not be used to check the validity of a public method’s argument(s).

对于公共函数,我们通常不使用assertion检查,因为一般来说,公共函数必须对无效的参数进行检查和处理。而私有函数往往是直接使用的

– Do not include normal functionality(不要用于改变程序中参数的操作,断言不应该以任何方式改变程序的状态)

// Incorrect use of assertions:
assert book.remove(name) != null;

3.File I/O

Data stored in variables, arrays, objects is temporary: once a program has finished executing, information is lost!

Saving data requires information to be stored in a file on a disk/CD

  • two ways of saving data:

This interaction with an external source is what we refer to as Input/Output:

Input: to bring in information (read)

Output: to send out information (write)

can be

anywhere:

of any type (any object)

java1/image-20220602161326106

Java input/output makes use of streams:

– A stream is a connection to a source of data or to a destination for data (sometimes both).

– Streams can represent any data, so a stream is a sequence of bytes that flow from a source to a destination.

we read information from an input stream and write information to an output stream

A program can manage multiple streams simultaneously

1.two broad categories of streams

Java has two broad categories of streams:

– byte streams(字节流)

machine-formatted data(无法用文本编辑器读取二进制文件)

InputStream

OutputStream

java1/image-20220522182645667

– character streams(文本流)

for human readable data(可以用文本编辑器处理)

Reader

Writer

  • Text files contain data represented in human-readable form.

  • Binary files contain data represented in binary form.

2.java.io.File Class

File 类:

java1/image-20220522201307571

Files live in directories within the file system.

– Complete file name (represented by a String) consists of the path + name of file

java1/image-20220602161408801

File f1 = new File("E:\\文件夹\\文件名")

java中使用\代表Windows中的\ 。

java.io.File: contains methods to obtain file properties, for renaming and deleting files.

– A wrapper class for a file’s name and directory path: represents an abstract pathname.

– It hides file system differences.

– No exception is thrown if file does not exist

Constructors:

java1/image-20220602161440131

methods

java1/image-20220602161449481

  • boolean exists() / boolean isDirectory() / boolean isFile()

  • boolean canRead() / boolean canWrite()

  • boolean delete(): returns true if file successfully deleted

  • String getAbsolutePath(): returns complete absolutefile/directory name

  • boolean renameTo(File dest): returns true if operation successful

  • long length(): returns length of the file in bytes

  • String[] list(): returns an array of strings containing the list of files in this directory

    java1/image-20220522202635587

4. Reading from / Writing to files

1. Open file

– Needs the file’s name and maybe its location (path).

– Open file by creating an instance of an appropriate stream class.

2. Perform operations

– Read from and/or write to the file.

– Call instance methods that belong to the ==stream object==’s class.

3. Close file(一定要释放资源)

– Any class from InputStream, OutputStream, Reader and Writer has a close() method.

File I/O can cause a large number of exceptions to be thrown.

5.FileReader versus FileWriter

FileReader

Java FileReader类继承自InputStreamReader类。 FileReader用于读取字符流。
FileReader类有几个构造函数来创建所需的对象。 以下是FileReader类提供的构造函数列表。

java1/image-20220522205201711

java.io.FileNotFoundException will occur if you attempt to create a FileReader with a nonexistent file.

java1/image-20220522205131531

记得用close()关闭所有与之相关的系统资源

FileWriter

在给出 File 对象的情况下构造一个 FileWriter 对象。

FileWriter(File file)

在给出 File 对象的情况下构造一个 FileWriter 对象。

FileWriter(File file, boolean append)

构造与某个文件描述符相关联的 FileWriter 对象。

FileWriter(FileDescriptor fd)

在给出文件名的情况下构造 FileWriter 对象,它具有指示是否挂起写入数据的 boolean 值(为true则下一次写入在本次末尾进行)。

FileWriter(String fileName, boolean append)

FileWriter: If the file doesn’t exist, a new file will be created.

java1/image-20220522205940428

void write(int c)

void write(byte[] cbuf)

void write(char[] cbuf,int off,int len)

void write(String str)

void write(String str, int off,int len)

记得用close()关闭所有与之相关的系统资源

BufferedReader

java1/image-20220602161507595

BufferedReader维护一个内部的8192个字符缓冲器。在BufferedReader中进行读取操作期间,将从磁盘读取一部分字符并将其存储在内部缓冲区中。 并且从内部缓冲区中单独读取字符。因此,减少了与磁盘的通信次数。

为了创建一个BufferedReader,我们必须首先导入java.io.BuferedReader包。导入软件包后,就可以创建阅读器。

//创建一个FileReader
FileReader file = new FileReader(String file);

//创建一个BufferedReader
BufferedReader buffer = new BufferedReader(file);

在上面的示例中,我们创建了一个名为buffer的BufferedReader和一个名为file的FileReader。

此处,BufferedReader的内部缓冲区的默认大小为8192个字符。 但是,我们也可以指定内部缓冲区的大小。

//创建一个具有指定大小的内部缓冲区的BufferdReader
BufferedReader buffer = new BufferedReader(file, int size);

read()方法

  • read() - 从阅读器的内部缓冲区读取单个字符
  • read(char[] array) - 从阅读器读取字符并将其存储在指定的数组中
  • read(char[] array, int start, int length)- 从阅读器读取等于length字符的数量,并从start位置开始存储在指定的数组中

skip()方法

要丢弃和跳过指定数量的字符,可以使用skip(int a)方法。

readline()方法(读取一行)

public String readline()

**IOException **包含 FileNotFoundException 所以只需要抛出 IOException.

4.Collection Classes

Collection in Java: “an object that groups multiple elements into a single unit”.

Java provides several interfaces, implementations and algorithms for handling collections of objects, via its Java Collections Framework (see java.util package).

集合类和数组不一样,数组元素既可以是基本类型的值,也可以是对象(实际上保存的是对象的引用变量),而集合里只能保存对象(实际上只是保存对象的引用变量,但通常习惯上认为集合里保存的是对象)。

Collection是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素,JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)的实现

collection的常用方法

java1/image-20220602161521978

处理集合时的接口、实现类、算法

java1/image-20220529113726855

java1/image-20220602161534187

4.1.集合的interface

  • Set: A collection that contains no duplicate elements;(模拟数学中的集合)

  • List: An ordered collection (also known as a sequence). Elements can be accessed by their position in the list, and it is possible to search for elements in the list. Lists allow for duplicate elements

java1/image-20220602161547665

java1/image-20220602161555993

  • Map: An object that maps keys to values. A map does not contain duplicate keys; each key can map to at most one value.

    Each key maps to one value only.

    Map 提供 key 到 value 的映射,你可以通过“键”查找“值”。一个 Map 中不能包含相同的 key ,每个 key 只能映射一个 value 。

4.2.集合的实现类

java1/image-20220602161607517

  • array 和arraylist:

    array 在初始化时必须确定长度

    array必须在分配值时必须确定位置(index)

  • Map的实现类 HashMap

    The HashMap class implements Map and is efficient for locating a value, as well as inserting and deleting a mapping.

    Entries are not ordered

import java.util.*;
public class HashMapTester {
public static void main( String[] args ) {
Map<String, String> petSounds = new HashMap<String, String>();
petSounds.put("cat", "Meow"); petSounds.put("mouse", "Squeak");
petSounds.put("dog", "Woof"); petSounds.put("guineaPig", "Squeak");
System.out.println("map = " + petSounds);
String val = (String)petSounds.get("dog");
System.out.println("Value for key 'dog' is: " + val);
}
}

java1/image-20220602161619596

Java Iterator(迭代器)不是一个集合,它是一个接口,可以用于访问、遍历集合

其中的方法:

java1/image-20220602161629351

调用 it.next() 会返回迭代器的下一个元素,并且更新迭代器的状态。

调用 it.hasNext() 用于检测集合中是否还有元素。

调用 it.remove() 将迭代器返回的元素删除。

ArrayList<String> alist = new ArrayList<String>();
// Add Strings to alist
for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
String s = it.next(); // No downcasting required.
System.out.println(s);
}

5.2-dimensional (2D) Arrays

Java stores a 2D array as an array of arrays, e.g.

int[][] nums = new int[5][4];
nums = new int[5][]; // OK
nums = new int[5][4]; // OK

must always specify the first dimension,do not need to specify the second dimension

A 2D array of objects is an array of an array of references to objects 对象的reference的数组的数组

利用arraylist实现二维数组

ArrayList<ArrayList<Integer>> topList =new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 3; i++)
topList.add(new ArrayList<Integer>());
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
topList.get(i).add(new Integer(i+j));
}

6.Sorting

Selection sort

  1. Find largest number and put it in the last position.

  2. Find next largest number and put it next to last one.

  3. Repeat until finished.

Insertion sort:

List of values is sorted by inserting (repeatedly) an unsorted element into a sorted sublist until the complete list is sorted

Bubble sort:

– Several passes are made through the array.

– Each time, successive adjacent pairs are compared.

• If pair is in decreasing order, order of values is swapped.

• Otherwise, move on to next pair.

void bubbleSort(double[] list) {
boolean changed = true;
do {
changed = false;
for (int j = 0;
j < list.length-1; j++)
if (list[j] > list[j+1]) {
double temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
} while (changed);
}

7.Comparing objects

在java中接口comparable使我们经常要接触到的,比如对集合或者数组进行排序,我们经常使用到Arrays.sort()或者Collections.sort().当集合中的对象是自定义的对象时,我们有两种方法能够使排序方法应用到自定义对象的集合(数组)中

Java defines two ways of comparing objects:

  1. The objects implement the Comparable interface.

    被排序的对象类要实现cmparable

  2. A Comparator object is used to compare the two objects.

• If the objects are Comparable, they are said to be sorted by their “natural” order.(自然排序)

A Comparable object can only offer one form of sorting.

– To provide multiple forms of sorting, Comparators must be used.

如果想对元素进行自然排序,必须在元素对象的类上实现comparable接口,该接口只有compareTo()一个方法。所以要重写compareTo()方法使其满足要求进行比较

用sort方法 排序,表示升序排列(其算法简单来说就是每两个都比一次)
(默认调用compareTo 如果返回1 则认为比较的对象比本对象大(放在后边))

public class Employee implements Comparable<Employee> {
    实现Comparable<E>接口
        
int empID;
String eName;
double salary;
static int i;
    
public Employee(String name, double sal) {
empID = i++;
eName = name;
salary = sal; }
public String toString() {
return "EmpID = " + empID + "\n" + "Ename = " + eName + "\n" +
"Salary = " + salary;
}
public int compareTo(Employee o1) {
    
if (this.salary == o1.salary) return 0;
else if (this.salary > o1.salary) return 1;
else return -1;
} }

import java.util.*;
public class ComparableDemo {
public static void main(String[] args) {
List<Employee> ts1 = new ArrayList<Employee>();
ts1.add(new Employee("Tom", 40000.00));
ts1.add(new Employee("Harry", 20000.00));
ts1.add(new Employee("Maggie", 50000.00));
ts1.add(new Employee("Chris", 70000.00));
    

Collections.sort(ts1);
    
Iterator <Employee> itr = ts1.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.println(element + "\n");
} } }
    

细碎知识

1.String类中的format方法

format方法使用占位符进行格式化
常规类型、字符类型和数值类型的占位符格式:
%[index$][标识][最小宽度][.精度]转换符
日期和时间类型的占位符格式:
%[index$][标识][最小宽度]转换符
与参数不对应的占位符格式:
%[标识][最小宽度]转换符
其中index表示参数列表中的位置上的值
可用标识:

标识 含义
- 在最小宽度内左对齐,不可与0标识一起使用
0 若内容长度不足最小宽度,则在左边用0来填充
# 对8进制和16进制,8进制前添加一个0,16进制前添加0x
+ 结果总包含一个+或-号
空格 正数前加空格,负数前加-号
, 只用与十进制,每3位数字间用,分隔
( 若结果为负数,则用括号括住,且不显示符号

可用转换符:

转换符 含义
b 布尔类型,只要实参为非false的布尔类型,均格式化为字符串true,否则为字符串false
n 平台独立的换行符, 也可通过System.getProperty(“line.separator”)获取
f 浮点数型(十进制)。显示9位有效数字,且会进行四舍五入。如99.99
a 浮点数型(十六进制)
e 指数类型。如9.38e+5
g 浮点数型(比%f,%a长度短些,显示6位有效数字,且会进行四舍五入)
s 字符串类型
c 字符类型
String result1 = String.format("小明今年%d岁,他住在%s,他的月工资有%.2f", 25,"北京市",6633.435);
System.out.println(result1);//输出:小明今年25岁,他住在北京市,他的月工资有6633.44
/*****************************************************/
double num = 123.4567899;
String result2 = String.format("%e", num);
System.out.println(result2);//输出:1.234568e+02

2.javadoc

To generate javadocdocumentation, type on the command line:

javadoc -d docsfile.java 

View the docs with a web browser:

– Start with the index.html file in the docs subdirectory.

Java文档注释用法+JavaDoc的使用详解_阿★永的博客-CSDN博客_javadoc

3.增强for

for 的其他语法

java1/image-20220602161656225

for (循环变量类型 循环变量名称 : 要被遍历的对象) 循环体

借助这种语法,遍历一个数组的操作就可以采取这样的写法

int[] integers = {1234}; 

for (int i : integers) { //等同于 int i;i<integers;i++

System.out.println(i);可以实现遍历
}

4.导包

java1/image-20220405163334345

java1/image-20220405163354269

5.Sting 和int 互换

字串 String 转换成整数 int

int i = Integer.parseInt([String]);

将整数 int 转换成字串 String

String s = Integer.toString(i);

String s = "" + i;

6.scanner

import java.util.Scanner;
Scanner sc = new Scanner(System.in);
s.nextLine()

7.运行错误和编译错误

①编译错误一般指语法错误或者很明显的逻辑错误。
如:缺少分号,少写括号,关键字书写错误等, 在eclipse往往会画红线。
②运行错误是在没有编译错误的基础上运行后产生的逻辑错误。
如:空指针异常,除数为0,越界访问等,一般会抛出异常。