JAVA常见的代码片段经常用于日常开发工作:学完这篇从小白到架构师

目录

1. 打印输出

2. 读取用户输入

3. 条件语句

4. 循环结构

5. 数组操作

6. 面向对象编程

7. 集合操作

8. 异常处理

9. 文件读写

10. 线程与并发

11. 枚举类型

12. Lambda表达式与函数式接口

13. 静态方法与静态成员

14. 泛型

总结:


Java 代码库是一个庞大的领域,但有一些常见的代码片段经常用于日常开发工作,包括输入输出、控制结构、集合、面向对象编程等。以下是一些 Java 中常见的代码片段,涵盖了基本的程序结构、常用功能和操作。

1. 打印输出

// 打印文本到控制台
System.out.println("Hello, World!");

// 打印格式化字符串
System.out.printf("My age is %d and my height is %.2f meters\n", 25, 1.75);

2. 读取用户输入

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 读取一个字符串
        System.out.print("请输入名字: ");
        String name = scanner.nextLine();
        
        // 读取一个整数
        System.out.print("请输入年龄: ");
        int age = scanner.nextInt();
        
        System.out.printf("名字: %s, 年龄: %d\n", name, age);
    }
}

3. 条件语句

int x = 10;
if (x > 5) {
    System.out.println("x 大于 5");
} else if (x == 5) {
    System.out.println("x 等于 5");
} else {
    System.out.println("x 小于 5");
}

// 三元运算符
int result = (x > 5) ? 1 : 0;

4. 循环结构

// for 循环
for (int i = 0; i < 10; i++) {
    System.out.println("当前 i 的值是: " + i);
}

// while 循环
int count = 0;
while (count < 5) {
    System.out.println("Count is: " + count);
    count++;
}

// do-while 循环
int number = 5;
do {
    System.out.println("Number is: " + number);
    number--;
} while (number > 0);

5. 数组操作

// 定义和初始化数组
int[] numbers = {1, 2, 3, 4, 5};

// 访问数组元素
System.out.println("数组的第一个元素是: " + numbers[0]);

// 遍历数组
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element at index " + i + ": " + numbers[i]);
}

// 使用增强型 for 循环遍历
for (int num : numbers) {
    System.out.println("Number: " + num);
}

6. 面向对象编程

// 定义一个简单的类
class Person {
    String name;
    int age;

    // 构造函数
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 成员方法
    public void sayHello() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建对象
        Person person = new Person("Alice", 30);
        
        // 调用对象的方法
        person.sayHello();
    }
}

7. 集合操作

import java.util.ArrayList;
import java.util.HashMap;

// 使用 ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// 遍历列表
for (String fruit : list) {
    System.out.println(fruit);
}

// 使用 HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);

// 遍历 Map
for (String key : map.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

8. 异常处理

try {
    int result = 10 / 0; // 这会引发 ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("捕获到异常: " + e.getMessage());
} finally {
    System.out.println("这个块总是会被执行");
}

9. 文件读写

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

// 写入文件
try {
    FileWriter writer = new FileWriter("output.txt");
    writer.write("Hello, World!");
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

// 读取文件
try {
    BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}

10. 线程与并发

// 实现 Runnable 接口
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("线程正在运行...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

// 使用 lambda 表达式创建线程
Thread thread = new Thread(() -> {
    System.out.println("Lambda 线程正在运行...");
});
thread.start();

11. 枚举类型

// 定义枚举
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        switch (today) {
            case MONDAY:
                System.out.println("今天是星期一");
                break;
            case FRIDAY:
                System.out.println("今天是星期五");
                break;
            default:
                System.out.println("今天是其他日子");
                break;
        }
    }
}

12. Lambda表达式与函数式接口

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

// 自定义函数式接口
@FunctionalInterface
interface MyFunction {
    void apply(String input);
}

public class Main {
    public static void main(String[] args) {
        MyFunction function = (input) -> System.out.println("Input is: " + input);
        function.apply("Hello!");
    }
}

13. 静态方法与静态成员

class MyClass {
    static int counter = 0;

    static void incrementCounter() {
        counter++;
    }
}

public class Main {
    public static void main(String[] args) {
        // 访问静态成员
        MyClass.incrementCounter();
        System.out.println("Counter: " + MyClass.counter);
    }
}

14. 泛型

// 泛型方法
public static <T> void printArray(T[] array) {
    for (T element : array) {
        System.out.println(element);
    }
}

// 使用泛型类
class Box<T> {
    private T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        // 泛型方法调用
        Integer[] numbers = {1, 2, 3};
        printArray(numbers);

        // 使用泛型类
        Box<String> box = new Box<>();
        box.set("Hello");
        System.out.println(box.get());
    }
}

总结:

以上代码示例展示了 Java 中常见的编程功能和操作,涵盖了输入输出、集合、异常处理、面向对象、线程、泛型等常用功能。这些代码是日常开发中经常会用到的基础操作,适用于各种应用场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值