60个java常用的代码(能够帮助您更好地理解Java编程)

博主主页:【南鸢1.0】

本文专栏:JAVA 

目录

基础语法

方法与函数

面向对象编程

集合框架

异常处理

输入输出

日期与时间

线程

Lambda表达式

Stream API

常用工具类

其他常用功能

数据库连接(JDBC)

网络编程

JavaFX (GUI)

注解

反射

Java 8 任意和方法引用

其他实用代码


以下是60个常用的Java代码片段,涵盖了基础语法、常用类和一些实用功能:

基础语法

  1. Hello World

    public class HelloWorld {  
        public static void main(String[] args) {  
            System.out.println("Hello, World!");  
        }  
    }  
  2. 变量声明

    int number = 10;  
    String text = "Hello";
  3. 条件语句

    if (number > 0) {  
        System.out.println("Positive");  
    } else {  
        System.out.println("Negative or Zero");  
    }
  4. 循环

    for (int i = 0; i < 5; i++) {  
        System.out.println(i);  
    }
  5. 数组

    int[] numbers = {1, 2, 3, 4, 5};

方法与函数

  1. 方法定义

    public int add(int a, int b) {  
        return a + b;  
    }
  2. 方法重载

    public int add(int a, int b) {  
        return a + b;  
    }  
    public double add(double a, double b) {  
        return a + b;  
    }
  3. 递归

    public int factorial(int n) {  
        if (n == 0) return 1;  
        return n * factorial(n - 1);  
    }

面向对象编程

  1. 类与对象

    class Dog {  
        String name;  
        void bark() {  
            System.out.println(name + " says woof!");  
        }  
    }
  2. 构造函数

    class Cat {  
        String name;  
        Cat(String name) {  
            this.name = name;  
        }  
    }
  3. 继承

    class Animal {}  
    class Dog extends Animal {}
  4. 接口

    interface Animal {  
        void sound();  
    }  
    class Cat implements Animal {  
        public void sound() {  
            System.out.println("Meow");  
        }  
    }

集合框架

  1. ArrayList

    List<String> list = new ArrayList<>();  
    list.add("Hello");
  2. HashMap

    Map<String, Integer> map = new HashMap<>();  
    map.put("One", 1);  
    map.put("Two", 2);
  3. 遍历集合

    for (String item : list) {  
        System.out.println(item);  
    }

异常处理

  1. try-catch

    try {  
        int result = 10 / 0;  
    } catch (ArithmeticException e) {  
        System.out.println("Cannot divide by zero!");  
    }
  2. 自定义异常

    class MyException extends Exception {  
        public MyException(String message) {  
            super(message);  
        }  
    }

输入输出

  1. 文件读取

    try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {  
        String line;  
        while ((line = br.readLine()) != null) {  
            System.out.println(line);  
        }  
    } catch (IOException e) {  
        e.printStackTrace();  
    }
  2. 文件写入

    try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {  
        writer.write("Hello, World!");  
    } catch (IOException e) {  
        e.printStackTrace();  
    }

日期与时间

  1. 获取当前日期

    LocalDate today = LocalDate.now();
  2. 日期格式化

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");  
    String formattedDate = today.format(formatter);

线程

  1. 创建线程

    Thread thread = new Thread(() -> System.out.println("Thread running"));  
    thread.start();
  2. Runnable接口

    class MyRunnable implements Runnable {  
        public void run() {  
            System.out.println("Runnable running");  
        }  
    }  
    new Thread(new MyRunnable()).start();

Lambda表达式

  1. 使用Lambda
    List<String> names = Arrays.asList("Alice", "Bob", "Charlie");  
    names.forEach(name -> System.out.println(name));

Stream API

  1. 使用Stream
    List<String> filtered = names.stream()  
                                  .filter(name -> name.startsWith("A"))  
                                  .collect(Collectors.toList());

常用工具类

  1. Math类

    int max = Math.max(5, 10);
  2. String manipulation

    String uppercase = "hello".toUpperCase();
  3. String split

    String[] parts = "a,b,c".split(",");
  4. UUID生成

    String uuid = UUID.randomUUID().toString();

其他常用功能

  1. JSON处理(使用Gson)

    Gson gson = new Gson();  
    String json = gson.toJson(yourObject);  
    YourClass obj = gson.fromJson(json, YourClass.class);
  2. 正则表达式

    boolean matches = "abc".matches("[a-z]+");
  3. 字符串连接

    String result = String.join(", ", list);

数据库连接(JDBC)

  1. 连接数据库

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "user", "password");
  2. 执行查询

    Statement stmt = con.createStatement();  
    ResultSet rs = stmt.executeQuery("SELECT * FROM users");

网络编程

  1. 连接到URL
    URL url = new URL("http://example.com");  
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

JavaFX (GUI)

  1. 创建窗口
    Stage stage = new Stage();  
    Scene scene = new Scene(new StackPane(), 300, 250);  
    stage.setScene(scene);  
    stage.show();

注解

  1. 自定义注解
    @Retention(RetentionPolicy.RUNTIME)  
    @Target(ElementType.METHOD)  
    public @interface MyAnnotation {}

反射

  1. 获取类信息

    Class<?> clazz = Class.forName("java.lang.String");
  2. 调用方法

    Method method = clazz.getMethod("length");  
    Object result = method.invoke("Hello");

Java 8 任意和方法引用

  1. 方法引用
    names.forEach(System.out::println);

其他实用代码

  1. 版本判断

    if (System.getProperty("java.version").startsWith("1.8")) {  
        System.out.println("Java 8");  
    }
  2. 克隆对象

    Object cloned = original.clone();
  3. 获取栈信息

    new Exception().printStackTrace();

  4. 检查空值

    if (obj == null) {  
        System.out.println("Object is null");  
    }
  5. 避免重复元素(Set)

    Set<String> set = new HashSet<>(list);
  6. 将集合转为数组

    String[] array = list.toArray(new String[0]);
  7. 时间延迟

    Thread.sleep(1000);
  8. 获取输入

    Scanner scanner = new Scanner(System.in);  
    String input = scanner.nextLine();
  9. 转换类型

    int value = Integer.parseInt("123");
  10. 使用Optional防止NullPointerException

    Optional<String> optional = Optional.ofNullable(name);  
    optional.ifPresent(System.out::println);
  11. 使用StringBuilder

    StringBuilder sb = new StringBuilder();  
    sb.append("Hello").append(" World");  
    String result = sb.toString();
  12. 多线程锁

    synchronized (this) {  
        // synchronized block  
    }
  13. 使用ExecutorService

    ExecutorService executor = Executors.newFixedThreadPool(2);  
    executor.submit(() -> System.out.println("Task"));
  14. 获取环境变量

    String path = System.getenv("PATH");
  15. 打印当前线程名称

    System.out.println(Thread.currentThread().getName());
  16. 基本数据类型转为字符串

    String str = Integer.toString(100);
  17. 简化主函数

    public static void main(String... args) {  
        // ...  
    }
  18. 使用File类

    File file = new File("file.txt");  
    boolean exists = file.exists();
  19. 使用Property类

    Properties properties = new Properties();  
    properties.load(new FileReader("config.properties"));
  20. 使用String.format

    String formatted = String.format("Hello, %s!", "World");

这些代码示例涵盖了Java的基本技能和一些高级特性,希望能够帮助您更好地理解Java编程。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南鸢1.0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值