[JAVASE] 异常 与 SE阶段知识点补充
在Java SE阶段,我们主要学习了以下内容:
- 面向对象的编程(OOP)
- 异常处理
- 集合框架
- 泛型
- 流式编程
- 多线程
- 网络编程
- 反射
- 数据库编程(JDBC)
- 文件IO
以下是对应这些知识点的简单示例代码:
- 异常处理:
try {
int data = 100 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
// 清理资源
}
- 集合框架:
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
for (String s : list) {
System.out.println(s);
}
- 泛型:
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
for (Integer number : numbers) {
System.out.println(number);
}
- 流式编程:
List<String> list = Arrays.asList("Hello", "World");
list.stream().forEach(System.out::println);
- 多线程:
Runnable task = () -> System.out.println("Hello from thread: " + Thread.currentThread().getName());
new Thread(task).start();
- 网络编程(基于Socket的简单通信):
try (ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
String inputLine = in.readLine();
out.println("Hello, " + inputLine);
} catch (IOException e) {
e.printStackTrace();
}
- 反射:
try {
Class<?> clazz = Class.forName("java.lang.String");
Constructor<?> constructor = clazz.getConstructor(String.class);
Object instance = constructor.newInstance("Hello");
Method method = clazz.getMethod("charAt", int.class);
Object result = method.invoke(instance, 0);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
- 数据库编程(JDBC):
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table")) {
while (resultSet.next()) {
System.out.println(resultSet.getString("my_column"));
}
} catch (SQLException e) {
e.printStackTrace(
评论已关闭