Java SE

2019-04-17  本文已影响0人  hgzzz

环境

  1. 安装JDK(Java Development Kit),Java 语言的软件开发工具包
  2. 配置电脑的PATH环境变量
  3. 安装IDEA

基础语法

  1. 注释:单行使用//单行注释,多行使用/*多行注释*/
  2. 关键字:全部小写,代码编辑器有颜色标记
  3. 常量
  1. 变量:内存中的一小块区域,在执行过程中,其值在一定的范围内改变
  1. 数据类型:Java是强类型语言,针对每一种数据都有明确的数据类型
  1. 类型转换
  1. 标识符:给变量、包、类、方法取的名称
  1. 运算符
  1. 获取键盘输入
package com.syntax;

// 导包
import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        // 创建键盘输入对象
        Scanner sc = new Scanner(System.in);
        // 接收数据
        System.out.println("请输入一个数据:");
        int i = sc.nextInt();
        System.out.println("你输入了:" + i);
    }
}
  1. 流程控制
  1. Random,用于产生随机数
package com.syntax;

import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int number = random.nextInt(10); // [0,10)
        System.out.print(number);
    }
}
  1. 数组:存储多个同一数据类型元素的容器,可以存储基本数据类型或者引用数据类型,长度定义好了则无法改变。
package com.syntax;

public class ArrayDemo {
    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
        for (int x = 0; x < arr.length; x++) {
            for (int y = 0; y < arr[x].length; y++) {
                System.out.println(arr[x][y]);
            }
        }
    }
}

  1. 方法:完成特定功能的代码块
权限修饰符 返回值类型 方法名 (参数类型 参数名1,参数类型 参数名2){
    方法体
    return 返回值
}
权限修饰符:public default(不加修饰符,当前包下可用) private(只能在当前类访问) protected(子类对象)
返回值类型: 限定返回值的类型,如果没有返回值为void
参数类型:限定实参的数据类型
参数名:形参名称
// 定义一个求和函数
package com.syntax;

public class MethodDemo {
    public static void main(String[] args) {
        System.out.println(sum(1,2));
    }
    public static int sum(int a, int b) {
        int c = a + b;
        return c;
    }
}
  1. 代码块 用 {}括起来的代码
  1. 修饰符

面向对象

  1. 类与对象
public Student(name,age) { // 构造方法
    this.name = name;
    this.age = age;
}
  1. 封装
  1. 继承 extends
  1. 抽象 abstract,用于修饰方法和类
  1. 接口:处理单一继承的局限性
  1. 多态:允许将子类类型的指针赋值给父类类型的指针
  1. this关键字:代表所在类的对象引用,super:代码父类的引用
    a. 静态方法随着类加载而加载(优先于对象),所以静态方法中没有this
    b. 通过this()调用子类的构造函数,super()调用父类的构造函数
  2. 字符串对象
  1. 集合类,长度可变
  1. 内部类:嵌套在其他类内部的类
  1. 包装类:封装了基本数据类型的类

IO流

  1. 概述
  1. 分类
// 1. 创建输出流对象
FileWriter fw = new FileWriter("filePath", boolean append);
// 2. 写入内容
fw.write("hello");
// 3. 刷新文件
fw.flush();
// 4. 释放资源
fw.close();
// 内部实现:创建一个文件,创建输出流对象,将该对象指向该文件
// 1. 创建输入流对象
FileReader fr = new FileReader("filePath");
// 2. 读数据 read()  一次读一个字符,返回该字符的ASCII码 使用循环来读出文件所有内容
int ch;
while((ch = fr.read()) != -1) {
    System.out.print((char)ch);
}
// 或者用一次读一个字符数组的方式读取, len 表示读出了几个字符(没读到则为-1)
char[] chs = new char[1024];
int len;
while((len = fr.read(chs)) != -1) {
    System.out.print(new String(chs, 0, len));
}
// 3. 释放资源
fr.close();
public class ObjectOutputStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 对象输出流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Src"));
        Student s1 = new Student("zs", 18);
        Student s2 = new Student("ls", 19);
        Student s3 = new Student("ww", 20);

        oos.writeObject(s1);
        oos.writeObject(s2);
        oos.writeObject(s3);

        // 对象输入流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Src"));
        // 读取对象

        try {
            while (true) {
                Object obj = ois.readObject();
                System.out.println(obj);
            }
        }catch(EOFException e) {
            System.out.println("读完了");
        }

        ois.close();
        oos.close();
    }
}
  1. 复制文件:也就是先读文件,再写文件
  2. 字符缓冲流
  1. File类: 文件和目录路径名的抽象表现形式,File 类的实例是不可变的
File(File parent, String child)
File(String pathname)
File(String parent, String child)
// 获取所有java文件
 public static void getJavaFileName (File file) {
        File[] files = file.listFiles(); // 获取所有的文件和目录的 File 对象数组
        for (File f : files) { // 遍历得到每一个File对象
            if (f.isFile()) {
                if (f.getName().endsWith(".java")) {
                    System.out.println(f);
                }
            }
        }
    }

集合体系结构

// 1. 创建集合对象
ArrayList<String> c = new ArrayList<String>();
c.add("hello");
c.add("world");

// 遍历方式1 Object toArray()
Object[] objs = c.toArray  ();
for (int i = 0; i < objs.length; i++) {
    String s = objs[i];
}
// 遍历方式2 Iterator 注意:迭代器是集合的一个副本,在操作过程中如果集合改变,则会抛出异常
Iterator<String> it = c.iterator();
while(it.hasNext()) {
    String s = it.next();
}
// 遍历方式2 增强for 在底层是和迭代器一样的,所以在使用时也不能去修改集合
for (String s : c) {
    Systen.out.println(s);
}
        // map 的遍历
        Map<String, String> map = new HashMap<>();
        map.put("23号", "James");
        map.put("24号", "Kobe");
        map.put("35号", "Durant");

        // 方式1:获取所有的键 再获取值
        Set<String> keys = map.keySet();:
        // 遍历键 获取值
        for (String key : keys) {
            System.out.println(key + ":" + map.get(key));
        }

        // 方式二,通过内部类 Entry 获取每对键和值
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + ":" + value);
        }

数据结构

  1. 数组
  1. 链表:存储当前地址、当前数据和下一个数据的地址
  1. 栈和队列

异常

  1. 异常:在代码编译或者运行时出现的错误,异常包括错误的类型、原因和位置
  2. 体系结构:Throwable是所以错误和异常的超类
Throwable(最顶层)
  Error(不能处理的严重问题)
  Exception(可以处理的问题)
  1. 异常的处理
try {
// 有可能出错的代码
} catch (Exception e) {  
// 代码出错时执行,处理异常
} finally {
// 一定会执行,用于释放资源、处理垃圾的收尾工作    
}
  1. 异常的分类
  1. 自定义异常
public class ExceptionDemo {
    public static void main(String[] args) {
        checkScore(200);
    }

    public static void checkScore(int score) {
        if (score < 0 || score > 100) {
            throw new ScoreException("成绩错误");
        }
        System.out.println("正确的成绩");
    }
}

class ScoreException extends RuntimeException {
    public ScoreException() {
    }

    public ScoreException(String message) {
        super(message);
    }
}

多线程

  1. 概念
  1. Thread
public class ThreadDemo {
    public static void main(String[] args) {
        // 使用匿名内部类 创建线程1
        Thread t1 = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(this.getName() + "使用匿名内部类实现多线程");
                }
            }
        };


        Thread t2 = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(this.getName() + "使用匿名内部类实现多线程");
                }
            }
        };
        t1.setName("Thread1");
        t2.setName("Thread2");
        t1.start();
        t2.start();
    }
}
  1. 并发问题
    a. synchronized:同步(锁),可以修饰代码块和方法,被修饰的代码块和方法一旦被某个线程访问,则会被锁住,其他线程无法访问
// 效率低
synchronized(锁对象) { // 锁对象需要被所有的线程共享
// 线程代码
}

// 同步方法
public synchronized void method() {
// 锁对象是this,静态方法锁对象是当前类的字节码对象
}
  1. 线程的生命周期
    a. 新建 继承Thread或实现Runable接口
    b. 就绪:已经具备了执行能力,但是没有执行权利
    c. 阻塞、等待(wait() notify()),注意:阻塞状态需要回到就绪状态
    d. 运行
    e. 死亡

网络编程

  1. Socket
  1. 使用UDP协议收发数据
public class UDPSend {
    public static void main(String[] args) throws IOException {
        // 1. 创建Socket对象
        DatagramSocket ds = new DatagramSocket();
        // 2. 创建数据并打包 DatagramPacket(数据包类,需要数据byte[],目标IP和端口号)
        String s = "hello world";
        byte[] bys = s.getBytes(); // 数据
        int length = bys.length; // 要发送数据长度
        InetAddress address = InetAddress.getByName("DESKTOP-7MTQ9R3"); // 目标设备ip
        System.out.println(address);
        int port = 9999; // 目标设备端口
        DatagramPacket dp = new DatagramPacket(bys, length, address, port); // 数据报包
        // 3. 发送数据
        ds.send(dp);

        // 4. 释放资源
        ds.close();
    }
}
public class UDPReceive {
    public static void main(String[] args) throws IOException {
        // 1. 创建接收端Socket对象
        DatagramSocket ds = new DatagramSocket(9999);
        // 2. 接收数据
        byte[] bys = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bys, bys.length); // 接收数据包的容器对象
        System.out.println(1);
        ds.receive(dp); // 阻塞 等待数据
        System.out.println(1);
        // 3. 解析数据
        InetAddress address = dp.getAddress();
        byte[] data = dp.getData(); // 获取接收到的数据
        int length = dp.getLength(); // 获取接收到的数据长度
        // 4. 输出数据
        System.out.println("sender=>" + address.getHostAddress());
        System.out.println(new String(data, 0, length));
        // 5. 释放资源
        ds.close();
    }
}
  1. 使用TCP协议收发数据
// 使用TCP协议发送数据(客户端)
public class TCPSend {
    public static void main(String[] args) throws IOException {
        // 1. 创建发送端(客户端)Socket对象(创建连接)
        Socket s = new Socket(InetAddress.getByName("DESKTOP-7MTQ9R3"), 6666);
        // 2. 获取输出流对象
        OutputStream os = s.getOutputStream();
        // 3. 发送数据
        String str = "hello world";
        os.write(str.getBytes());
        // 4. 释放资源
        os.close();
    }
}
public class TCPReceive {
    public static void main(String[] args) throws IOException {
        // 1. 创建接收端(服务端)Socket对象
        ServerSocket ss = new ServerSocket(6666);
        // 2. 监听接收数据 阻塞 返回一个Socket
        Socket s = ss.accept();
        // 3. 获取输入流对象
        InputStream is = s.getInputStream();
        // 4. 获取数据
        InetAddress address = s.getInetAddress();
        byte[] bys = new byte[1024];
        int len; // 存储读到的数据个数
        len = is.read(bys);
        // 5. 输出数据
        System.out.println("sender=>" + address);
        System.out.println(new String(bys, 0, len));
        // 6. 释放资源
        is.close();
    }
}

扩展

  1. Java中的内存分配


    Java中的内存分配
  2. 成员变量和局部变量区别
上一篇 下一篇

猜你喜欢

热点阅读