重庆特种作业证查询外贸网站谷歌seo
文章目录
- 一、Java语言概述
- 1.1 Java特点
- 1.2 JVM、JRE、JDK关系
- 二、基础语法
- 2.1 数据类型
- 基本数据类型(8种)
- 引用数据类型
- 2.2 变量与常量
- 2.3 运算符
- 三、流程控制
- 3.1 分支结构
- 3.2 循环结构
- 3.3 跳转语句
- 四、面向对象编程
- 4.1 类与对象
- 4.2 封装、继承、多态
- 封装
- 继承
- 多态
- 4.3 抽象类与接口
- 抽象类
- 接口
- 五、异常处理
- 5.1 异常体系
- 5.2 异常处理机制
- 5.3 自定义异常
- 六、集合框架
- 6.1 集合体系
- 6.2 常用集合类
- List示例
- Set示例
- Map示例
- 6.3 集合工具类
- 七、IO流
- 7.1 流分类
- 7.2 常用IO操作
- 文件读写
- 对象序列化
- 八、多线程
- 8.1 线程创建方式
- 8.2 线程同步
- 8.3 线程池
- 九、Java新特性
- 9.1 Java 8重要特性
- Lambda表达式
- Stream API
- 方法引用
- 9.2 Java 11特性
- 局部变量类型推断
- 字符串增强
- 9.3 Java 17特性
- 密封类(Sealed Classes)
- 模式匹配
- 十、最佳实践与常见问题
- 10.1 编码规范
- 10.2 常见问题
- 10.3 调试技巧
一、Java语言概述
1.1 Java特点
- 跨平台性:Write Once, Run Anywhere(一次编写,到处运行)
- 面向对象:封装、继承、多态
- 健壮性:强类型机制、异常处理、垃圾回收
- 多线程:内置多线程支持
- 安全性:字节码验证、安全管理机制
1.2 JVM、JRE、JDK关系
- JDK(Java Development Kit):Java开发工具包,包含JRE和开发工具
- JRE(Java Runtime Environment):Java运行环境,包含JVM和核心类库
- JVM(Java Virtual Machine):Java虚拟机,执行字节码文件
二、基础语法
2.1 数据类型
基本数据类型(8种)
类型 | 大小 | 默认值 | 取值范围 |
---|---|---|---|
byte | 1字节 | 0 | -128 ~ 127 |
short | 2字节 | 0 | -32768 ~ 32767 |
int | 4字节 | 0 | -2^31 ~ 2^31-1 |
long | 8字节 | 0L | -2^63 ~ 2^63-1 |
float | 4字节 | 0.0f | ±3.4E+38(有效位数6-7位) |
double | 8字节 | 0.0d | ±1.7E+308(有效位数15位) |
char | 2字节 | ‘\u0000’ | ‘\u0000’ ~ ‘\uffff’ |
boolean | - | false | true/false |
引用数据类型
- 类(Class)
- 接口(Interface)
- 数组(Array)
- 枚举(Enum)
- 注解(Annotation)
2.2 变量与常量
// 变量声明
int age = 25;
String name = "张三";// 常量(final修饰)
final double PI = 3.1415926;
2.3 运算符
类型 | 运算符示例 |
---|---|
算术运算符 | + - * / % ++ – |
关系运算符 | > < >= <= == != |
逻辑运算符 | && || ! & | ^ |
位运算符 | & | ^ ~ << >> >>> |
赋值运算符 | = += -= *= /= %= &= |= ^= <<= >>= >>>= |
条件运算符 | (条件) ? 表达式1 : 表达式2 |
instanceof | 检查对象是否是特定类的实例 |
三、流程控制
3.1 分支结构
// if-else
if (score >= 90) {System.out.println("优秀");
} else if (score >= 60) {System.out.println("及格");
} else {System.out.println("不及格");
}// switch-case
switch (day) {case 1:System.out.println("周一");break;case 2:System.out.println("周二");break;// ...default:System.out.println("无效输入");
}
3.2 循环结构
// for循环
for (int i = 0; i < 10; i++) {System.out.println(i);
}// while循环
int i = 0;
while (i < 10) {System.out.println(i);i++;
}// do-while循环
int j = 0;
do {System.out.println(j);j++;
} while (j < 10);// 增强for循环(foreach)
int[] numbers = {1, 2, 3};
for (int num : numbers) {System.out.println(num);
}
3.3 跳转语句
// break
for (int i = 0; i < 10; i++) {if (i == 5) break; // 跳出循环System.out.println(i);
}// continue
for (int i = 0; i < 10; i++) {if (i % 2 == 0) continue; // 跳过本次循环System.out.println(i);
}// return
public int add(int a, int b) {return a + b; // 返回结果并结束方法
}
四、面向对象编程
4.1 类与对象
// 类定义
public class Person {// 成员变量(属性)private String name;private int age;// 构造方法public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}// 成员方法public void introduce() {System.out.println("我叫" + name + ",今年" + age + "岁");}// getter/setterpublic String getName() {return name;}public void setName(String name) {this.name = name;}
}// 创建对象
Person p1 = new Person();
Person p2 = new Person("张三", 25);
p2.introduce();
4.2 封装、继承、多态
封装
public class Student {private String name;private int score;// 提供公共方法访问私有属性public int getScore() {return score;}public void setScore(int score) {if (score >= 0 && score <= 100) {this.score = score;} else {System.out.println("分数不合法");}}
}
继承
// 父类
public class Animal {public void eat() {System.out.println("动物吃东西");}
}// 子类
public class Dog extends Animal {@Overridepublic void eat() {System.out.println("狗吃骨头");}public void bark() {System.out.println("汪汪叫");}
}// 使用
Dog dog = new Dog();
dog.eat(); // 调用子类重写方法
dog.bark(); // 调用子类特有方法
多态
Animal animal = new Dog(); // 向上转型
animal.eat(); // 实际调用Dog类的eat方法// 向下转型
if (animal instanceof Dog) {Dog dog = (Dog) animal;dog.bark();
}
4.3 抽象类与接口
抽象类
public abstract class Shape {// 抽象方法(无实现)public abstract double area();// 普通方法public void printInfo() {System.out.println("这是一个形状");}
}public class Circle extends Shape {private double radius;public Circle(double radius) {this.radius = radius;}@Overridepublic double area() {return Math.PI * radius * radius;}
}
接口
public interface USB {// 常量String VERSION = "3.0";// 抽象方法void transferData();// 默认方法(Java 8+)default void powerOn() {System.out.println("USB设备通电");}// 静态方法(Java 8+)static void showVersion() {System.out.println("USB版本:" + VERSION);}
}public class FlashDisk implements USB {@Overridepublic void transferData() {System.out.println("U盘传输数据");}
}
五、异常处理
5.1 异常体系
- Throwable
- Error:系统错误(如内存溢出)
- Exception
- RuntimeException:运行时异常(如空指针、数组越界)
- 非RuntimeException:检查异常(如IO异常、SQL异常)
5.2 异常处理机制
try {// 可能抛出异常的代码FileInputStream fis = new FileInputStream("test.txt");int data = fis.read();
} catch (FileNotFoundException e) {System.out.println("文件未找到");
} catch (IOException e) {System.out.println("IO异常");
} finally {// 无论是否发生异常都会执行System.out.println("资源清理");
}// try-with-resources(Java 7+)
try (FileInputStream fis = new FileInputStream("test.txt")) {int data = fis.read();
} catch (IOException e) {e.printStackTrace();
}
5.3 自定义异常
public class MyException extends Exception {public MyException() {super();}public MyException(String message) {super(message);}
}// 使用
public void checkAge(int age) throws MyException {if (age < 0) {throw new MyException("年龄不能为负数");}
}
六、集合框架
6.1 集合体系
- Collection
- List:有序可重复
- ArrayList
- LinkedList
- Vector
- Set:无序不重复
- HashSet
- TreeSet
- LinkedHashSet
- Queue:队列
- LinkedList
- PriorityQueue
- List:有序可重复
- Map:键值对
- HashMap
- TreeMap
- LinkedHashMap
- Hashtable
6.2 常用集合类
List示例
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");// 遍历
for (String lang : list) {System.out.println(lang);
}// 使用迭代器
Iterator<String> it = list.iterator();
while (it.hasNext()) {System.out.println(it.next());
}
Set示例
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(1); // 重复元素不会被添加System.out.println(set.size()); // 输出2
Map示例
Map<String, Integer> map = new HashMap<>();
map.put("语文", 90);
map.put("数学", 95);
map.put("英语", 88);// 遍历
for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());
}// Java 8+遍历
map.forEach((k, v) -> System.out.println(k + ": " + v));
6.3 集合工具类
// Collections工具类
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9);
Collections.sort(numbers); // 排序
Collections.reverse(numbers); // 反转
Collections.shuffle(numbers); // 随机打乱// Arrays工具类
int[] arr = {3, 1, 4, 1, 5, 9};
Arrays.sort(arr); // 排序
int index = Arrays.binarySearch(arr, 4); // 二分查找
七、IO流
7.1 流分类
- 按方向:
- 输入流(InputStream/Reader)
- 输出流(OutputStream/Writer)
- 按处理单位:
- 字节流(InputStream/OutputStream)
- 字符流(Reader/Writer)
- 按功能:
- 节点流(直接操作数据源)
- 处理流(包装其他流)
7.2 常用IO操作
文件读写
// 字节流读写
try (FileInputStream fis = new FileInputStream("input.txt");FileOutputStream fos = new FileOutputStream("output.txt")) {byte[] buffer = new byte[1024];int len;while ((len = fis.read(buffer)) != -1) {fos.write(buffer, 0, len);}
}// 字符流读写
try (FileReader fr = new FileReader("input.txt");FileWriter fw = new FileWriter("output.txt")) {char[] buffer = new char[1024];int len;while ((len = fr.read(buffer)) != -1) {fw.write(buffer, 0, len);}
}// 缓冲流(提高效率)
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {String line;while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();}
}
对象序列化
// 实现Serializable接口
public class Student implements Serializable {private static final long serialVersionUID = 1L;private String name;private int age;// ...
}// 序列化对象
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.dat"))) {Student stu = new Student("张三", 20);oos.writeObject(stu);
}// 反序列化
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.dat"))) {Student stu = (Student) ois.readObject();System.out.println(stu.getName());
}
八、多线程
8.1 线程创建方式
// 1. 继承Thread类
class MyThread extends Thread {@Overridepublic void run() {System.out.println("线程运行");}
}// 2. 实现Runnable接口
class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("线程运行");}
}// 3. 实现Callable接口(可返回结果)
class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {return "线程执行结果";}
}// 使用
new MyThread().start(); // 方式1new Thread(new MyRunnable()).start(); // 方式2FutureTask<String> task = new FutureTask<>(new MyCallable());
new Thread(task).start();
String result = task.get(); // 获取返回值
8.2 线程同步
// 同步代码块
public void syncMethod() {synchronized (this) {// 需要同步的代码}
}// 同步方法
public synchronized void syncMethod() {// 需要同步的代码
}// Lock锁
private final Lock lock = new ReentrantLock();public void lockMethod() {lock.lock();try {// 需要同步的代码} finally {lock.unlock();}
}
8.3 线程池
// 创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);// 提交任务
pool.execute(() -> {System.out.println("任务执行");
});// 关闭线程池
pool.shutdown();
九、Java新特性
9.1 Java 8重要特性
Lambda表达式
// 替代匿名内部类
new Thread(() -> System.out.println("Lambda表达式")).start();// 集合操作
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));
Stream API
List<String> names = Arrays.asList("Tom", "Jerry", "Bob");
// 过滤
names.stream().filter(name -> name.startsWith("T")).forEach(System.out::println);// 映射
List<Integer> lengths = names.stream().map(String::length).collect(Collectors.toList());
方法引用
// 静态方法引用
Function<String, Integer> parser = Integer::parseInt;// 实例方法引用
Consumer<String> printer = System.out::println;// 构造方法引用
Supplier<List<String>> listSupplier = ArrayList::new;
9.2 Java 11特性
局部变量类型推断
var list = new ArrayList<String>(); // 自动推断为ArrayList<String>
var stream = list.stream(); // 自动推断为Stream<String>
字符串增强
String str = " Java 11 ";
str.strip(); // 去除前后空白(比trim()更严格)
str.repeat(3); // 重复字符串
str.lines().count(); // 行数统计
9.3 Java 17特性
密封类(Sealed Classes)
public abstract sealed class Shape permits Circle, Square, Rectangle { /*...*/ }public final class Circle extends Shape { /*...*/ }
public final class Square extends Shape { /*...*/ }
public non-sealed class Rectangle extends Shape { /*...*/ }
模式匹配
// instanceof模式匹配
if (obj instanceof String s) {System.out.println(s.length());
}// switch模式匹配
return switch (shape) {case Circle c -> "圆形,半径=" + c.radius();case Square s -> "正方形,边长=" + s.side();default -> "其他形状";
};
十、最佳实践与常见问题
10.1 编码规范
- 命名规范:见名知义,遵循驼峰命名法
- 代码格式:统一缩进(4个空格),合理空行
- 注释规范:类/方法注释使用Javadoc,关键逻辑添加行注释
- 方法设计:单一职责,不超过50行
- 异常处理:不要捕获异常后忽略,使用特定异常而非通用异常
10.2 常见问题
-
NPE(空指针异常):
- 使用Objects.requireNonNull()校验参数
- 使用Optional避免null检查
-
字符串拼接:
- 避免在循环中使用+拼接字符串
- 使用StringBuilder或StringJoiner
-
资源泄漏:
- 使用try-with-resources自动关闭资源
- 确保数据库连接、IO流等资源被正确关闭
-
并发问题:
- 使用线程安全的集合类(如ConcurrentHashMap)
- 避免过度同步,减小同步代码块范围
-
性能优化:
- 集合初始化时指定容量
- 避免频繁的自动装箱/拆箱
- 使用基本数据类型替代包装类(如int替代Integer)
10.3 调试技巧
-
日志调试:
import org.slf4j.Logger; import org.slf4j.LoggerFactory;public class MyClass {private static final Logger logger = LoggerFactory.getLogger(MyClass.class);public void myMethod() {logger.debug("调试信息");logger.info("重要信息");logger.error("错误信息", exception);} }
-
IDE调试:
- 断点调试(普通断点、条件断点)
- 表达式求值(Evaluate Expression)
- 变量监视(Watches)
- 多线程调试(Thread Dump)
-
JVM工具:
- jps:查看Java进程
- jstack:查看线程堆栈
- jmap:查看内存使用
- jconsole/jvisualvm:图形化监控工具