1.BigDecimal 精度运算
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalDemo {
public static void main(String[] args) {
// ================== 初始化(必须用字符串避免精度丢失)[6,7](@ref) ==================
BigDecimal num1 = new BigDecimal("10.5");
BigDecimal num2 = new BigDecimal("3.2");
BigDecimal dividend = new BigDecimal("10");
BigDecimal divisor = new BigDecimal("3");
// ================== 基础算术运算 ==================
// 加法 [3,5](@ref)
BigDecimal sum = num1.add(num2);
System.out.println("加法结果: " + sum); // 13.7
// 减法 [3,5](@ref)
BigDecimal difference = num1.subtract(num2);
System.out.println("减法结果: " + difference); // 7.3
// 乘法 [3,5](@ref)
BigDecimal product = num1.multiply(num2);
System.out.println("乘法结果: " + product); // 33.60
// 除法(必须指定舍入模式)[1,5](@ref)
BigDecimal quotient = num1.divide(num2, 2, RoundingMode.HALF_UP);
System.out.println("除法结果: " + quotient); // 3.28
// ================== 数学函数运算 ==================
// 绝对值 [4](@ref)
BigDecimal absValue = num1.abs();
System.out.println("绝对值: " + absValue); // 10.5
// 取反 [4](@ref)
BigDecimal negated = num1.negate();
System.out.println("取反结果: " + negated); // -10.5
// 幂运算(JDK 9+)[1](@ref)
BigDecimal power = num1.pow(2);
System.out.println("平方: " + power); // 110.25
// ================== 精度控制与标度操作 ==================
// 设置标度(保留2位小数,四舍五入)[1,7](@ref)
BigDecimal scaled = new BigDecimal("123.4567").setScale(2, RoundingMode.HALF_UP);
System.out.println("四舍五入后: " + scaled); // 123.46
// 去除尾部零 [1](@ref)
BigDecimal stripped = new BigDecimal("123.45000").stripTrailingZeros();
System.out.println("去除尾部零: " + stripped); // 123.45
// 缩放十次幂 [1](@ref)
BigDecimal scaledByTen = new BigDecimal("123.456789").scaleByPowerOfTen(3);
System.out.println("缩放十次幂: " + scaledByTen); // 123456.789
// ================== 比较与转换 ==================
// 比较大小(忽略标度)[4,7](@ref)
int comparison = num1.compareTo(new BigDecimal("10.50"));
System.out.println("比较结果: " + comparison); // 0(数值相等)
// 转换为基本类型(可能丢失精度)[4](@ref)
double d = num1.doubleValue(); // 10.5
int i = num1.intValue(); // 10(直接截断)
System.out.println("转换为 double: " + d + ", int: " + i);
// 精确转换(超出范围抛异常)[1](@ref)
try {
long lExact = num1.longValueExact(); // 10
System.out.println("精确转换 long: " + lExact);
} catch (ArithmeticException e) {
System.out.println("转换异常: " + e.getMessage());
}
// ================== 特殊运算 ==================
// 余数运算 [1](@ref)
BigDecimal remainder = dividend.remainder(divisor);
System.out.println("余数: " + remainder); // 1
// 求商和余数数组 [1](@ref)
BigDecimal[] divideAndRemainder = dividend.divideAndRemainder(divisor);
System.out.println("商: " + divideAndRemainder[0] + ", 余数: " + divideAndRemainder[1]); // 3, 1
// 最大值/最小值 [1](@ref)
BigDecimal max = num1.max(num2);
BigDecimal min = num1.min(num2);
System.out.println("最大值: " + max + ", 最小值: " + min); // 10.5, 3.2
// ================== 小数点移动 ==================
// 左移2位 [1](@ref)
BigDecimal movedLeft = num1.movePointLeft(2);
System.out.println("小数点左移两位: " + movedLeft); // 0.105
// 右移1位 [1](@ref)
BigDecimal movedRight = num1.movePointRight(1);
System.out.println("小数点右移一位: " + movedRight); // 105.0
}
}
2.类与对象
// 类定义:描述对象的行为和状态
class Dog {
// 实例变量(对象状态)
String name;
String color;
// 方法(对象行为)
void bark() {
System.out.println(name + "在汪汪叫");
}
}
public class TestDog {
public static void main(String[] args) {
// 创建对象实例
Dog myDog = new Dog();
myDog.name = "阿黄";
myDog.color = "黄色";
myDog.bark(); // 输出:阿黄在汪汪叫
}
}
3.变量类型
public class VariablesDemo {
// 成员变量(非静态)
int instanceVar = 10;
// 类变量(静态)
static String classVar = "全局变量";
void method() {
// 局部变量
int localVar = 20;
System.out.println(localVar);
}
public static void main(String[] args) {
System.out.println(classVar); // 直接访问静态变量
VariablesDemo obj = new VariablesDemo();
System.out.println(obj.instanceVar);
obj.method();
}
}
4.数组
public class ArrayDemo {
public static void main(String[] args) {
// 数组声明与初始化
int[] numbers = {1, 2, 3};
String[] names = new String[3];
names[0] = "张三";
// 多维数组
int[][] matrix = {{1,2}, {3,4}};
System.out.println(matrix[1][0]); // 输出3
}
}
5.枚举
// 单独声明枚举类型
enum FreshJuiceSize { SMALL, MEDIUM, LARGE }
class FreshJuice {
FreshJuiceSize size;
}
public class EnumTest {
public static void main(String[] args) {
FreshJuice juice = new FreshJuice();
juice.size = FreshJuiceSize.MEDIUM;
System.out.println(juice.size); // 输出MEDIUM
}
}
6.继承
// 父类
class Animal {
void eat() {
System.out.println("动物进食");
}
}
// 子类继承
class Cat extends Animal {
@Override
void eat() {
System.out.println("猫吃鱼");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat(); // 输出:猫吃鱼
}
}
7.接口
// 接口定义
interface Communication {
void call();
}
// 类实现接口
class Phone implements Communication {
@Override
public void call() {
System.out.println("拨打电话中...");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Phone myPhone = new Phone();
myPhone.call();
}
}
8.修饰符与访问控制
public class ModifierDemo {
// 私有变量(仅本类可访问)
private int privateVar = 1;
// 公开方法
public void publicMethod() {
System.out.println("公开方法");
}
// 静态方法
static void staticMethod() {
System.out.println("类方法");
}
}
9.关键字
/*
██████╗ █████╗ ██╗ ██╗ █████╗ ██╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ ██████╗ ██████╗ ███████╗
██╔════╝ ██╔══██╗ ██║ ██║██╔══██╗ ██║ ██║██╔═══██╗██║ ██║██╔════╝██╔═══██╗██╔══██╗██╔════╝
██║ ███████║ ██║ █╗ ██║███████║ ███████║██║ ██║██║ █╗ ██║██║ ██║ ██║██║ ██║█████╗
██║ ██╔══██║ ██║███╗██║██╔══██║ ██╔══██║██║ ██║██║███╗██║██║ ██║ ██║██║ ██║██╔══╝
╚██████╗ ██║ ██║ ╚███╔███╔╝██║ ██║ ██║ ██║╚██████╔╝╚███╔███╔╝╚██████╗╚██████╔╝██████╔╝███████╗
╚═════╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝
*/
// 访问控制修饰符示例
class AccessModifiers {
private int privateVar; // 仅本类可见
protected void protectMethod() {} // 同包或子类可见
public String publicField; // 全局可见
/* default */ int packageVar; // 包级可见(默认修饰符,不需要显式声明) */
}
// 类/方法/变量修饰符示例
abstract class Animal { // 抽象类
final int LEGS = 4; // 不可修改的常量
static String TYPE = "哺乳动物"; // 类变量
abstract void sound(); // 抽象方法
}
class Dog extends Animal implements Runnable { // 继承+接口实现
volatile boolean status; // 易失变量
transient String tempData; // 不序列化的字段
@Override
synchronized void sound() { // 同步方法
System.out.println("汪汪");
}
strictfp double calculate() { // 严格浮点计算
return 0.1 + 0.2;
}
}
// 程序控制语句示例
class ControlFlow {
void demo() {
for (int i=0; i<5; i++) {
if (i == 3) continue; // 跳过当前循环
switch (i) {
case 1:
System.out.println("一");
break;
default:
System.out.println("其他");
}
}
do { // do-while循环
System.out.println("执行");
} while (false);
while(true) { // 无限循环
return; // 方法返回
}
}
}
// 错误处理示例
class ExceptionDemo {
void test() throws Exception { // 声明可能抛出异常
try {
if (1 > 0) throw new Exception("异常示例");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("最终执行");
}
}
}
// 包与类型示例
package com.example; // 包声明
import java.util.List; // 导入包
class PrimitiveTypes {
boolean flag = true; // 布尔型
byte smallNum = 127; // 字节型
char ch = 'A'; // 字符型
double price = 9.99; // 双精度
float ratio = 3.14f; // 单精度
int count = 100; // 整型
long bigNum = 100000L; // 长整型
short age = 30; // 短整型
}
class ReferenceDemo {
void method() {
this.toString(); // 当前对象引用
super.hashCode(); // 父类方法调用
}
void emptyReturn() { // 无返回值方法
System.out.println("void示例");
}
}
/*
██████╗ ███████╗██████╗ ███████╗██████╗ ██████╗
██╔════╝ ██╔════╝██╔══██╗██╔════╝██╔══██╗██╔═══██╗
██║ ███╗█████╗ ██████╔╝█████╗ ██║ ██║██║ ██║
██║ ██║██╔══╝ ██╔══██╗██╔══╝ ██║ ██║██║ ██║
╚██████╔╝██║ ██║ ██║███████╗██████╔╝╚██████╔╝
╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝
*/
// 注意:以下为保留关键字,不能实际使用
// goto // 跳转语句(未实现)
// const // 常量声明(未实现)
代码结构说明:
访问控制:展示了private/protected/public/default四种访问权限
类修饰符:包含abstract/final/static等核心修饰符
方法控制:演示synchronized/strictfp/transient等特殊修饰符
流程控制:覆盖所有控制语句关键字的使用场景
异常处理:完整try-catch-finally-throw-throws工作流
类型系统:包含8种基本类型+void的声明方式
特殊引用:this/super的实际应用场景
保留关键字:展示未启用的goto/const(注释状态)
10.类与对象定义
// 文件名:Dog.java
public class Dog {
// 成员变量(属性)
private String breed;
private String color;
private int age;
// 类变量(静态变量)
private static int dogCount = 0;
// 构造方法
public Dog(String breed, String color, int age) {
this.breed = breed;
this.color = color;
this.age = age;
dogCount++;
}
// 成员方法(行为)
public void bark() {
System.out.println("Woof! Woof!");
}
// 访问器方法(Getter/Setter)
public String getBreed() { return breed; }
public void setBreed(String breed) { this.breed = breed; }
public static int getDogCount() { return dogCount; }
// 重写 toString 方法
@Override
public String toString() {
return "品种: " + breed + ", 颜色: " + color + ", 年龄: " + age;
}
}
11.继承与多态
// 抽象类示例
abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound(); // 抽象方法
public String getName() { return name; }
}
// 子类继承抽象类
class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() { // 方法重写
System.out.println("Meow!");
}
}
12.接口与多继承
// 定义接口
interface Eatable {
void eat();
}
// 实现接口的类
class Puppy extends Dog implements Eatable {
public Puppy(String breed, String color, int age) {
super(breed, color, age);
}
@Override
public void eat() { // 实现接口方法
System.out.println("Puppy is eating...");
}
// 方法重载(同名方法,参数不同)
public void play(String toy) {
System.out.println("Playing with " + toy);
}
public void play(int hours) {
System.out.println("Playing for " + hours + " hours");
}
}
13.封装与测试类
// 文件名:Main.java
public class Main {
public static void main(String[] args) {
// 创建对象
Dog myDog = new Dog("Golden Retriever", "Golden", 3);
System.out.println(myDog); // 调用 toString()
myDog.bark();
// 测试继承与多态
Animal cat = new Cat("Tom");
cat.makeSound(); // 输出: Meow!
// 测试接口与多态
Puppy puppy = new Puppy("Husky", "Gray", 1);
puppy.eat(); // 输出: Puppy is eating...
puppy.play("Ball"); // 方法重载示例
puppy.play(2);
// 访问静态变量
System.out.println("已创建的小狗数量: " + Dog.getDogCount());
}
}
14.Java 基本数据类型
import java.util.Optional;
/**
* 本类展示 Java 基本数据类型及其相关特性,并包含 JDK 各版本的新特性示例
*/
public class JavaDataTypesDemo {
public static void main(String[] args) {
// ============== 基础数据类型的定义与默认值(JDK 1.0+) ==============
// 整数类型
byte byteVal = 100; // 8位,-128~127
short shortVal = 1000; // 16位,-32768~32767
int intVal = 100000; // 32位(默认整数类型)
long longVal = 100000L; // 64位,需加L后缀
// 浮点类型
float floatVal = 3.14f; // 32位,需加f后缀
double doubleVal = 3.14; // 64位(默认浮点类型)
// 布尔与字符
boolean boolVal = true; // 1位,true/false
char charVal = 'A'; // 16位,Unicode字符
// ============== JDK 5 新特性:自动装箱/拆箱 ==============
// 基本类型与包装类自动转换
Integer autoBoxing = intVal; // 自动装箱(int -> Integer)
int autoUnboxing = autoBoxing; // 自动拆箱(Integer -> int)
// ============== JDK 7 新特性:二进制字面量 & 下划线分隔符 ==============
int binaryLiteral = 0b1010; // 二进制前缀 0b
long underscored = 1_000_000L; // 数字可加下划线增强可读性
// ============== JDK 8 新特性:Optional 处理空引用 ==============
Optional<String> optional = Optional.ofNullable(null);
optional.ifPresentOrElse(
str -> System.out.println(str),
() -> System.out.println("值为空")
);
// ============== JDK 10 新特性:局部变量类型推断 (var) ==============
var inferredInt = 100; // 编译器推断为 int 类型
var inferredList = List.of(1, 2, 3); // 推断为 List<Integer>
// ============== JDK 14 新特性:Record 类(简化不可变数据类) ==============
record Point(int x, int y) {} // 自动生成构造器/getter/equals等方法
Point p = new Point(10, 20);
System.out.println(p.x() + ", " + p.y());
=======================char 转Unicode 数字,表情,文字 ==============
https://apps.timwhitlock.info/emoji/tables/unicode#
https://www.emojiall.com/zh-hans
char c = '并';
System.out.println((int) c); // 输出 20013
String emoji = new String(new int[]{128512}, 0, 1);
System.out.println(emoji); // 输出 😊
int[] codePoints = {0x1F1F7,0x1F601};
String complexEmoji = new String(codePoints, 0, 2);
System.out.println(complexEmoji); // 输出 👩🚀
int[] codes = {119, 111, 114, 108, 100}; // "world" 的码点
StringBuilder word = new StringBuilder();
for (int code : codes) {
word.append((char) code); // 将码点转为字符并拼接
}
System.out.println(word.toString()); // 输出 world
// ============== 类型转换示例 ==============
// 强制转换(可能丢失精度)
double d = 100.5;
int i = (int) d; // 结果为 100(截断小数)
// ============== 其他重要特性 ==============
// JDK 15 文本块(多行字符串)
String json = """
{
"name": "Java",
"version": 17
}
""";
// JDK 16 模式匹配 instanceof
Object obj = "Pattern Matching";
if (obj instanceof String s) { // 直接绑定变量 s
System.out.println(s.length());
}
}
// ============== JDK 9 新特性:私有接口方法 ==============
interface AdvancedMath {
private static void log(String message) {
System.out.println("Log: " + message);
}
default void calculate() {
log("计算开始");
// 实现逻辑...
}
}
}
15.变量命名规则
// 类名:驼峰命名法,首字母大写
public class NamingExample {
// 实例变量:驼峰命名法,首字母小写,通常为 private
private int studentAge;
// 静态变量(驼峰命名法):首字母小写
public static int maxRetries = 3;
// 静态变量(蛇形命名法):全大写+下划线,常用于常量
public static final int MAX_CONNECTIONS = 10;
// 方法参数:驼峰命名法,首字母小写
public void processData(String inputData) {
// 局部变量:驼峰命名法,首字母小写
int temporaryResult = 0;
// 有意义的命名示例
double discountPercentage = 0.15;
// 避免歧义:明确区分开始和结束时间
long startTime = System.currentTimeMillis();
long endTime = startTime + 1000;
// ... 方法逻辑 ...
}
// 常量:全大写+下划线,final 修饰
private static final double TAX_RATE = 0.07;
// 错误示例(仅用于对比)
// private int 1stValue; // 错误:数字开头
// private String class; // 错误:使用关键字
// public static int maxsize; // 错误:未使用驼峰命名
}
public class NamingExample { ... }
private int studentAge;
public static int maxRetries = 3;
public static final int MAX_CONNECTIONS = 10;
int temporaryResult = 0;
double discountPercentage = 0.15;
public void processData(String inputData) { ... }
private static final double TAX_RATE = 0.07;
16.修饰符
// 文件名:ModifiersExample.java
// public类(访问修饰符)
public class ModifiersExample {
// 访问修饰符示例
public int publicVar = 1; // 公有变量
private int privateVar = 2; // 私有变量
protected int protectedVar = 3; // 受保护变量
int defaultVar = 4; // 默认访问变量
// static修饰符
public static int staticVar = 5; // 类变量
private static int instanceCount = 0; // 静态私有计数器
// final修饰符
public static final double PI = 3.1415; // 常量
// volatile修饰符(多线程可见性)
private volatile boolean active = true;
// synchronized方法(线程安全)
public synchronized void increment() {
instanceCount++;
}
// 构造方法
public ModifiersExample() {
instanceCount++;
}
// private方法
private void privateMethod() {
System.out.println("私有方法被调用");
}
// protected方法
protected void protectedMethod() {
System.out.println("受保护的方法被调用");
}
// 默认访问方法
void defaultMethod() {
System.out.println("默认访问方法被调用");
}
// 公有方法访问私有变量(封装性)
public int getPrivateVar() {
return privateVar;
}
// 内部抽象类(abstract修饰符)
public abstract static class AbstractExample {
public abstract void abstractMethod(); // 抽象方法
}
// 内部具体类继承抽象类
public static class ConcreteExample extends AbstractExample {
@Override
public void abstractMethod() {
System.out.println("抽象方法实现");
}
}
// transient变量(不参与序列化)
private transient String transientData = "临时数据";
public static void main(String[] args) {
// 实例化主类
ModifiersExample example = new ModifiersExample();
// 访问不同修饰符的变量
example.publicVar = 10; // 直接访问公有变量
System.out.println("publicVar: " + example.publicVar);
// 访问私有变量需通过公共方法
System.out.println("privateVar via getter: " + example.getPrivateVar());
// 调用不同访问权限的方法
example.protectedMethod();
example.defaultMethod();
// 访问静态变量
System.out.println("staticVar: " + ModifiersExample.staticVar);
// 访问final常量
System.out.println("PI: " + ModifiersExample.PI);
// 调用synchronized方法
example.increment();
System.out.println("instanceCount: " + instanceCount);
// 实例化内部类
ConcreteExample concrete = new ConcreteExample();
concrete.abstractMethod();
// volatile变量操作
example.active = false;
System.out.println("active状态已更新: " + example.active);
}
}
17.运算符
/**
* JavaOperatorsExample 类演示了 Java 中各种运算符的使用方法。
* 包括:算术、关系、位运算、逻辑、赋值、条件运算符等。
*/
public class JavaOperatorsExample {
public static void main(String[] args) {
// --------------------- 1. 算术运算符示例 ---------------------
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b)); // 30
System.out.println("a - b = " + (a - b)); // -10
System.out.println("a * b = " + (a * b)); // 200
System.out.println("b / a = " + (b / a)); // 2
System.out.println("b % a = " + (b % a)); // 0
System.out.println("c % a = " + (c % a)); // 5
System.out.println("a++ = " + (a++)); // 10(先返回原值再自增)
System.out.println("a-- = " + (a--)); // 11(先返回当前值再自减)
System.out.println("d++ = " + (d++)); // 25
System.out.println("++d = " + (++d)); // 27
// --------------------- 2. 自增自减运算符示例 ---------------------
int x = 5;
int y = 2 * ++x; // 前缀自增:x先+1=6,再参与运算
int z = 2 * x++; // 后缀自增:x先参与运算,再+1=7
System.out.println("前缀自增后 x=" + x + ", y=" + y); // x=7, y=12
System.out.println("后缀自增后 x=" + x + ", z=" + z); // x=7, z=12
// --------------------- 3. 关系运算符示例 ---------------------
System.out.println("a == b = " + (a == b)); // false
System.out.println("a != b = " + (a != b)); // true
System.out.println("a > b = " + (a > b)); // false
System.out.println("a < b = " + (a < b)); // true
// --------------------- 4. 位运算符示例 ---------------------
int bitA = 60; // 二进制:0011 1100
int bitB = 13; // 二进制:0000 1101
System.out.println("bitA & bitB = " + (bitA & bitB)); // 12(0000 1100)
System.out.println("bitA | bitB = " + (bitA | bitB)); // 61(0011 1101)
System.out.println("bitA ^ bitB = " + (bitA ^ bitB)); // 49(0011 0001)
System.out.println("~bitA = " + (~bitA)); // -61(1100 0011补码)
System.out.println("bitA << 2 = " + (bitA << 2)); // 240(1111 0000)
System.out.println("bitA >> 2 = " + (bitA >> 2)); // 15(0000 1111)
// --------------------- 5. 逻辑运算符示例 ---------------------
boolean boolA = true;
boolean boolB = false;
System.out.println("boolA && boolB = " + (boolA && boolB)); // false
System.out.println("boolA || boolB = " + (boolA || boolB)); // true
System.out.println("!(boolA && boolB) = " + !(boolA && boolB)); // true
// 短路逻辑运算符示例
int num = 5;
boolean result = (num < 4) && (num++ < 10); // 第一个条件为 false,不会执行第二个条件
System.out.println("result = " + result + ", num = " + num); // false, num=5
// --------------------- 6. 赋值运算符示例 ---------------------
int assignVar = 10;
assignVar += 5; // 等价于 assignVar = assignVar + 5
System.out.println("assignVar += 5 → " + assignVar); // 15
assignVar %= 3; // 等价于 assignVar = assignVar % 3
System.out.println("assignVar %= 3 → " + assignVar); // 0
// --------------------- 7. 条件运算符(三元运算符)示例 ---------------------
int score = 80;
String grade = (score >= 60) ? "及格" : "不及格";
System.out.println("成绩结果:" + grade); // 及格
// --------------------- 8. instanceof 运算符示例 ---------------------
Vehicle vehicle = new Car();
System.out.println("vehicle 是 Car 的实例吗?" + (vehicle instanceof Car)); // true
}
// 定义内部类用于 instanceof 示例
static class Vehicle {}
static class Car extends Vehicle {}
}
18.循环
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class AllLoopsDemo {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry", "Date");
Map<Integer, String> map = Map.of(1, "A", 2, "B", 3, "C");
// ========================
// 基础循环结构 (JDK 1.0+)
// ========================
System.out.println("\n=== 传统 for 循环 ===");
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
System.out.println("\n=== while 循环 ===");
int count = 0;
while (count < fruits.size()) {
System.out.println(fruits.get(count++));
}
System.out.println("\n=== do..while 循环 ===");
int index = 0;
do {
System.out.println(fruits.get(index++));
} while (index < fruits.size());
// ========================
// 增强型循环 (JDK 5+)
// ========================
System.out.println("\n=== 增强型 for 循环 ===");
for (String fruit : fruits) {
System.out.println(fruit);
}
// ========================
// 迭代器模式 (JDK 1.2+)
// ========================
System.out.println("\n=== 迭代器循环 ===");
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// ========================
// JDK 8+ 新特性循环
// ========================
System.out.println("\n=== Stream forEach ===");
fruits.stream().forEach(System.out::println);
System.out.println("\n=== 并行流循环 (JDK8) ===");
fruits.parallelStream().forEach(System.out::println);
System.out.println("\n=== forEach 方法 (JDK8) ===");
fruits.forEach(fruit -> System.out.println(fruit.toUpperCase()));
System.out.println("\n=== 方法引用循环 (JDK8) ===");
fruits.forEach(System.out::println);
// ========================
// JDK 9+ 新特性循环
// ========================
System.out.println("\n=== takeWhile 循环 (JDK9) ===");
Stream.of("A", "B", "C", "", "D")
.takeWhile(s -> !s.isEmpty())
.forEach(System.out::println);
System.out.println("\n=== dropWhile 循环 (JDK9) ===");
Stream.of(2, 4, 6, 8, 9, 10)
.dropWhile(n -> n % 2 == 0)
.forEach(System.out::println);
// ========================
// JDK 16+ 新特性
// ========================
System.out.println("\n=== Stream.mapMulti (JDK16) ===");
record Pair(String k, int v) {}
List<Pair> pairs = List.of(new Pair("A", 1), new Pair("B", 2));
pairs.stream()
.mapMulti((pair, consumer) -> {
consumer.accept(pair.k());
consumer.accept(pair.v());
})
.forEach(System.out::println);
// ========================
// 特殊数据结构循环
// ========================
System.out.println("\n=== Map 遍历 (JDK8+) ===");
map.forEach((k, v) -> System.out.println(k + ":" + v));
System.out.println("\n=== 枚举遍历 ===");
Vector<String> vector = new Vector<>(fruits);
Enumeration<String> en = vector.elements();
while (en.hasMoreElements()) {
System.out.println(en.nextElement());
}
// ========================
// 异步循环 (JDK8+)
// ========================
System.out.println("\n=== CompletableFuture 循环 (JDK8) ===");
List<CompletableFuture<Void>> futures = fruits.stream()
.map(fruit -> CompletableFuture.runAsync(() ->
System.out.println("Async: " + fruit)))
.toList();
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
}
}
19.涵盖条件语句、switch-case
、Number/Math
类、Character
类、String
类、StringBuilder
类
import java.util.Locale;
/**
* 综合示例类:整合条件语句、switch-case、Number/Math、Character、String、StringBuilder 的使用
*/
public class IntegrationExample {
// 示例1:条件语句(链接1) + switch-case(链接2)
public static void evaluateGrade(int score) {
// if-else 条件分支(链接1)
if (score < 0 || score > 100) {
System.out.println("无效分数");
return;
}
// switch-case 判断等级(链接2)
String grade;
switch (score / 10) {
case 10:
case 9:
grade = "A";
break;
case 8:
grade = "B";
break;
case 7:
grade = "C";
break;
case 6:
grade = "D";
break;
default:
grade = "F";
}
System.out.println("得分等级: " + grade);
}
// 示例2:Number/Math 类(链接3) + Character 类(链接4)
public static void numberAndCharDemo() {
// 装箱拆箱(链接3)
Integer numObj = 42; // 自动装箱
int num = numObj; // 自动拆箱
// Math 类方法(链接3)
double sqrtVal = Math.sqrt(num);
long rounded = Math.round(3.6);
// Character 类方法(链接4)
char ch = 'A';
boolean isLetter = Character.isLetter(ch);
boolean isDigit = Character.isDigit('7');
System.out.printf("Math.sqrt(%d)=%.2f, 字符'%c'是字母:%b\n", num, sqrtVal, ch, isLetter);
}
// 示例3:String 类(链接5)操作
public static void stringOperations() {
// 字符串创建与连接
String s1 = "Hello";
String s2 = new String(" World");
String combined = s1.concat(s2).toUpperCase();
// 字符串格式化(链接5)
String formatted = String.format(Locale.US, "格式化示例:%s 长度=%d", combined, combined.length());
// 子字符串操作
String substring = combined.substring(0, 5);
System.out.println(formatted + " | 子串: " + substring);
}
// 示例4:StringBuilder(链接6)高效操作
public static void stringBuilderDemo() {
StringBuilder sb = new StringBuilder();
sb.append("初始内容") // 追加内容
.insert(2, "[插入]") // 在索引2处插入
.delete(5, 7) // 删除索引5-7
.reverse(); // 反转字符串
System.out.println("StringBuilder结果: " + sb);
}
public static void main(String[] args) {
// 执行所有示例
evaluateGrade(85);
numberAndCharDemo();
stringOperations();
stringBuilderDemo();
}
}
20.涵盖数组、日期时间、正则表达式、方法、构造方法、文件 IO、Scanner 和异常处理
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.*;
/**
* 综合示例类,涵盖以下知识点:
* 1. 数组(链接1) 2. 日期时间(链接2) 3. 正则表达式(链接3)
* 4. 方法(链接4) 5. 构造方法(链接5) 6. 文件IO(链接6)
* 7. Scanner(链接7) 8. 异常处理(链接8)
*/
public class IntegratedExamples {
// 自定义异常(对应链接8)
static class InvalidEmailException extends Exception {
public InvalidEmailException(String message) {
super(message);
}
}
// 示例方法:数组操作(对应链接1)
public static void arrayExample() {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("数组遍历:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println("\n数组总和:" + calculateSum(numbers));
}
// 示例方法:计算数组总和(对应链接4的方法定义)
private static int calculateSum(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
// 示例方法:日期时间处理(对应链接2)
public static void dateTimeExample() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间:" + sdf.format(now));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("7天后日期:" + sdf.format(calendar.getTime()));
}
// 示例方法:正则表达式验证邮箱(对应链接3)
public static void validateEmail(String email) throws InvalidEmailException {
String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if (!matcher.matches()) {
throw new InvalidEmailException("无效邮箱格式:" + email);
}
System.out.println("邮箱验证通过:" + email);
}
// 示例方法:文件读写(对应链接6)
public static void fileIOExample() throws IOException {
String fileName = "demo.txt";
try (FileWriter writer = new FileWriter(fileName)) {
writer.write("Hello, File IO!\n");
writer.write("当前时间:" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
}
System.out.println("\n文件内容:");
try (Scanner fileScanner = new Scanner(new File(fileName))) {
while (fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
}
}
// 主方法(整合所有功能)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// 1. 数组操作示例
arrayExample();
// 2. 日期时间示例
dateTimeExample();
// 3. 邮箱验证(用户输入)
System.out.print("\n请输入邮箱地址:");
String email = scanner.nextLine();
validateEmail(email);
// 4. 文件IO操作
fileIOExample();
// 5. 构造方法示例:处理自定义异常
if (!email.contains("@company.com")) {
throw new InvalidEmailException("仅支持公司邮箱");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("数组越界错误:" + e.getMessage());
} catch (InvalidEmailException e) {
System.err.println("邮箱错误:" + e.getMessage());
} catch (IOException e) {
System.err.println("文件操作失败:" + e.getMessage());
} catch (InputMismatchException e) {
System.err.println("输入类型不匹配");
} finally {
scanner.close();
System.out.println("\n程序执行完毕,资源已释放");
}
}
}
21.继承、多态、封装、抽象类、接口、枚举、反射、包 等特性
=================包结构与枚举定义=============
// 文件路径: com/example/enums/AnimalType.java
package com.example.enums;
// 枚举:动物类型
public enum AnimalType {
MAMMAL, BIRD, REPTILE;
}
==================抽象类与封装===========
// 文件路径: com/example/model/Animal.java
package com.example.model;
import com.example.enums.AnimalType;
// 抽象类 + 封装
public abstract class Animal {
// 封装属性
private String name;
private int age;
private AnimalType type;
public Animal(String name, int age, AnimalType type) {
this.name = name;
this.age = age;
this.type = type;
}
// Getter/Setter
public String getName() { return name; }
public int getAge() { return age; }
public AnimalType getType() { return type; }
// 抽象方法
public abstract void makeSound();
// 通用方法(可被重写)
public void eat() {
System.out.println(name + " is eating.");
}
}
=============接口定义=========
// 文件路径: com/example/interfaces/Swimmable.java
package com.example.interfaces;
// 接口
public interface Swimmable {
void swim();
}
=============具体子类实现(继承、多态、重写、接口)========
// 文件路径: com/example/model/Dog.java
package com.example.model;
import com.example.enums.AnimalType;
import com.example.interfaces.Swimmable;
// 继承 + 实现接口 + 重写
public class Dog extends Animal implements Swimmable {
public Dog(String name, int age) {
super(name, age, AnimalType.MAMMAL);
}
@Override
public void makeSound() {
System.out.println(getName() + " says: Woof!");
}
@Override
public void swim() {
System.out.println(getName() + " is swimming.");
}
}
// 文件路径: com/example/model/Penguin.java
package com.example.model;
import com.example.enums.AnimalType;
public class Penguin extends Animal {
public Penguin(String name, int age) {
super(name, age, AnimalType.BIRD);
}
@Override
public void makeSound() {
System.out.println(getName() + " says: Honk!");
}
// 方法重载
public void eat(String food) {
System.out.println(getName() + " is eating " + food);
}
}
===============反射操作类=========
// 文件路径: com/example/util/ReflectionDemo.java
package com.example.util;
import com.example.model.Animal;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
// 反射操作
public class ReflectionDemo {
public static void demoReflection() throws Exception {
// 通过类名获取Class对象
Class<?> clazz = Class.forName("com.example.model.Dog");
// 创建实例
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Animal dog = (Animal) constructor.newInstance("Buddy", 3);
// 调用方法
Method makeSound = clazz.getMethod("makeSound");
makeSound.invoke(dog);
}
}
================= 主类(多态、包、枚举使用===============
// 文件路径: com/example/MainApp.java
package com.example;
import com.example.enums.AnimalType;
import com.example.model.Animal;
import com.example.model.Dog;
import com.example.model.Penguin;
import com.example.util.ReflectionDemo;
public class MainApp {
public static void main(String[] args) throws Exception {
// 多态
Animal animal1 = new Dog("Rex", 2);
Animal animal2 = new Penguin("Pingu", 5);
// 调用重写方法
animal1.makeSound(); // 输出: Rex says: Woof!
animal2.makeSound(); // 输出: Pingu says: Honk!
// 接口方法调用
((Dog) animal1).swim(); // 输出: Rex is swimming.
// 枚举使用
System.out.println(animal2.getType()); // 输出: BIRD
// 反射演示
ReflectionDemo.demoReflection();
}
}
22.结构实现、集合操作、新特性
// 导入所有需要的Java集合类和特性
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.time.LocalDate;
import java.util.stream.Collectors;
/**
* 本类演示Java集合框架核心组件及JDK 1-24关键特性
* 包含数据结构实现、集合操作、新特性应用示例
* 每个操作均包含详细注释说明
*/
public class CollectionExamples {
public static void main(String[] args) {
// ==================== 基础数据结构示例 ====================
// ArrayList示例(JDK 1.2引入)
List<String> arrayList = new ArrayList<>(); // JDK7+ 菱形语法
arrayList.add("Java"); // 添加元素
arrayList.add(0, "Python"); // 在指定位置插入(JDK1.2)
System.out.println("ArrayList: " + arrayList);
// LinkedList示例(JDK 1.2)
Deque<String> linkedList = new LinkedList<>(); // 实现Deque接口(JDK6+)
linkedList.addFirst("First"); // 头部插入(JDK1.6)
linkedList.addLast("Last"); // 尾部插入
System.out.println("LinkedList: " + linkedList);
// HashSet示例(JDK 1.2)
Set<Integer> hashSet = new HashSet<>();
hashSet.add(10);
hashSet.add(10); // 重复元素自动过滤
System.out.println("HashSet: " + hashSet);
// HashMap示例(JDK 1.2)
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 10); // 添加键值对
hashMap.putIfAbsent("Apple", 20); // JDK8+ 方法
System.out.println("HashMap: " + hashMap);
// ==================== 迭代器与遍历 ====================
// 传统迭代器(JDK1.2)
Iterator<String> it = arrayList.iterator();
while(it.hasNext()) {
String element = it.next();
if(element.equals("Python")) {
it.remove(); // 安全删除元素
}
}
// 增强for循环(JDK5+)
for(String s : arrayList) {
System.out.println("ForEach: " + s);
}
// ==================== JDK新特性示例 ====================
// JDK8+ Lambda表达式
arrayList.forEach(element ->
System.out.println("Lambda: " + element));
// JDK8+ Stream API
List<String> filtered = arrayList.stream()
.filter(s -> s.length() > 3) // 过滤
.map(String::toUpperCase) // 转换
.collect(Collectors.toList()); // 收集结果
System.out.println("Stream处理: " + filtered);
// JDK10+ 局部变量类型推断
var varList = List.of("A", "B", "C"); // JDK9+ List.of
// JDK16+ Record类(不可变数据载体)
record Person(String name, int age) {} // 自动生成equals/hashCode
Person p = new Person("Alice", 30);
System.out.println("Record: " + p);
// JDK14+ Switch表达式
String result = switch(p.age()) {
case 30 -> "Young"; // 箭头语法
default -> "Other";
};
System.out.println("Switch表达式: " + result);
// JDK15+ 文本块
String json = """
{
"name": "%s",
"age": %d
}
""".formatted(p.name(), p.age()); // JDK15+ formatted
System.out.println("文本块JSON:\n" + json);
// JDK21+ 虚拟线程(预览特性)
Runnable task = () -> System.out.println(
Thread.currentThread().isVirtual() ? "虚拟线程" : "平台线程");
Thread.ofVirtual().start(task); // 创建虚拟线程
// ==================== 并发集合示例 ====================
// ConcurrentHashMap(JDK5+)
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.computeIfAbsent("key", k -> 100); // JDK8+方法
// CopyOnWriteArrayList(JDK5+)
List<String> cowList = new CopyOnWriteArrayList<>();
cowList.addAll(List.of("线程安全", "写时复制"));
// ==================== 其他重要特性 ====================
// Optional避免空指针(JDK8+)
Optional<String> opt = Optional.ofNullable(null);
System.out.println("Optional: " + opt.orElse("默认值"));
// 时间API(JDK8+)
LocalDate today = LocalDate.now();
System.out.println("当前日期: " + today);
// 模块化系统(JDK9+)
// module-info.java中需要声明: requires java.base;
// 模式匹配instanceof(JDK16+预览,JDK21正式)
Object obj = "字符串";
if(obj instanceof String s && s.length() > 2) {
System.out.println("模式匹配: " + s.toUpperCase());
}
}
}
23.泛型示例代码
================有界类型参数 来限制泛型类型==============
class A {
String name;
public A(String name) {
this.name = name;
}
@Override
public String toString() {
return "A{name='" + name + "'}";
}
}
class B extends A {
public B(String name) {
super(name);
}
}
public class RestrictedGenericMethod {
// 泛型方法,限制只有 A 类或其子类可以调用
public static <T extends A> void process(T obj) {
System.out.println("Processing object: " + obj);
}
public static void main(String[] args) {
A a = new A("Object A");
B b = new B("Object B");
// 调用方法
process(a); // 合法:A 是 T 的上限
process(b); // 合法:B 是 A 的子类
// 如果尝试传入非 A 类型的对象,编译器会报错
// String str = "Hello";
// process(str); // 编译错误:String 不是 A 的子类
}
}
//如果 A 实现了某个接口(如 Comparable<A>),你还可以进一步限制泛型类型:
public static <T extends A & Comparable<T>> void process(T obj) {
System.out.println("Processing object: " + obj);
}
====================泛型=================
// 引入Java 5新特性:泛型(Generics)
public class GenericDemo<T> { // 泛型类定义,T为类型参数(JDK5新特性)
private T data; // 泛型字段,类型由实例化时指定(JDK5)
public GenericDemo(T data) { // 泛型构造方法(JDK5)
this.data = data;
}
// 泛型方法,E为独立类型参数(JDK5)
public static <E> void printElements(E[] elements) {
// 增强for循环(JDK5新特性)
for (E element : elements) {
System.out.print(element + " ");
}
System.out.println();
}
// 有界类型参数:T必须实现Comparable接口(JDK5)
public static <T extends Comparable<T>> T findMax(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
// 类型通配符示例(JDK5)
public static void printWildcardList(List<?> list) {
System.out.println("List Content: " + list.get(0));
}
public static void main(String[] args) {
// 泛型类实例化(JDK5)
GenericDemo<Integer> intDemo = new GenericDemo<>(100);
// 钻石操作符类型推断(JDK7新特性)
System.out.println("Integer Data: " + intDemo.data);
// 泛型方法调用
String[] strArr = {"A", "B", "C"};
printElements(strArr); // 类型自动推断(JDK5)
// 有界泛型方法调用
System.out.println("Max Value: " + findMax(15, 25));
// 类型通配符使用
List<Double> doubleList = List.of(3.14); // List.of(JDK9新特性)
printWildcardList(doubleList);
// var局部变量类型推断(JDK10新特性)
var stringDemo = new GenericDemo<>("Hello Generics");
System.out.println("String Data: " + stringDemo.data);
}
}
24.序列化
// 导入序列化相关类
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 示例类:实现Serializable接口以支持序列化
* JDK 1.1+ 支持基础序列化功能
*/
public class SerializationExample implements Serializable {
// 普通字段,默认支持序列化
private String name;
// transient字段:不参与序列化(JDK 1.1+)
private transient int sensitiveData;
// 静态字段:不会被序列化(属于类级别)
private static String staticField = "Class-Level Data";
/**
* 构造函数
*/
public SerializationExample(String name, int sensitiveData) {
this.name = name;
this.sensitiveData = sensitiveData;
}
/**
* 序列化对象到文件
*/
public void serialize(String filename) {
try (
// 文件输出流(JDK 1.1+)
FileOutputStream fileOut = new FileOutputStream(filename);
// 对象输出流(JDK 1.1+)
ObjectOutputStream out = new ObjectOutputStream(fileOut)
) {
out.writeObject(this); // 将当前对象写入流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从文件反序列化对象
*/
public static SerializationExample deserialize(String filename) {
try (
// 文件输入流(JDK 1.1+)
FileInputStream fileIn = new FileInputStream(filename);
// 对象输入流(JDK 1.1+)
ObjectInputStream in = new ObjectInputStream(fileIn)
) {
// 强制类型转换(JDK 1.5+ 泛型可优化此处)
return (SerializationExample) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 重写toString方法(JDK 1.0+)
*/
@Override
public String toString() {
return "Name: " + name + ", SensitiveData: " + sensitiveData;
}
/**
* 主方法测试序列化与反序列化
*/
public static void main(String[] args) {
// 创建对象
SerializationExample obj = new SerializationExample("Test", 12345);
// 序列化到文件
obj.serialize("example.ser");
// 反序列化后输出
SerializationExample restored = deserialize("example.ser");
System.out.println(restored);
// 输出:Name: Test, SensitiveData: 0(transient字段丢失)
}
}
//JDK 8的Lambda序列化
// Lambda表达式需满足函数式接口且捕获变量可序列化
Serializable lambda = (Serializable & Runnable) () -> System.out.println("Serializable Lambda");
//JDK 17的反序列化过滤器
// 设置反序列化过滤器(阻止特定类)
ObjectInputFilter filter = info -> info.serialClass() == Dangerous.class ? Status.REJECTED : Status.ALLOWED;
ObjectInputStream in = new ObjectInputStream(fileIn).setObjectInputFilter(filter);
//JDK 16的记录类序列化
// 记录类默认可序列化
public record User(String name, int age) implements Serializable {}
25.网络编程
==============客户端实现===========
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
/***
* 支持实时通信的客户端实现
* 启动命令: java ChatClient [主机] [端口]
*/
public class ChatClient {
private static volatile boolean connected = true;
public static void main(String[] args) {
String host = args.length > 0 ? args[0] : "localhost";
int port = parsePort(args);
try (Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
System.out.printf("""
🟢 连接成功
▶ 服务器地址: %s
▶ 输入消息回车发送
▶ 输入 exit 退出
%n""", socket.getRemoteSocketAddress());
// JDK 7 新特性:ForkJoinPool 实现消息并行处理
ForkJoinPool.commonPool().execute(() -> receiveMessages(in));
sendMessages(out);
} catch (ConnectException e) {
System.err.println("🔴 连接被拒绝,请检查:");
System.err.println("1. 服务端是否启动");
System.err.println("2. 防火墙设置");
System.err.println("3. 地址是否正确 (" + host + ":" + port + ")");
} catch (IOException e) {
System.err.println("⚠️ 通信异常: " + e.getMessage());
}
}
private static int parsePort(String[] args) {
try {
return args.length > 1 ? Integer.parseInt(args[1]) : 8080;
} catch (NumberFormatException e) {
System.out.println("❗ 使用默认端口 8080");
return 8080;
}
}
private static void sendMessages(DataOutputStream out) {
try (BufferedReader consoleReader = new BufferedReader(
new InputStreamReader(System.in))) {
while (connected) {
System.out.print("↘ 输入消息: ");
String message = consoleReader.readLine();
out.writeUTF(message);
out.flush();
if ("exit".equalsIgnoreCase(message)) {
connected = false;
System.out.println("⛔ 已断开连接");
}
}
} catch (IOException e) {
System.err.println("消息发送失败: " + e.getMessage());
}
}
private static void receiveMessages(DataInputStream in) {
try {
while (connected) {
String serverMsg = in.readUTF();
System.out.printf("\n[服务器消息] << %s%n↘ 输入消息: ", serverMsg);
}
} catch (EOFException e) {
System.err.println("\n⛔ 连接被服务器关闭");
} catch (IOException e) {
if (connected) {
System.err.println("\n⚠️ 接收消息异常: " + e.getMessage());
}
}
}
}
========================服务端===========
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
/***
* 支持实时通信的服务端实现
* 启动命令: java ChatServer [端口]
*/
public class ChatServer {
private static final int MAX_CLIENTS = 100;
private static final ExecutorService threadPool = Executors.newFixedThreadPool(MAX_CLIENTS);
public static void main(String[] args) {
int port = parsePort(args);
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.printf("""
🚀 服务端已启动
▶ 监听端口: %d
▶ 等待客户端连接...
%n""", port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.printf("✅ 新客户端接入: %s%n",
clientSocket.getRemoteSocketAddress());
// 为每个客户端创建独立会话
threadPool.execute(new ClientHandler(clientSocket));
}
} catch (IOException e) {
System.err.println("⚠️ 服务端异常: " + e.getMessage());
}
}
private static int parsePort(String[] args) {
try {
return args.length > 0 ? Integer.parseInt(args[0]) : 8080;
} catch (NumberFormatException e) {
System.out.println("❗ 使用默认端口 8080");
return 8080;
}
}
/***
* JDK 5 新特性:通过实现Runnable处理并发连接
*/
private static class ClientHandler implements Runnable {
private final Socket socket;
private boolean running = true;
ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
// JDK 8 新特性:CompletableFuture 实现双工通信
CompletableFuture.runAsync(() -> handleOutput(out));
handleInput(in);
} catch (IOException e) {
System.err.println("客户端连接异常: " + e.getMessage());
} finally {
closeResources();
}
}
private void handleInput(DataInputStream in) throws IOException {
while (running) {
String message = in.readUTF();
if ("exit".equalsIgnoreCase(message)) {
System.out.printf("⛔ 客户端 %s 断开连接%n",
socket.getRemoteSocketAddress());
break;
}
System.out.printf("[客户端消息] %s >> %s%n",
socket.getRemoteSocketAddress(), message);
}
}
private void handleOutput(DataOutputStream out) {
try (BufferedReader consoleReader = new BufferedReader(
new InputStreamReader(System.in))) {
while (running) {
System.out.print("↘ 输入服务端消息: ");
String serverMsg = consoleReader.readLine();
out.writeUTF(serverMsg);
out.flush();
}
} catch (IOException e) {
System.err.println("服务端消息发送失败: " + e.getMessage());
}
}
private void closeResources() {
try {
running = false;
if (!socket.isClosed()) socket.close();
} catch (IOException e) {
System.err.println("资源关闭异常: " + e.getMessage());
}
}
}
}
26.发送邮件
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
import com.sun.mail.util.MailSSLSocketFactory;
import java.security.GeneralSecurityException;
/**
* 邮件发送工具类
* 功能:支持文本邮件、HTML邮件、带附件邮件发送
* 支持SMTP服务器认证和SSL加密(适用于QQ邮箱等需要SSL的服务器)
* 依赖:mail.jar 和 activation.jar(需添加到项目构建路径)
*/
public class EmailSender {
// 邮件会话对象
private Session session;
// 发件人邮箱
private String from;
/**
* 构造方法
* @param smtpHost SMTP服务器地址 如"smtp.qq.com"
* @param from 发件邮箱地址
* @param authCode 授权码/密码(QQ邮箱使用授权码)
* @param sslEnabled 是否启用SSL加密
*/
public EmailSender(String smtpHost, String from, String authCode, boolean sslEnabled)
throws GeneralSecurityException {
this.from = from;
Properties props = new Properties();
// 基础配置
props.setProperty("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true"); // 启用认证
// SSL加密配置
if (sslEnabled) {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
props.setProperty("mail.smtp.port", "465"); // QQ邮箱SSL端口
}
// 创建认证器
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, authCode);
}
};
// 创建邮件会话
this.session = Session.getInstance(props, authenticator);
session.setDebug(true); // 启用调试模式(生产环境建议关闭)
}
/**
* 发送文本邮件
* @param to 收件人地址
* @param subject 邮件主题
* @param content 文本内容
*/
public void sendTextEmail(String to, String subject, String content)
throws MessagingException {
MimeMessage message = new MimeMessage(session);
configureBaseMessage(message, to, subject);
message.setText(content); // 设置纯文本内容
Transport.send(message);
}
/**
* 发送HTML邮件
* @param to 收件人地址
* @param subject 邮件主题
* @param htmlContent HTML内容
*/
public void sendHtmlEmail(String to, String subject, String htmlContent)
throws MessagingException {
MimeMessage message = new MimeMessage(session);
configureBaseMessage(message, to, subject);
message.setContent(htmlContent, "text/html;charset=utf-8"); // 设置HTML内容
Transport.send(message);
}
/**
* 发送带附件的邮件
* @param to 收件人地址
* @param subject 邮件主题
* @param textContent 正文内容
* @param filePath 附件文件路径
*/
public void sendAttachmentEmail(String to, String subject, String textContent, String filePath)
throws MessagingException {
MimeMessage message = new MimeMessage(session);
configureBaseMessage(message, to, subject);
// 创建多重消息容器
MimeMultipart multipart = new MimeMultipart();
// 添加文本内容
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(textContent);
multipart.addBodyPart(textPart);
// 添加附件
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(filePath);
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName(source.getName());
multipart.addBodyPart(attachmentPart);
// 设置完整消息
message.setContent(multipart);
Transport.send(message);
}
/**
* 配置基础邮件信息(发件人、收件人、主题)
*/
private void configureBaseMessage(MimeMessage message, String to, String subject)
throws MessagingException {
message.setFrom(new InternetAddress(this.from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
}
}
27.多线程编程
/***
* Java多线程编程综合演示类
* 本类演示了三种创建线程的方式及常用线程方法的使用
*/
public class MultiThreadingDemo {
/***
* 一、通过实现Runnable接口创建线程(推荐方式)
* 优点:
* 1. 避免Java单继承的限制
* 2. 便于多个线程共享资源
* 3. 符合面向接口编程原则
*/
static class RunnableExample implements Runnable {
private final String threadName;
public RunnableExample(String name) {
this.threadName = name;
System.out.println("创建Runnable线程: " + threadName);
}
@Override
public void run() {
System.out.println("运行中: " + threadName);
try {
for (int i = 3; i > 0; i--) {
System.out.println(threadName + " 倒计时: " + i);
Thread.sleep(500); // 阻塞状态示例
}
} catch (InterruptedException e) {
System.out.println(threadName + " 被中断");
}
System.out.println(threadName + " 退出");
}
}
/***
* 二、通过继承Thread类创建线程
* 注意:
* 1. Java不支持多继承,因此限制了扩展能力
* 2. 直接调用run()只是普通方法,必须通过start()启动线程
*/
static class ThreadSubclassExample extends Thread {
public ThreadSubclassExample(String name) {
super(name);
System.out.println("创建Thread子类线程: " + getName());
}
@Override
public void run() {
System.out.println("运行中: " + getName());
try {
for (int i = 3; i > 0; i--) {
System.out.println(getName() + " 倒计时: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println(getName() + " 被中断");
}
System.out.println(getName() + " 退出");
}
}
/***
* 三、通过Callable和Future创建线程(可获取返回值)
* 特点:
* 1. 可以返回执行结果
* 2. 可以抛出异常
* 3. 配合线程池使用更高效
*/
static class CallableExample implements java.util.concurrent.Callable<Integer> {
private final String taskName;
public CallableExample(String name) {
this.taskName = name;
}
@Override
public Integer call() throws Exception {
System.out.println(taskName + " 开始执行");
int sum = 0;
for (int i = 1; i <= 3; i++) {
sum += i;
System.out.println(taskName + " 计算中: " + i);
Thread.sleep(500);
}
return sum;
}
}
/***
* 主方法 - 线程调度演示
*/
public static void main(String[] args) {
// 演示线程优先级(1-10,默认5)
final int MIN_PRIORITY = Thread.MIN_PRIORITY; // 1
final int NORM_PRIORITY = Thread.NORM_PRIORITY;// 5
final int MAX_PRIORITY = Thread.MAX_PRIORITY; // 10
// 1. 使用Runnable方式创建线程
Runnable runnableDemo = new RunnableExample("Runnable线程-1");
Thread thread1 = new Thread(runnableDemo);
thread1.setPriority(MAX_PRIORITY); // 设置最高优先级
// 2. 使用Thread子类方式创建线程
ThreadSubclassExample thread2 = new ThreadSubclassExample("Thread子类-2");
thread2.setPriority(MIN_PRIORITY); // 设置最低优先级
// 3. 使用Callable方式创建线程
java.util.concurrent.FutureTask<Integer> futureTask =
new java.util.concurrent.FutureTask<>(new CallableExample("Callable任务"));
Thread thread3 = new Thread(futureTask);
// 启动所有线程
thread1.start();
thread2.start();
thread3.start();
try {
// 等待thread3执行完成
thread3.join(2000); // 最多等待2秒
if (futureTask.isDone()) {
System.out.println("\nCallable任务结果: " + futureTask.get());
}
// 中断演示
thread1.interrupt();
// 判断线程状态
System.out.println("\n线程状态:");
System.out.println("thread1 存活状态: " + thread1.isAlive());
System.out.println("thread2 存活状态: " + thread2.isAlive());
System.out.println("thread3 存活状态: " + thread3.isAlive());
} catch (Exception e) {
e.printStackTrace();
}
// 守护线程示例(当所有非守护线程结束时自动终止)
Thread daemonThread = new Thread(() -> {
while (true) {
System.out.println("守护线程运行中...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
});
daemonThread.setDaemon(true);
daemonThread.start();
}
/***
* 线程生命周期说明:
* 1. 新建状态(New):线程对象被创建
* 2. 就绪状态(Runnable):调用start()后进入就绪队列
* 3. 运行状态(Running):获得CPU时间片开始执行run()
* 4. 阻塞状态(Blocked):遇到sleep()/wait()/同步锁等情况
* 5. 终止状态(Terminated):run()执行结束或发生异常
*
* 重要方法说明:
* - start(): 启动线程进入就绪状态
* - sleep(): 使线程暂停指定时间(不释放锁)
* - join(): 等待目标线程终止
* - yield(): 让出当前CPU时间片
* - interrupt(): 中断线程
* - setDaemon(): 设置为守护线程
*/
}
28.基础Applet程序
/*
* 示例:基础Applet程序 - HelloWorldApplet
* 功能:在浏览器中显示"Hello World"文本,演示Applet基础结构
*/
// 导入必要的包
import java.applet.Applet; // Applet基类
import java.awt.Graphics; // 图形绘制类
/***
* HelloWorldApplet类继承自java.applet.Applet
* 这是所有Applet程序的基类,提供生命周期管理和浏览器交互能力
*/
public class HelloWorldApplet extends Applet {
/***
* paint方法(重写自Container类)
* 作用:执行图形界面绘制,当以下情况会自动调用:
* 1. Applet首次加载
* 2.浏览器窗口调整大小
* 3.repaint()方法被调用时
/*
* @param g 图形上下文对象,由浏览器自动创建并传递
* 包含绘制区域、颜色、字体等图形状态信息
*/
@Override
public void paint(Graphics g) {
/*
* 使用Graphics对象的drawString方法绘制文本
* 参数说明:
* 第1个参数:"Hello World" - 要显示的字符串
* 第2个参数:25 - 文本基线起始X坐标(像素)
* 第3个参数:50 - 文本基线起始Y坐标(像素)
*
* 坐标系说明:
* 原点(0,0)位于Applet显示区域的左上角
* X轴向右延伸,Y轴向下延伸
*/
g.drawString("Hello World", 25, 50);
}
/*
* Applet生命周期方法说明(未在本示例中重写的方法):
*
* 1. init():
* - 首次加载时调用
* - 用于初始化变量、加载资源、设置布局等
* - 在param标签处理完成后执行
*
* 2. start():
* - init()之后自动调用
* - 每次页面获得焦点时调用(如浏览器切换回页面)
* - 启动动画、线程等需要持续运行的功能
*
* 3. stop():
* - 当页面失去焦点时调用(如切换浏览器标签)
* - 暂停消耗资源的操作以节省系统资源
*
* 4. destroy():
* - 浏览器正常关闭时调用
* - 释放系统资源、保存状态等收尾操作
*/
}
/*
* 配套HTML文件示例(需与.class文件同目录):
*
* <html>
* <head>
* <title>Hello World Applet Demo</title>
* </head>
* <body>
* <hr>
* <applet
* code="HelloWorldApplet.class"
* width="300"
* height="100"
* >
* 您的浏览器不支持Java Applet,请使用支持Java的浏览器查看
* </applet>
* <hr>
* </body>
* </html>
*
* HTML参数说明:
* code - 指定主类文件名(需包含.class扩展名)
* width - Applet显示区域宽度(像素)
* height - Applet显示区域高度(像素)
*/
29.注释
/**
* <p>项目名称: JavaDocDemo</p>
* <p>文件名称: Student.java</p>
* <p>描述: [学生信息模型类,用于管理学生基本数据和操作]</p>
* <p>创建时间: 2023-10-10</p>
* <p>公司信息: XXX公司 技术部</p>
* @author <a href="mailto:author@example.com">张三</a>
* @version v1.0
* @update [1][2023-10-11][李四][新增年龄验证逻辑]
*/
public class Student {
// 类实现...
}
/** 学生姓名 */
private String name;
/** 学生年龄(需大于0) */
private int age;
/**
* @Title: Student
* @Description: [构造方法,初始化学生姓名和年龄]
* @Param: name 学生姓名
* @Param: age 学生年龄
* @exception IllegalArgumentException 当年龄小于0时抛出
* @author <a href="mailto:author@example.com">张三</a>
* @CreateDate: 2023-10-10 14:30:00
*/
public Student(String name, int age) {
if (age < 0) throw new IllegalArgumentException("年龄无效");
this.name = name;
this.age = age;
}
/**
* @Title: getAge
* @Description: [获取学生年龄]
* @Return: int 学生年龄
* @author <a href="mailto:author@example.com">张三</a>
* @CreateDate: 2023-10-10 14:30:00
*/
public int getAge() {
return age;
}
/**
* @Title: setAge
* @Description: [设置学生年龄,年龄必须大于0]
* @Param: age 学生年龄
* @exception IllegalArgumentException 当年龄小于0时抛出
* @author <a href="mailto:author@example.com">张三</a>
* @CreateDate: 2023-10-10 14:30:00
* @update [1][2023-10-11][李四][新增年龄验证逻辑]
*/
public void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("年龄无效");
this.age = age;
}
30.MySQL 连接工具类实现
package com.example.dbutils;
import java.sql.*;
/**
* MySQL数据库连接工具类
* 功能说明:
* 1. 封装MySQL数据库连接、查询、资源释放等操作
* 2. 支持MySQL 8.0+版本的特殊配置
* 3. 提供基本查询执行和结果处理功能
*/
public class MySQLConnector {
// 数据库连接参数配置
private static final String DEFAULT_DRIVER = "com.mysql.cj.jdbc.Driver"; // MySQL 8.0+驱动类
private final String jdbcUrl; // 数据库连接URL
private final String username; // 数据库用户名
private final String password; // 数据库密码
private Connection connection; // 数据库连接对象
private Statement statement; // SQL执行对象
private ResultSet resultSet; // 结果集对象
/**
* 构造方法
* @param jdbcUrl 数据库连接URL,格式示例:
* jdbc:mysql://localhost:3306/dbname?useSSL=false&serverTimezone=UTC
* @param username 数据库用户名
* @param password 数据库密码
*/
public MySQLConnector(String jdbcUrl, String username, String password) {
this.jdbcUrl = jdbcUrl;
this.username = username;
this.password = password;
}
/**
* 初始化数据库连接
* @throws ClassNotFoundException 驱动类未找到异常
* @throws SQLException 数据库连接失败异常
*/
public void connect() throws ClassNotFoundException, SQLException {
// 1. 加载JDBC驱动(MySQL 8.0+需要显式指定)
Class.forName(DEFAULT_DRIVER);
// 2. 建立数据库连接
System.out.println("正在连接数据库...");
connection = DriverManager.getConnection(jdbcUrl, username, password);
// 3. 创建Statement对象(后续执行SQL使用)
statement = connection.createStatement();
}
/**
* 执行查询SQL语句
* @param sql 需要执行的SELECT语句
* @return ResultSet 查询结果集
* @throws SQLException SQL执行异常
*/
public ResultSet executeQuery(String sql) throws SQLException {
if (statement == null) {
throw new SQLException("Statement未初始化,请先调用connect()方法");
}
System.out.println("正在执行查询: " + sql);
resultSet = statement.executeQuery(sql);
return resultSet;
}
/**
* 打印查询结果(示例方法)
* @throws SQLException 结果集处理异常
*/
public void printResults() throws SQLException {
if (resultSet == null) {
System.out.println("没有可用的结果集");
return;
}
// 获取结果集元数据(用于获取列信息)
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍历结果集
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
Object value = resultSet.getObject(i);
System.out.printf("%s: %s\t", columnName, value);
}
System.out.println();
}
}
/**
* 关闭数据库资源
*/
public void close() {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
System.out.println("数据库连接已关闭");
} catch (SQLException e) {
System.err.println("关闭连接时发生错误:");
e.printStackTrace();
}
}
/**
* 使用示例
*/
public static void main(String[] args) {
// 配置连接参数(根据实际环境修改)
String url = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String user = "root";
String pass = "123456";
MySQLConnector dbConnector = new MySQLConnector(url, user, pass);
try {
// 1. 建立连接
dbConnector.connect();
// 2. 执行查询
String query = "SELECT id, name, url FROM websites";
dbConnector.executeQuery(query);
// 3. 处理结果(这里演示打印结果)
System.out.println("查询结果:");
dbConnector.printResults();
} catch (ClassNotFoundException e) {
System.err.println("JDBC驱动加载失败,请检查驱动包是否存在");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("数据库操作异常:");
e.printStackTrace();
} finally {
// 4. 确保关闭连接
dbConnector.close();
}
}
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...