我是菜鸟:java学习中小知识点笔记

  1. 类中定义的域有2中,非静态域(实例变量) 和 静态域(类变量)。
  2. 如果在声明final域的时候没有提供初始值,那么在构造函数中必须初始化。(必须在构造函数中吗? 或者在初始化代码块中进行初始化,当然对于静态常量只能在定义时候初始化或者在静态代码块中给定初始值,而不能够在构造函数中再赋值)
  3. 初始化顺序:
    • Static定义的对象,按照定义的顺序,不区分static变量或者静态块(仅仅在首次生成这个类的对象或者首次访问属于哪个类的静态数据成员时候)
    • 定义的非静态对象(多次执行)
    • 类的构造器
package com.uestc.kun;

public class Order {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("-------------------------");
    System.out.println("main field Start");
       extend2 = new Extend();
      System.out.println("End of main field");
    }

//  Extend extend1;
    static Extend extend2 = new Extend();

}

class Base{
    Base(){
        System.out.println("Base constructor");
    }
    Base(int i){
        System.out.println("Base ("+i+")");
    }
}

class Extend{
    Base base1 = new Base(11);

    static Base base4;
    static Base base5 = new Base(55);

    {
        System.out.println("Base unstatic filed");
        base1 = new Base(1);
        base4 = new Base(555);
        System.out.println("End of Base unstatic filed");
    }


    static {

         System.out.println("Base Static filed");
         base4 = new Base(4);
         base5 = new Base(5);
         base3 = new Base(3);
         System.out.println("End of Base Static filed");

    }
    public Extend(){
        System.out.println("Extend constructor");
        base1 = new Base(1);
        base2 = new Base(2);
        base3 = new Base(3);
        base4 = new Base(4);
        base5 = new Base(5);
        System.out.println("End of Extend constructor");
    }
    static Base base3 = new Base(33);
    Base base2 = new Base(22);
}

/*
执行结果:
Base (55)
Base Static filed
Base (4)
Base (5)
Base (3)
End of Base Static filed
Base (33)
Base (11)
Base unstatic filed
Base (1)
Base (555)
End of Base unstatic filed
Base (22)
Extend constructor
Base (1)
Base (2)
Base (3)
Base (4)
Base (5)
End of Extend constructor
-------------------------
main field Start
Base (11)
Base unstatic filed
Base (1)
Base (555)
End of Base unstatic filed
Base (22)
Extend constructor
Base (1)
Base (2)
Base (3)
Base (4)
Base (5)
End of Extend constructor
End of main field

*/

方法

方法也分为实例方法和类方法。静态方法即使不存在对象也能够执行。
静态方法不能引用实例变量的原因:静态方法操作的变量的对象可能没有创建,即操作可能不存在的变量。也就是要求在不存在任何实例变量的时候,静态方法也可以执行。
main函数被声明为static的原因:应用程序在开始执行前不存在对象,为了开始执行,因此声明为static
虽然实例方法(非静态方法)针对类的对象,但是实际上对于每个实例方法,内存中都只有一个实例方法副本提供给类所有对象共享
如果方法不返回值,可以使用return来结束方法的执行。
局部变量不会被自动初始化。
Java中对所有的参数传递都是采用的值传递, 这意味着传给方法的每个参数都会制作一个副本,然后将副本传递给方法,并通过参数名进行引用。(如果使用基本类型变量作为参数,方法无法在调用程序中修改这个变量的值。)
当一个对象参数使用final关键字修饰时候,可以确保对象不被修改。(对基本类型变量使用final关键字,毫无意义。)
每个实例方法都有一个this指针,指向调用方法当前的对象。

初始化代码块

静态化初始代码块

static定义的代码块,并且在类加载时执行一次。静态类初始化代码块只能够初始化类的静态成员数据。

非静态初始化代码块

在创建对象的时候都执行一次,可以初始化类的实例变量。

其实用非静态代码块初始化静态变量也是可以的,不过一般不这样使用。

类可以拥有多个初始化代码块,他们按照出现的顺序依次执行。类加载时会执行静态代码块,创建对象时会执行非静态代码块。

使用构造函数复制对象

假设有一个对象Student stu1 = new Student(name,age), 我们想创建一个新的对象Student stu2 = stu1, 将其作为参数传递给方法,以达到修改stu2而保持stu1内容不变,这是不可能的。其解决方式是使用构造函数:

Student(final Student old){
  name = old.name;
  age = old.age;
  ++count; //记录有多少个对象
}

在使用输出对象的时候,编译器会自动的调用toString对象。
System.out.println(“Student:”+ stu1);

常用类介绍

String,StringBuilder,StringBuffer

  • String
    String 类型与int,float等数据之间的转化

eg1.

int x;
String str = "123";
x = Interger.parseInt(str); // Float.parseFloat(str1);

eg2.

float x = 11.2f;
String str = String.valueOf(x);
  • 字符串拷贝到数组
// Method1
String s1 = "Here is a sample.";
char [] temp = new char[6];
s1.getChars(2,8,temp,0);

//Method2
char [] temp = new char[s1.length()];
temp = s1.toCharArray();
  • StringBuffer
    StringBuffer类实际上封装的是一个字符数组。

Random, Math

使用Random类产生随机数。

Random random = new Random();//使用当前毫秒值作为种子
//Random random1 = new Random(long seed);
int ran = random.nextInt(8); // 0-8之间的随机数
//double nextGaussian();// 平局值,偏差均为0的高斯分布

使用Math类产生随机数

int random = (int)(Math.random()*10)%3+1; //1-3, Math.random: 0.0 - 1.0

Java 异常处理

Java 编译器要求Java程序必须捕获或者声明所有已检查异常。对于未检查异常可以不做处理。
throw 语句
throw ThrowableInstance

Eg.

try{...}catch(Exception e){
throw new ArrayIndexOutOfBoundsException("数组越界");
}

throws语句:如果一个方法引发了异常,而他本省不对异常进行处理,那么方法必须将这个异常抛给调用以使得程序能够继续执行下去。

集合框架

除了以map结尾的类以外(Map接口),其它类都实现了collection接口。

Collection

集合可以转化为任何其他的对象数组,但是不能直接转化为基本数据类型的数组。由于Collection接口继承了Iterable< E > 接口,因此可以使用”foreach”语句。

Set

要存放到Set容器的对象,这个类一定要重写equals()和hashCode()方法。

Set接口的对象存储对象时候,根据每个对象的哈希值(hashCode()方法获得)来获得存储所用,然后使用equals()方法对该位置的元素进行比较。
TreeSet 类使用红黑树结构对加入的元素进行排序,因此对象是可排序的,即要实现Comparable接口。(compareTo()方法, 实现Comparable接口的对象可以使用Collections.sort() 和Arrays.sort()排序。)

Map接口

Map< K , V>: K 是用Set来存放的。必须重写hashCode() 和 equals()方法。

Java IO

Java 对文件和目录的操作

windows系统中,路径分割符为”\”, Unix上为“/”.
获取当前工作目录:System.getProperty(“user.dir”);

Java文件操作示例:

import java.io.File;
import java.io.IOException;

public class JavaFileOperation  {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        File dir1 = new File("D:\\JavaIO");
        if(!dir1.exists())dir1.mkdir();
        File dir2 = new File(dir1, "dir2\\dir3");
        if(!dir2.exists())dir2.mkdirs();

        File file1 = new File(dir1, "Test1.txt");
        if(!file1.exists())file1.createNewFile();
        File file2 = new File("D:\\JavaIO\\dir2\\test2.txt");
        if(!file2.exists())file2.createNewFile();

        ShowFile(dir1,0);
        removeAll(dir1);
        ShowFile(dir1,0);

    }

    public static void ShowFile(File file, int level){
        StringBuilder sb = new StringBuilder("|--");
        for(int i=0;i<level;i++)sb.insert(0, "|  ");
        File[] childs = file.listFiles();
        int length = childs==null?0:childs.length;
        for(int i=0;i<length;i++){
            System.out.println(sb.toString()+childs[i].getName());
            if(childs[i].isDirectory())ShowFile(childs[i],level+1);
        }
    }
    public static void removeAll(File file){
        if(file.isDirectory()){
            File[] child = file.listFiles();
            for(int i = 0; i<child.length;i++)
                removeAll(child[i]);
            System.out.println("删除目录:"+ file.getAbsolutePath());
            file.delete();  // 删除空文件夹
        }
        else {
            file.delete();
            System.out.println("删除文件:"+ file.getAbsolutePath());
            }

    }

}

File 类根本无法访问文件的具体内容,无法从文件中读取数据和写入数据,这些操作要使用IO流。

字节流 InputStream / OutputStream (抽象类)

  1. 文件流 FileInputStream/FileOutputStream 以字节为单位的文件输入输出流—–适合操作二进制文件,例如图片,声音等。
    IO流操作文件步骤:

    • 创建连接到指定数据源的IO流对象。FileInputStream fin = new FileInputStream("D:\\Java.txt");
    • 利用IO流类提供的方法进行读写。

      //read
      int i = fin.read();
      while(i!=-1){
      System.out.print((char)i);
      i = fin.read()
      }
      //write
      FileOutputStream fout = new FileOutputStream("D:\\java.txt",true);//true 表示追加
      fout.write("你好".getBytes());

    • 关闭文件流

  2. 字节缓冲流: BufferedInputStream/ BufferedOutputStream (操作文件使用缓冲流,可以提高效率。)

字符流 Reader / Writer

  1. 文件流 FileReader/ FileWriter —-适合操作文本文件
  2. 字节缓冲流: BufferedReader/ BufferedWriter

转换流 InputStreamReader/OutputStreamWriter

数据流 DataInputStream/ DataOutputStream

对象流 ObjectOutputStream/ObjectInputStream

对象流不能序列化static和transient修饰的成员变量,并且必须实现Serializable这个标记接口。

// 序列化保存到文件
ObjectOutputStream  oos = new ObjectOutputStream(new FileOutputStream("D:\\Java.txt"));
oos.writeObject(new Student("A",100));
oos.flush();

//反序列化
ObjectInputStream  ois = new ObjectInputStream("D:\\Java.txt");
Student stu = (Student)ois.readObject();

随机存取文件流 RandomAccessFile

多线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值