Java基础全方位解析:从入门到精通(零基础学IT)

目录

一、Java语言概述

二、Java安装及环境搭配

2.1检测是否安装成功

三、Java 数据类型(重点)

3.1基本数据类型

3.2类型转换

3.3运算符

3.3.1算术运算符

3.3.2赋值运算符

3.3.3比较运算符

3.3.4逻辑运算符

3.3.5三元运算符

四、Java条件循环

4.1 if-else 条件语句

4.2switch-case 语句

4.3while 循环

4.4 do-while 循环

4.5for 循环

4.6增强型 for 循环(for-each 循环)

4.7break 和 continue 的使用

五、面向对象

5.1定义类并介绍有参无参构造器

5.2继承

5.3equals()

5.4interface接口

六、Java中常见常用的类

6.1Object 类

6.2String 类

6.3 StringBuffer 和 StringBuilder 类

6.4Scanner 类

6.5Math 类

6. 6Random 类

6.7 Date、DateFormat 和 SimpleDateFormat 类

6.8System 类

6.9BigInteger 和 BigDecimal 类

七、ArrayList类

八、自定义异常类

九、关键字

9.1class

9.2public, private, protected

9.3static

9.4final

9.5if, else, for, while

9.6try, catch, finally, throw, throws


一、Java语言概述

Java诞生于1995年,原属于SUN公司,2009年4月20日,美国数据软件巨头甲骨文公司(*Oracle*)宣布以74亿美元收购SUN公司。Java是最受欢迎的开发语言,已经火了20年,并将继续引领着IT的编程语言。

二、Java安装及环境搭配

Java下载地址:Java Archive Downloads - Java SE 8u211 and later (oracle.com)icon-default.png?t=N7T8https://www.oracle.com/java/technologies/javase/javase8u211-later-archive-downloads.html

 路径选择好之后傻瓜式安装(一直点击下一步)

安装好之后找到bin文件夹(个人比较喜欢安装到D盘)

将复制好的路径配置到Path里及安装成功

2.1检测是否安装成功

打开终端输入命令 java -version 

显示版本号即安装成功! 

三、Java 数据类型(重点)

3.1基本数据类型

在Java中,数据类型包括基本数据类型和引用数据类型。以下是一些基本数据类型的代码示例,每个示例都有相应的注释来说明其用法和特点。

public class DataTypesExample {

    public static void main(String[] args) {
        // 基本数据类型示例
        // 整数类型
        byte myByte = 10; // 8位有符号整数,范围 -128 到 127
        short myShort = 500; // 16位有符号整数,范围 -32,768 到 32,767
        int myInt = 10000; // 32位有符号整数,范围 -2^31 到 2^31 - 1
        long myLong = 15000000000L; // 64位有符号整数,范围 -2^63 到 2^63 - 1

        // 浮点类型
        float myFloat = 3.14159f; // 32位IEEE 754浮点数,单精度
        double myDouble = 2.71828; // 64位IEEE 754浮点数,双精度

        // 字符类型
        char myChar = 'A'; // 16位Unicode字符,范围 '\u0000'(0)到 '\uffff'(65,535)

        // 布尔类型
        boolean myBoolean = true; // 逻辑值,true或false

        // 输出变量值
        System.out.println("byte: " + myByte);
        System.out.println("short: " + myShort);
        System.out.println("int: " + myInt);
        System.out.println("long: " + myLong);
        System.out.println("float: " + myFloat);
        System.out.println("double: " + myDouble);
        System.out.println("char: " + myChar);
        System.out.println("boolean: " + myBoolean);
    }
}
  1. 整数类型

    • byte: 用于存储小范围整数值,占用8位,范围在 -128 到 127 之间。
    • short: 用于存储中等范围整数值,占用16位,范围在 -32,768 到 32,767 之间。
    • int: 最常用的整数类型,占用32位,范围在 -2^31 到 2^31 - 1 之间。
    • long: 用于存储大整数值,占用64位,范围在 -2^63 到 2^63 - 1 之间,需要在数值后面加上 L 或 l 表示。
  2. 浮点类型

    • float: 用于存储单精度浮点数,占用32位,通常在数值后面加上 f 或 F 表示。
    • double: 用于存储双精度浮点数,占用64位,默认情况下数值为 double 类型。
  3. 字符类型

    • char: 用于存储Unicode字符,占用16位,可以表示范围从 '\u0000'(0)到 '\uffff'(65,535)的字符。
  4. 布尔类型

    • boolean: 用于存储逻辑值,只能是 true 或 false

这些基本数据类型在Java中非常重要,它们用于存储不同类型的数据,每种类型都有其自身的范围和用途。

3.2类型转换

在Java中,数据类型转换分为隐式转换(自动类型转换)和显式转换(强制类型转换)。以下是一些数据类型转换的示例代码,每个示例都有相应的注释来解释转换的过程和注意事项。

public class TypeConversionExample {

    public static void main(String[] args) {
        // 隐式类型转换(自动类型转换)
        int intValue = 100;
        long longValue = intValue; // int类型向long类型转换,自动转换,没有精度损失

        float floatValue = longValue; // long类型向float类型转换,自动转换,没有精度损失

        // 显式类型转换(强制类型转换)
        double doubleValue = 3.14159;
        int truncatedValue = (int) doubleValue; // double类型向int类型转换,需要显式转换,会损失小数部分

        char charValue = 'A';
        int asciiValue = (int) charValue; // char类型向int类型转换,需要显式转换,会转换为对应的ASCII码值

        // 输出转换后的值
        System.out.println("longValue: " + longValue);
        System.out.println("floatValue: " + floatValue);
        System.out.println("truncatedValue: " + truncatedValue);
        System.out.println("asciiValue: " + asciiValue);
    }
}
  1. 隐式类型转换

    • 隐式类型转换是自动进行的,Java会自动将小范围类型转换为大范围类型,例如将 int 类型转换为 long 类型,或将 long 类型转换为 float 类型。这种转换不会造成数据丢失或精度损失。
  2. 显式类型转换

    • 显式类型转换需要使用强制转换操作符 (type),将大范围类型转换为小范围类型。例如将 double 类型转换为 int 类型,或将 char 类型转换为 int 类型。在这种转换中可能会发生精度损失或数据溢出,需要注意数据是否超出目标类型的范围。
  3. 示例中的转换

    • intValue 是一个 int 类型的变量,将其赋值给 longValue,因为 long 类型的范围比 int 大,所以可以直接赋值,这是隐式类型转换的一个例子。
    • doubleValue 是一个 double 类型的变量,将其强制转换为 int 类型并赋值给 truncatedValue,这是显式类型转换的一个例子,会丢失小数部分。
    • charValue 是一个 char 类型的变量,将其强制转换为 int 类型并赋值给 asciiValue,这也是显式类型转换的一个例子,将字符转换为其对应的ASCII码值。

在进行类型转换时,需要注意数据范围和精度的问题,以避免因为转换而导致意外的数据损失或错误。

3.3运算符

对常量和变量进行操作的符号称为运算符

3.3.1算术运算符

public class ArithmeticOperatorsExample {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        // 加法运算
        int sum = a + b; // sum = 10 + 5 = 15
        System.out.println("Sum: " + sum);

        // 减法运算
        int difference = a - b; // difference = 10 - 5 = 5
        System.out.println("Difference: " + difference);

        // 乘法运算
        int product = a * b; // product = 10 * 5 = 50
        System.out.println("Product: " + product);

        // 除法运算
        int quotient = a / b; // quotient = 10 / 5 = 2
        System.out.println("Quotient: " + quotient);

        // 取模运算(求余数)
        int remainder = a % b; // remainder = 10 % 5 = 0
        System.out.println("Remainder: " + remainder);
    }
}

3.3.2赋值运算符

public class AssignmentOperatorsExample {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        // 简单赋值
        int c = a + b; // c = 15

        // 复合赋值
        c += a; // 等同于 c = c + a,c = 15 + 10 = 25
        System.out.println("c after += operation: " + c);

        c -= b; // 等同于 c = c - b,c = 25 - 5 = 20
        System.out.println("c after -= operation: " + c);

        c *= a; // 等同于 c = c * a,c = 20 * 10 = 200
        System.out.println("c after *= operation: " + c);

        c /= b; // 等同于 c = c / b,c = 200 / 5 = 40
        System.out.println("c after /= operation: " + c);

        c %= a; // 等同于 c = c % a,c = 40 % 10 = 0
        System.out.println("c after %= operation: " + c);
    }
}

3.3.3比较运算符

public class ComparisonOperatorsExample {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        // 相等比较
        boolean isEqual = (a == b); // false
        System.out.println("a == b: " + isEqual);

        // 不等比较
        boolean notEqual = (a != b); // true
        System.out.println("a != b: " + notEqual);

        // 大于比较
        boolean greaterThan = (a > b); // true
        System.out.println("a > b: " + greaterThan);

        // 小于比较
        boolean lessThan = (a < b); // false
        System.out.println("a < b: " + lessThan);

        // 大于等于比较
        boolean greaterThanOrEqual = (a >= b); // true
        System.out.println("a >= b: " + greaterThanOrEqual);

        // 小于等于比较
        boolean lessThanOrEqual = (a <= b); // false
        System.out.println("a <= b: " + lessThanOrEqual);
    }
}

3.3.4逻辑运算符

public class LogicalOperatorsExample {

    public static void main(String[] args) {
        boolean x = true;
        boolean y = false;

        // 逻辑与
        boolean resultAnd = x && y; // false
        System.out.println("x && y: " + resultAnd);

        // 逻辑或
        boolean resultOr = x || y; // true
        System.out.println("x || y: " + resultOr);

        // 逻辑非
        boolean resultNotX = !x; // false
        System.out.println("!x: " + resultNotX);

        boolean resultNotY = !y; // true
        System.out.println("!y: " + resultNotY);
    }
}

3.3.5三元运算符

public class TernaryOperatorExample {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        // 使用三元运算符计算较大的数
        int max = (a > b) ? a : b; // max = (10 > 5) ? 10 : 5 = 10
        System.out.println("Max value: " + max);

        // 使用三元运算符实现条件赋值
        String result = (a % 2 == 0) ? "Even" : "Odd"; // result = (10 % 2 == 0) ? "Even" : "Odd" = "Even"
        System.out.println("Number is: " + result);
    }
}

四、Java条件循环

4.1 if-else 条件语句

public class IfElseExample {

    public static void main(String[] args) {
        int num = 10;

        // 如果 num 大于 0,则输出正数
        if (num > 0) {
            System.out.println("Positive number");
        } else { // 否则输出非正数
            System.out.println("Non-positive number");
        }
    }
}

4.2switch-case 语句

public class SwitchCaseExample {

    public static void main(String[] args) {
        int dayOfWeek = 3;
        String dayName;

        switch (dayOfWeek) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            default:
                dayName = "Invalid day";
                break;
        }

        System.out.println("Day of the week is: " + dayName);
    }
}

4.3while 循环

public class WhileLoopExample {

    public static void main(String[] args) {
        int count = 1;

        // 循环打印数字 1 到 5
        while (count <= 5) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}

4.4 do-while 循环

public class DoWhileLoopExample {

    public static void main(String[] args) {
        int count = 1;

        // 使用 do-while 打印数字 1 到 5
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count <= 5);
    }
}

4.5for 循环

public class ForLoopExample {

    public static void main(String[] args) {
        // 打印数字 1 到 5 使用 for 循环
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count is: " + i);
        }
    }
}

4.6增强型 for 循环(for-each 循环)

import java.util.ArrayList;
import java.util.List;

public class EnhancedForLoopExample {

    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // 使用增强型 for 循环遍历集合
        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }
    }
}

4.7break 和 continue 的使用

public class BreakContinueExample {

    public static void main(String[] args) {
        // 使用 break 语句结束循环
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break; // 当 i 等于 5 时,退出循环
            }
            System.out.println("i: " + i);
        }

        // 使用 continue 语句跳过当前循环
        for (int j = 1; j <= 5; j++) {
            if (j == 3) {
                continue; // 当 j 等于 3 时,跳过本次循环
            }
            System.out.println("j: " + j);
        }
    }
}

五、面向对象

5.1定义类并介绍有参无参构造器

// 定义一个名为Person的类
public class Person {

    // 成员变量
    private String name;
    private int age;

    // 无参构造器
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }

    // 有参构造器
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 方法:设置姓名
    public void setName(String name) {
        this.name = name;
    }

    // 方法:获取姓名
    public String getName() {
        return name;
    }

    // 方法:设置年龄
    public void setAge(int age) {
        this.age = age;
    }

    // 方法:获取年龄
    public int getAge() {
        return age;
    }

    // 方法:显示个人信息
    public void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    // 主方法,用于测试 Person 类
    public static void main(String[] args) {
        // 使用无参构造器创建对象
        Person person1 = new Person();
        person1.displayInfo();  // 输出:Name: Unknown, Age: 0

        // 使用有参构造器创建对象
        Person person2 = new Person("Alice", 30);
        person2.displayInfo();  // 输出:Name: Alice, Age: 30

        // 使用方法修改对象属性
        person1.setName("Bob");
        person1.setAge(25);
        person1.displayInfo();  // 输出:Name: Bob, Age: 25
    }
}

  1. 成员变量

    • name:姓名,类型为 String
    • age:年龄,类型为 int
  2. 构造器

    • public Person():无参构造器,初始化 name 为 "Unknown",age 为 0。
    • public Person(String name, int age):有参构造器,根据传入的参数初始化 name 和 age
  3. 方法

    • public void setName(String name):设置 name 的方法。
    • public String getName():获取 name 的方法。
    • public void setAge(int age):设置 age 的方法。
    • public int getAge():获取 age 的方法。
    • public void displayInfo():显示个人信息的方法,输出 name 和 age
  4. 主方法

    • main 方法用于测试 Person 类的功能,演示了使用无参和有参构造器创建对象,并调用方法设置和获取对象的属性,最后显示对象的信息。

这个例子展示了一个简单的Java类如何定义、实例化和使用。通过构造器和方法,可以有效地管理类的状态和行为。

5.2继承

// 定义一个父类 Animal
class Animal {
    private String name;

    // 父类构造器
    public Animal(String name) {
        this.name = name;
    }

    // 父类方法:显示动物的信息
    public void displayInfo() {
        System.out.println("Animal: " + name);
    }
}

// 定义一个子类 Dog 继承自 Animal
class Dog extends Animal {
    private String breed;

    // 子类构造器
    public Dog(String name, String breed) {
        super(name);  // 调用父类的构造器
        this.breed = breed;
    }

    // 子类方法:显示狗的信息,包括品种
    public void displayInfo() {
        System.out.println("Dog: " + super.getName() + ", Breed: " + breed);
    }
}

// 主类,用于测试继承关系
public class Main {
    public static void main(String[] args) {
        // 创建一个 Animal 对象
        Animal animal = new Animal("Generic Animal");
        animal.displayInfo();  // 输出:Animal: Generic Animal

        // 创建一个 Dog 对象
        Dog dog = new Dog("Buddy", "Labrador");
        dog.displayInfo();  // 输出:Dog: Buddy, Breed: Labrador
    }
}
  1. Animal 类

    • Animal 类是一个简单的父类,有一个 name 成员变量和一个 displayInfo() 方法。
    • 构造器 public Animal(String name) 用于初始化 name
  2. Dog 类

    • Dog 类是 Animal 类的子类,继承了 Animal 类的 name 和 displayInfo() 方法。
    • 添加了 breed 成员变量,并在构造器 public Dog(String name, String breed) 中使用 super(name) 调用父类构造器初始化 name
    • 覆盖了父类的 displayInfo() 方法,输出狗的信息包括品种。
  3. 主类 Main

    • Main 类包含 main() 方法,用于测试继承关系。
    • 创建了一个 Animal 对象和一个 Dog 对象,并分别调用它们的 displayInfo() 方法展示信息。

在这个示例中,Dog 类继承了 Animal 类的属性和方法,并添加了自己的特有属性和方法。这展示了继承在Java中的基本用法和功能。

5.3equals()

在Java中,==equals() 是用来比较对象的方法,但它们的作用和行为有所不同。

  1. == 运算符

    • 在Java中,== 用于比较两个对象的引用是否相同,即它们是否指向同一个内存地址。
    • 如果比较的是基本数据类型,== 则比较它们的值是否相等。
  2. equals() 方法

    • equals() 方法是 Object 类的方法,用于比较两个对象的内容是否相等。
    • 默认情况下,equals() 方法在 Object 类中的实现与 == 运算符的行为相同,即比较引用是否相同。
    • 在Java中,通常需要根据对象的具体类型来重写 equals() 方法,以便比较对象的内容。

下面是一个示例,演示了 ==equals() 的不同之处:

public class EqualityExample {
    public static void main(String[] args) {
        // 创建两个相同内容的字符串对象
        String str1 = new String("hello");
        String str2 = new String("hello");

        // 使用 == 比较对象引用
        System.out.println("Using ==:");
        System.out.println("str1 == str2: " + (str1 == str2));  // false,因为是不同的对象引用

        // 使用 equals 比较对象内容
        System.out.println("\nUsing equals():");
        System.out.println("str1.equals(str2): " + str1.equals(str2));  // true,内容相同

        // 创建两个相同内容的整数对象
        Integer num1 = 1000;
        Integer num2 = 1000;

        // 使用 == 比较对象引用
        System.out.println("\nUsing == with Integer:");
        System.out.println("num1 == num2: " + (num1 == num2));  // false,因为超过了Integer缓存范围,分别指向不同对象

        // 使用 equals 比较对象内容
        System.out.println("\nUsing equals() with Integer:");
        System.out.println("num1.equals(num2): " + num1.equals(num2));  // true,内容相同
    }
}
  1. 字符串比较

    • 创建了两个字符串对象 str1 和 str2,它们内容相同但是是两个不同的对象。
    • 使用 == 比较它们的引用,结果为 false,因为它们不是同一个对象。
    • 使用 equals() 方法比较它们的内容,结果为 true,因为内容相同。
  2. 整数对象比较

    • 创建了两个整数对象 num1 和 num2,它们的值都是 1000
    • 使用 == 比较它们的引用,结果为 false,因为超过了 Integer 缓存范围,分别指向不同的对象。
    • 使用 equals() 方法比较它们的内容,结果为 true,因为它们的值相同。

通过这个示例,可以看出 == 运算符比较的是对象的引用地址,而 equals() 方法比较的是对象的内容。在实际应用中,通常根据具体的业务需求来选择使用哪种比较方法。

5.4interface接口

// 定义一个接口 Animal
interface Animal {
    // 接口方法,没有方法体
    void makeSound();

    // 可以定义常量
    String COLOR = "Brown";  // 默认为 public static final
}

// 定义一个类 Dog 实现 Animal 接口
class Dog implements Animal {
    // 实现接口方法
    public void makeSound() {
        System.out.println("Bark Bark!");
    }

    // 可以有自己的成员变量和方法
    private String breed;

    public Dog(String breed) {
        this.breed = breed;
    }

    public void displayInfo() {
        System.out.println("Dog breed: " + breed);
        System.out.println("Color: " + COLOR);  // 接口中的常量可以直接使用
    }
}

// 主类,用于测试接口和实现类
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("Labrador");
        dog.makeSound();  // 调用实现的接口方法
        dog.displayInfo();  // 调用自己的方法和接口中的常量
    }
}
  1. Animal 接口

    • Animal 是一个接口,定义了一个抽象方法 makeSound(),该方法没有方法体。
    • 接口中可以定义常量,这些常量默认为 public static final,因此在实现类中可以直接使用。
  2. Dog 类实现 Animal 接口

    • Dog 类实现了 Animal 接口,并实现了 makeSound() 方法。
    • Dog 类可以有自己的成员变量(如 breed)和方法(如 displayInfo())。
    • 在 displayInfo() 方法中,展示了如何访问接口中定义的常量 COLOR
  3. 主类 Main

    • Main 类包含 main() 方法,用于测试 Dog 类的功能。
    • 创建一个 Dog 对象,并调用 makeSound() 和 displayInfo() 方法来展示接口的实现和自身的方法。

这个示例展示了如何定义一个接口、实现接口,并在实现类中使用接口方法和常量。接口在Java中用于定义一组方法的规范,而实现接口的类则提供了具体的实现细节。

六、Java中常见常用的类

6.1Object 类

Object 类是所有类的根类,它包含了一些所有对象都具备的基本方法,如 equals(), hashCode(), toString() 等。所有类都直接或间接继承自 Object 类。

public class ObjectExample {
    public static void main(String[] args) {
        Object obj = new Object();
        
        // toString() 方法返回对象的字符串表示
        System.out.println(obj.toString());  // 输出:java.lang.Object@hashcode

        // equals() 方法比较两个对象是否相等(默认实现是比较引用)
        Object obj1 = new Object();
        Object obj2 = new Object();
        System.out.println(obj1.equals(obj2));  // 输出:false
    }
}

6.2String 类

String 类用于表示字符串,是不可变的(immutable)对象。

public class StringExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = new String("Hello");

        // 比较字符串内容使用 equals() 方法
        System.out.println(str1.equals(str2));  // 输出:true

        // 字符串连接
        String fullName = str1 + " World";
        System.out.println(fullName);  // 输出:Hello World

        // 获取字符串长度
        int length = fullName.length();
        System.out.println("Length of string: " + length);  // 输出:Length of string: 11

        // 提取子字符串
        String substr = fullName.substring(6);
        System.out.println("Substring: " + substr);  // 输出:Substring: World
    }
}

6.3 StringBuffer 和 StringBuilder 类

StringBufferStringBuilder 类都用于处理可变的字符串,其中 StringBuffer 是线程安全的,而 StringBuilder 则不是。

public class StringBufferStringBuilderExample {
    public static void main(String[] args) {
        // 使用 StringBuffer
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("Hello");
        stringBuffer.append(" World");
        stringBuffer.insert(5, ",");  // 在指定位置插入字符
        System.out.println(stringBuffer.toString());  // 输出:Hello, World

        // 使用 StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Java");
        stringBuilder.append(" Programming");
        stringBuilder.delete(4, 5);  // 删除指定位置的字符
        System.out.println(stringBuilder.toString());  // 输出:JavaProgramming
    }
}

6.4Scanner 类

Scanner 类用于从用户输入中读取基本类型和字符串。

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 从用户输入读取整数
        System.out.print("Enter an integer: ");
        int num = scanner.nextInt();
        System.out.println("You entered: " + num);

        // 从用户输入读取字符串
        System.out.print("Enter a string: ");
        String str = scanner.next();
        System.out.println("You entered: " + str);

        scanner.close();
    }
}

6.5Math 类

Math 类提供了用于执行基本数学运算的方法,如绝对值、三角函数、指数函数等。

public class MathExample {
    public static void main(String[] args) {
        // 计算绝对值
        double absValue = Math.abs(-3.14);
        System.out.println("Absolute value: " + absValue);  // 输出:Absolute value: 3.14

        // 计算平方根
        double sqrtValue = Math.sqrt(16);
        System.out.println("Square root: " + sqrtValue);  // 输出:Square root: 4.0

        // 计算指数
        double expValue = Math.exp(2);
        System.out.println("Exponential value: " + expValue);  // 输出:Exponential value: 7.3890560989306495
    }
}

6. 6Random 类

Random 类用于生成随机数。

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random();
        
        // 生成随机整数
        int randInt = random.nextInt(100);  // 生成 0 到 99 之间的随机整数
        System.out.println("Random integer: " + randInt);

        // 生成随机双精度浮点数
        double randDouble = random.nextDouble();
        System.out.println("Random double: " + randDouble);

        // 生成随机布尔值
        boolean randBool = random.nextBoolean();
        System.out.println("Random boolean: " + randBool);
    }
}

6.7 Date、DateFormat 和 SimpleDateFormat 类

Date 类表示特定的时间点,而 DateFormatSimpleDateFormat 类用于格式化日期和时间。

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateExample {
    public static void main(String[] args) {
        // 使用 Date 获取当前时间
        Date now = new Date();
        System.out.println("Current time: " + now);

        // 使用 SimpleDateFormat 格式化日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = dateFormat.format(now);
        System.out.println("Formatted date: " + formattedDate);

        // 使用 Calendar 获取特定日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(2024, Calendar.JULY, 4);  // 设置日期为 2024 年 7 月 4 日
        Date specificDate = calendar.getTime();
        System.out.println("Specific date: " + specificDate);
    }
}

6.8System 类

System 类提供了标准输入、输出和错误流的访问方法,以及一些系统相关的实用方法。

public class SystemExample {
    public static void main(String[] args) {
        // 获取当前时间毫秒数
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println("Current time in milliseconds: " + currentTimeMillis);

        // 标准输出
        System.out.println("Hello, World!");

        // 退出程序
        System.exit(0);
    }
}

6.9BigInteger 和 BigDecimal 类

BigInteger 类用于表示任意精度的整数,而 BigDecimal 类用于表示任意精度的十进制数。

import java.math.BigInteger;
import java.math.BigDecimal;

public class BigIntegerBigDecimalExample {
    public static void main(String[] args) {
        // 使用 BigInteger 进行大整数运算
        BigInteger bigInt1 = new BigInteger("12345678901234567890");
        BigInteger bigInt2 = new BigInteger("98765432109876543210");
        BigInteger sum = bigInt1.add(bigInt2);
        System.out.println("Sum of BigIntegers: " + sum);

        // 使用 BigDecimal 进行精确的十进制运算
        BigDecimal bigDecimal1 = new BigDecimal("123.456");
        BigDecimal bigDecimal2 = new BigDecimal("456.789");
        BigDecimal product = bigDecimal1.multiply(bigDecimal2);
        System.out.println("Product of BigDecimals: " + product);
    }
}

七、ArrayList类

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        // 创建一个ArrayList来存储字符串
        ArrayList<String> fruits = new ArrayList<>();

        // 添加元素到ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");

        // 打印ArrayList的大小
        System.out.println("ArrayList的大小是:" + fruits.size());

        // 访问ArrayList中的元素
        System.out.println("第一个水果是:" + fruits.get(0));
        System.out.println("最后一个水果是:" + fruits.get(fruits.size() - 1));

        // 检查ArrayList是否包含特定元素
        System.out.println("是否包含'Cherry':" + fruits.contains("Cherry"));
        System.out.println("是否包含'Grapes':" + fruits.contains("Grapes"));

        // 在指定位置插入元素
        fruits.add(2, "Orange");
        System.out.println("插入后的ArrayList:" + fruits);

        // 修改ArrayList中的元素
        fruits.set(1, "Mango");
        System.out.println("修改后的ArrayList:" + fruits);

        // 删除指定位置的元素
        fruits.remove(3);
        System.out.println("删除后的ArrayList:" + fruits);

        // 清空ArrayList
        fruits.clear();
        System.out.println("清空后的ArrayList:" + fruits);

        // 检查ArrayList是否为空
        System.out.println("ArrayList是否为空:" + fruits.isEmpty());
    }
}
  1. 导入ArrayList类: import java.util.ArrayList;

    • 这行代码导入了Java标准库中的ArrayList类,使得我们可以在程序中使用ArrayList。
  2. 定义ArrayList对象: ArrayList<String> fruits = new ArrayList<>();

    • 创建了一个名为fruits的ArrayList对象,其中存储的是字符串(<String>表示泛型类型为String)。
  3. 添加元素到ArrayList: fruits.add("Apple");

    • 使用add方法向ArrayList中添加元素。
  4. 获取ArrayList的大小: fruits.size()

    • 使用size()方法获取ArrayList中元素的数量。
  5. 访问ArrayList中的元素: fruits.get(0)

    • 使用get(index)方法访问指定索引处的元素。
  6. 检查ArrayList中是否包含元素: fruits.contains("Cherry")

    • 使用contains(element)方法检查ArrayList是否包含特定元素。
  7. 在指定位置插入元素: fruits.add(2, "Orange");

    • 使用add(index, element)方法在指定索引处插入元素。
  8. 修改ArrayList中的元素: fruits.set(1, "Mango");

    • 使用set(index, element)方法修改指定索引处的元素。
  9. 删除指定位置的元素: fruits.remove(3);

    • 使用remove(index)方法删除指定索引处的元素。
  10. 清空ArrayList: fruits.clear();

    • 使用clear()方法清空ArrayList中的所有元素。
  11. 检查ArrayList是否为空: fruits.isEmpty();

    • 使用isEmpty()方法检查ArrayList是否为空。

这个例子演示了如何使用Java中的ArrayList类进行元素的添加、访问、修改、删除以及其他一些操作。ArrayList是动态数组,可以根据需要动态增加或减少其大小,并提供了丰富的方法来操作其元素。

八、自定义异常类

当我们需要在Java中创建自定义异常类时,通常会继承自Java标准库中的Exception类或其子类。以下是一个详细的案例代码,包括如何定义和使用自定义异常类:

// 自定义异常类
class InvalidAgeException extends Exception {
    private int age;

    // 构造函数,接收年龄作为参数
    public InvalidAgeException(int age) {
        this.age = age;
    }

    // 覆盖toString方法,提供异常的详细信息
    @Override
    public String toString() {
        return "InvalidAgeException: Age cannot be negative or zero, but received " + age;
    }
}

// 测试类
public class CustomExceptionExample {
    // 方法用于验证年龄是否合法,如果不合法则抛出自定义异常
    public static void validateAge(int age) throws InvalidAgeException {
        if (age <= 0) {
            throw new InvalidAgeException(age);
        } else {
            System.out.println("Age is valid: " + age);
        }
    }

    public static void main(String[] args) {
        try {
            // 测试合法年龄
            validateAge(25);
            
            // 测试非法年龄,将抛出异常
            validateAge(-2);
        } catch (InvalidAgeException e) {
            // 捕获并处理自定义异常
            System.out.println("Caught an exception: " + e);
        }
    }
}
  1. 自定义异常类 InvalidAgeException

    • 继承自Java中的Exception类。
    • 包含一个私有成员变量age,用于存储引发异常的年龄值。
    • 提供一个构造函数,接收年龄作为参数,用于初始化异常对象。
    • 覆盖toString()方法,以便在捕获异常时打印有用的错误信息。
  2. 测试类 CustomExceptionExample

    • 包含一个静态方法validateAge(int age),用于验证年龄是否合法。
    • 在方法中,如果年龄小于等于0,则抛出InvalidAgeException异常。
    • main方法中进行测试:
      • 调用validateAge(25),输出年龄合法的信息。
      • 调用validateAge(-2),这里会抛出自定义的InvalidAgeException异常。
    • 使用try-catch块捕获并处理异常,打印异常信息。

九、关键字

9.1class

// 定义一个简单的类
public class MyClass {
    private String name;

    public MyClass(String name) {
        this.name = name;
    }

    public void displayName() {
        System.out.println("Name: " + name);
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass("John");
        obj.displayName();
    }
}

9.2publicprivateprotected

// 使用访问修饰符定义类和成员
public class MyClass {
    private String privateField;
    public String publicField;
    protected String protectedField;

    public MyClass() {
        privateField = "private";
        publicField = "public";
        protectedField = "protected";
    }
}

9.3static

// 使用静态变量和静态方法
public class StaticExample {
    private static int count;

    public StaticExample() {
        count++;
    }

    public static void displayCount() {
        System.out.println("Count: " + count);
    }

    public static void main(String[] args) {
        StaticExample obj1 = new StaticExample();
        StaticExample obj2 = new StaticExample();

        StaticExample.displayCount(); // 输出 Count: 2
    }
}

9.4final

// 使用final关键字定义常量和不可继承的类
public final class FinalExample {
    private final int MAX_VALUE = 100;

    public final void displayMaxValue() {
        System.out.println("Maximum Value: " + MAX_VALUE);
    }

    public static void main(String[] args) {
        FinalExample obj = new FinalExample();
        obj.displayMaxValue();
    }
}

9.5ifelseforwhile

// 使用条件语句和循环
public class LoopExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        // for循环
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }

        // while循环
        int sum = 0;
        int j = 1;
        while (j <= 10) {
            sum += j;
            j++;
        }
        System.out.println("Sum: " + sum);

        // if-else条件语句
        int x = 10;
        if (x > 0) {
            System.out.println("Positive number");
        } else {
            System.out.println("Non-positive number");
        }
    }
}

9.6trycatchfinallythrowthrows

// 使用异常处理关键字
public class ExceptionHandling {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[4]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed.");
        }

        // 抛出异常
        validateAge(15);
    }

    public static void validateAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or older.");
        } else {
            System.out.println("Age is valid.");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值