从入门到精通:30个实战Java代码练习题解析与提升

前言
Java编程作为一门广泛应用于企业级应用、移动端开发、大数据处理等多个领域的语言,掌握其核心编程技能至关重要。实战练习是巩固和提高编程技能的有效途径。本文将提供30个实战Java代码练习题,并对每个题目进行详细解析,帮助读者从入门到精通。
1. Java基础语法
1.1 题目1:输出”Hello, World!”
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
1.2 题目2:定义一个整型变量并赋值,输出其值
public class VariableExample {
public static void main(String[] args) {
int num = 10;
System.out.println(num);
}
}
2. 数据类型与变量
2.1 题目3:定义一个浮点型变量并赋值,输出其值
public class FloatExample {
public static void main(String[] args) {
double num = 3.14;
System.out.println(num);
}
}
2.2 题目4:定义一个字符型变量并赋值,输出其值
public class CharExample {
public static void main(String[] args) {
char letter = ‘A’;
System.out.println(letter);
}
}
3. 运算符与表达式
3.1 题目5:计算并输出两个整数的和、差、积、商
public class OperatorExample {
public static void main(String[] args) {
int a = 5;
int b = 3;
System.out.println(“和:” + (a + b));
System.out.println(“差:” + (a – b));
System.out.println(“积:” + (a * b));
System.out.println(“商:” + (a / b));
}
}
3.2 题目6:计算并输出表达式
(3 + 2) * 5 – 4 / 2
的值
public class ExpressionExample {
public static void main(String[] args) {
int result = (3 + 2) * 5 – 4 / 2;
System.out.println(result);
}
}
4. 流程控制
4.1 题目7:使用if语句判断一个整数是否为偶数
public class IfExample {
public static void main(String[] args) {
int num = 10;
if (num % 2 == 0) {
System.out.println(num + ” 是偶数”);
} else {
System.out.println(num + ” 是奇数”);
}
}
}
4.2 题目8:使用for循环输出1到10的整数
public class ForExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) { System.out.println(i); } } } 5. 面向对象编程 5.1 题目9:定义一个学生类,包含姓名和年龄属性 public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } 5.2 题目10:创建一个学生对象并输出其姓名和年龄 public class StudentExample { public static void main(String[] args) { Student student = new Student("张三", 20); System.out.println("姓名:" + student.getName()); System.out.println("年龄:" + student.getAge()); } } 6. 集合框架 6.1 题目11:使用ArrayList存储学生对象,并输出所有学生的姓名 import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String[] args) { List students = new ArrayList<>();
students.add(new Student(“张三”, 20));
students.add(new Student(“李四”, 22));
students.add(new Student(“王五”, 23));

for (Student student : students) {
System.out.println(student.getName());
}
}
}
6.2 题目12:使用LinkedList替换ArrayList,并实现相同的功能
import java.util.LinkedList;
import java.util.List;

public class LinkedListExample {
public static void main(String[] args) {
List students = new LinkedList<>();
students.add(new Student(“张三”, 20));
students.add(new Student(“李四”, 22));
students.add(new Student(“王五”, 23));

for (Student student : students) {
System.out.println(student.getName());
}
}
}
7. 异常处理
7.1 题目13:定义一个除法运算,如果除数为0则抛出异常
public class DivisionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b;
System.out.println(“结果:” + result);
} catch (ArithmeticException e) {
System.out.println(“除数不能为0”);
}
}
}
7.2 题目14:使用try-catch块捕获并处理IOException
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class IOExceptionExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(“example.txt”))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(“文件读取错误”);
}
}
}
8. 多线程
8.1 题目15:定义一个线程,使其在运行时输出数字1到10
public class ThreadExample implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) { System.out.println(Thread.currentThread().getName() + " " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Thread thread = new Thread(new ThreadExample()); thread.start(); } } 8.2 题目16:创建两个线程,实现线程间的同步 public class SynchronizedExample { private static int count = 0; public static void main(String[] args) { Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) { synchronized (SynchronizedExample.class) { count++; } } }); Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) { synchronized (SynchronizedExample.class) { count++; } } }); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("最终结果:" + count); } } 9. 网络编程 9.1 题目17:使用Socket编程实现客户端与服务器之间的简单通信 // 服务器端 import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class ServerExample { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(12345); System.out.println("服务器启动,等待连接..."); Socket socket = serverSocket.accept(); System.out.println("客户端连接成功"); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); String inputLine; while ((inputLine = reader.readLine()) != null) { System.out.println("客户端:" + inputLine); writer.println("服务器:" + inputLine); } reader.close(); writer.close(); socket.close(); serverSocket.close(); } } 9.2 题目18:使用Socket编程实现客户端与服务器之间的文件传输 // 服务器端 import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class FileTransferServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(12345); System.out.println("服务器启动,等待连接..."); Socket socket = serverSocket.accept(); System.out.println("客户端连接成功"); File file = new File("example.txt"); byte[] buffer = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(buffer); fis.close(); socket.getOutputStream().write(buffer); socket.getOutputStream().flush(); socket.getOutputStream().close(); socket.close(); serverSocket.close(); } } 10. 数据库编程 10.1 题目19:使用JDBC连接MySQL数据库,并查询数据 import java.sql.*; public class JdbcExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; try (Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM student")) { while (resultSet.next()) { System.out.println("姓名:" + resultSet.getString("name") + ",年龄:" + resultSet.getInt("age")); } } catch (SQLException e) { e.printStackTrace(); } } } 10.2 题目20:使用PreparedStatement执行带参数的SQL语句 import java.sql.*; public class PreparedStatementExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; try (Connection connection = DriverManager.getConnection(url, user, password); PreparedStatement statement = connection.prepareStatement("INSERT INTO student(name, age) VALUES(?, ?)")) { statement.setString(1, "李四"); statement.setInt(2, 23); int rowsAffected = statement.executeUpdate(); System.out.println("影响行数:" + rowsAffected); } catch (SQLException e) { e.printStackTrace(); } } } 11. 总结 通过以上30个实战Java代码练习题的解析与提升,相信读者已经对Java编程有了更深入的了解。不断练习和总结是提高编程技能的关键。希望读者在今后的学习和工作中能够不断进步,成为一名优秀的Java程序员。