首页 > 应用开发 > Java > 一些常见的Java 开发代码
以下是一些常见的 Java 开发代码示例,涵盖了不同方面的功能:
java1public class HelloWorld {2 public static void main(String[] args) {3 System.out.println("Hello, World!");4 5 // 变量和数据类型示例6 int number = 10;7 double price = 19.99;8 String message = "Welcome to Java";9 boolean isJavaFun = true;10 11 System.out.println("Number: " + number);12 System.out.println("Price: $" + price);13 System.out.println(message);14 System.out.println("Is Java fun? " + isJavaFun);15 }16}
java1// 定义一个类2public class Person {3 // 字段4 private String name;5 private int age;6 7 // 构造方法8 public Person(String name, int age) {9 this.name = name;10 this.age = age;11 }12 13 // 方法14 public void introduce() {15 System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");16 <"shenzhoumedia.com"> <"bijiapinpai.com"> <"fjiqx.com"> }17 18 // Getter 和 Setter19 public String getName() {20 return name;21 }22 23 public void setName(String name) {24 this.name = name;25 }26 27 public int getAge() {28 return age;29 }30 31 public void setAge(int age) {32 this.age = age;33 }34}3536// 使用类37public class Main {38 public static void main(String[] args) {39 Person person = new Person("Alice", 25);40 person.introduce();41 42 person.setAge(26);43 System.out.println(person.getName() + "'s new age: " + person.getAge());44 }45}
java1import java.util.ArrayList;2import java.util.HashMap;3import java.util.List;4import java.util.Map;56public class CollectionsExample {7 public static void main(String[] args) {8 // List 示例9 List<String> fruits = new ArrayList<>();10 fruits.add("Apple");11 fruits.add("Banana");12 fruits.add("Orange");13 14 System.out.println("Fruits: " + fruits);15 16 for (String fruit : fruits) {17 System.out.println(fruit);18 }19 20 // Map 示例21 Map<String, Integer> fruitStock = new HashMap<>();22 fruitStock.put("Apple", 10);23 fruitStock.put("Banana", 15);24 fruitStock.put("Orange", 8);25 26 System.out.println("\nFruit Stock:");27 for (Map.Entry<String, Integer> entry : fruitStock.entrySet()) {28 System.out.println(entry.getKey() + ": " + entry.getValue());29 }30 }31}
java1import java.io.BufferedReader;2import java.io.BufferedWriter;3import java.io.FileReader;4import java.io.FileWriter;5import java.io.IOException;67public class FileIOExample {8 public static void main(String[] args) {9 String filename = "example.txt";10 11 // 写入文件12 try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {13 writer.write("This is line 1");14 writer.newLine();15 writer.write("This is line 2");16 <"sdwxwn.com"> <"doyeepp.com"> <"xayyv.com"> writer.newLine();17 writer.write("This is line 3");18 System.out.println("Data written to file successfully.");19 } catch (IOException e) {20 System.err.println("Error writing to file: " + e.getMessage());21 }22 23 // 读取文件24 System.out.println("\nFile contents:");25 try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {26 String line;27 while ((line = reader.readLine()) != null) {28 System.out.println(line);29 }30 } catch (IOException e) {31 System.err.println("Error reading file: " + e.getMessage());32 }33 }34}
java1public class ThreadExample {2 public static void main(String[] args) {3 // 创建并启动线程4 Thread thread1 = new Thread(new MyRunnable("Thread 1"));5 Thread thread2 = new Thread(new MyRunnable("Thread 2"));6 7 thread1.start();8 thread2.start();9 }10}1112class MyRunnable implements Runnable {13 private String name;14 15 public MyRunnable(String name) {16 this.name = name;17 }18 19 @Override20 public void run() {21 for (int i = 1; i <= 5; i++) {22 System.out.println(name + ": Count " + i);23 try {24 Thread.sleep(500); // 暂停500毫秒25 } catch (InterruptedException e) {26 System.err.println(name + " was interrupted");27 }28 }29 System.out.println(name + " finished");30 }31}
java1import org.springframework.web.bind.annotation.*;23@RestController4@RequestMapping("/api/users")5public class UserController {6 7 // 模拟数据库8 private Map<Integer, User> users = new HashMap<>();9 private int nextId = 1;10 11 // 获取所有用户12 @GetMapping13 public List<User> getAllUsers() {14 return new ArrayList<>(users.values());15 }16 17 // 获取单个用户18 @GetMapping("/{id}")19 public ResponseEntity<User> getUserById(@PathVariable int id) {20 User user = users.get(id);21 if (user == null) {22 return ResponseEntity.notFound().build();23 }24 return ResponseEntity.ok(user);25 }26 27 // 创建用户28 @PostMapping29 public ResponseEntity<User> createUser(@RequestBody User user) {30 user.setId(nextId++);31 users.put(user.getId(), user);32 return ResponseEntity.ok(user);33 }34 35 // 更新用户36 @PutMapping("/{id}")37 public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User userDetails) {38 User user = users.get(id);39 if (user == null) {40 return ResponseEntity.notFound().build();41 }42 user.setName(userDetails.getName());43 user.setEmail(userDetails.getEmail());44 return ResponseEntity.ok(user);45 }46 47 // 删除用户48 @DeleteMapping("/{id}")49 public ResponseEntity<Void> deleteUser(@PathVariable int id) {50 if (users.remove(id) == null) {51 return ResponseEntity.notFound().build();52 }53 return ResponseEntity.noContent().build();54 }55}5657class User {58 private int id;59 private String name;60 private String email;61 62 // 构造方法、getter和setter省略63 // 实际开发中应该使用Lombok或手动生成64}
java1import java.sql.*;23public class JdbcExample {4 // 数据库连接信息5 private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";6 private static final String USER = "username";7 private static final String PASSWORD = "password";8 9 public static void main(String[] args) {10 Connection conn = null;11 PreparedStatement pstmt = null;12 ResultSet rs = null;13 14 try {15 // 1. 注册驱动并建立连接16 conn = DriverManager.getConnection(URL, USER, PASSWORD);17 18 // 2. 创建PreparedStatement19 String sql = "SELECT id, name, email FROM users WHERE id > ?";20 pstmt = conn.prepareStatement(sql);21 pstmt.setInt(1, 0); // 设置参数22 23 // 3. 执行查询24 rs = pstmt.executeQuery();25 26 // 4. 处理结果集27 while (rs.next()) {28 int id = rs.getInt("id");29 String name = rs.getString("name");30 <"wenfatshed.com"> <"hrbrkxfqc.com"> <"tjjsjcj.com"> String email = rs.getString("email");31 32 System.out.printf("ID: %d, Name: %s, Email: %s%n", id, name, email);33 }34 35 // 插入数据示例36 String insertSql = "INSERT INTO users (name, email) VALUES (?, ?)";37 pstmt = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);38 pstmt.setString(1, "John Doe");39 pstmt.setString(2, "john@example.com");40 int affectedRows = pstmt.executeUpdate();41 42 if (affectedRows > 0) {43 try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {44 if (generatedKeys.next()) {45 System.out.println("Inserted record with ID: " + generatedKeys.getInt(1));46 }47 }48 }49 50 } catch (SQLException e) {51 System.err.println("Database error: " + e.getMessage());52 } finally {53 // 5. 关闭资源54 try {55 if (rs != null) rs.close();56 if (pstmt != null) pstmt.close();57 if (conn != null) conn.close();58 } catch (SQLException e) {59 System.err.println("Error closing resources: " + e.getMessage());60 }61 }62 }63}
java1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;45public class Java8Features {6 public static void main(String[] args) {7 // Lambda 表达式8 Runnable runnable = () -> System.out.println("Running in a thread");9 new Thread(runnable).start();10 11 // Stream API12 List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");13 14 // 过滤和映射15 List<String> longNames = names.stream()16 .filter(name -> name.length() > 4)17 .map(String::toUpperCase)18 .collect(Collectors.toList());19 20 System.out.println("Long names: " + longNames);21 22 // Optional 示例23 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);24 Optional<Integer> firstEven = numbers.stream()25 .filter(n -> n % 2 == 0)26 .findFirst();27 28 firstEven.ifPresent(num -> System.out.println("First even number: " + num));29 30 // 默认方法31 MyInterface impl = new MyInterfaceImpl();32 impl.printMessage();33 impl.printDefaultMessage();34 }35}3637interface MyInterface {38 void printMessage();39 40 // 默认方法41 default void printDefaultMessage() {42 System.out.println("Default message from interface");43 }44}4546class MyInterfaceImpl implements MyInterface {47 @Override48 public void printMessage() {49 System.out.println("Implementation specific message");50 }51}
这些示例涵盖了 Java 开发中的基础和常见场景。根据您的具体需求,我可以提供更针对性的代码示例或更详细的解释。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3099840/ ,如需转载,请注明出处,否则将追究法律责任。