50个JAVA常见代码大全:学完这篇从Java小白到架构师

以下是50个Java常见代码示例,涵盖基础语法、面向对象、集合框架、IO流、多线程、网络编程、设计模式等核心知识点,从入门到进阶逐步深入,助力从Java小白向架构师进阶:

一、基础语法

  1. Hello World
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  1. 变量与数据类型
public class Variables {
    public static void main(String[] args) {
        int num = 10;          // 整数
        double pi = 3.14159;   // 浮点数
        char ch = 'A';         // 字符
        boolean flag = true;   // 布尔值
        String str = "Java";   // 字符串
        System.out.println(num + " " + pi + " " + ch + " " + flag + " " + str);
    }
}
  1. 条件语句(if-else)
public class IfElseDemo {
    public static void main(String[] args) {
        int score = 85;
        if (score >= 90) {
            System.out.println("优秀");
        } else if (score >= 60) {
            System.out.println("及格");
        } else {
            System.out.println("不及格");
        }
    }
}
  1. 循环语句(for)
public class ForLoop {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("i = " + i);
        }
    }
}
  1. 循环语句(while)
public class WhileLoop {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            System.out.println("i = " + i);
            i++;
        }
    }
}
  1. 循环语句(do-while)
public class DoWhileLoop {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("i = " + i);
            i++;
        } while (i <= 10);
    }
}
  1. switch-case语句
public class SwitchCase {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("星期一");
                break;
            case 2:
                System.out.println("星期二");
                break;
            case 3:
                System.out.println("星期三");
                break;
            default:
                System.out.println("其他星期");
        }
    }
}
  1. 数组定义与遍历
public class ArrayDemo {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        for (int num : nums) {
            System.out.println(num);
        }
    }
}
  1. 二维数组
public class TwoDimensionalArray {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
  1. 方法定义与调用
public class MethodDemo {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(3, 5);
        System.out.println("3 + 5 = " + result);
    }
}

二、面向对象

  1. 类与对象
class Person {
    String name;
    int age;

    void sayHello() {
        System.out.println("Hello, I'm " + name + ", " + age + " years old.");
    }
}

public class ClassObject {
    public static void main(String[] args) {
        Person p = new Person();
        p.name = "Tom";
        p.age = 20;
        p.sayHello();
    }
}
  1. 构造方法
class Student {
    String name;
    int id;

    // 构造方法
    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    void showInfo() {
        System.out.println("Name: " + name + ", ID: " + id);
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        Student s = new Student("Alice", 1001);
        s.showInfo();
    }
}
  1. 封装
class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

public class EncapsulationDemo {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.deposit(1000);
        System.out.println("Balance: " + account.getBalance());
    }
}
  1. 继承
class Animal {
    void eat() {
        System.out.println("Animal eats");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // 继承自Animal
        dog.bark();
    }
}
  1. 多态
interface Shape {
    void draw();
}

class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing Rectangle");
    }
}

public class PolymorphismDemo {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Rectangle();
        shape1.draw();
        shape2.draw();
    }
}
  1. 抽象类
abstract class Vehicle {
    abstract void run();
}

class Car extends Vehicle {
    @Override
    void run() {
        System.out.println("Car runs on road");
    }
}

public class AbstractClassDemo {
    public static void main(String[] args) {
        Vehicle car = new Car();
        car.run();
    }
}
  1. 接口
interface Flyable {
    void fly();
}

class Bird implements Flyable {
    @Override
    public void fly() {
        System.out.println("Bird flies with wings");
    }
}

public class InterfaceDemo {
    public static void main(String[] args) {
        Flyable bird = new Bird();
        bird.fly();
    }
}
  1. static关键字
class MathUtils {
    public static final double PI = 3.14159;

    public static int square(int num) {
        return num * num;
    }
}

public class StaticDemo {
    public static void main(String[] args) {
        System.out.println("PI: " + MathUtils.PI);
        System.out.println("Square of 5: " + MathUtils.square(5));
    }
}
  1. final关键字
public class FinalDemo {
    public static void main(String[] args) {
        final int MAX = 100;
        // MAX = 200;  // 编译错误,final变量不可修改
        System.out.println(MAX);
    }
}

final class FinalClass {
    // 此类不能被继承
}
  1. this关键字
class Person {
    private String name;

    public void setName(String name) {
        this.name = name;  // this区分成员变量和局部变量
    }

    public String getName() {
        return this.name;
    }
}

public class ThisDemo {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Bob");
        System.out.println(p.getName());
    }
}

三、集合框架

  1. ArrayList
import java.util.ArrayList;

public class ArrayListDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}
  1. LinkedList
import java.util.LinkedList;

public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.addFirst(5);  // 在头部添加
        numbers.addLast(30);  // 在尾部添加

        System.out.println(numbers);
    }
}
  1. HashMap
import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Tom", 90);
        scores.put("Alice", 95);
        scores.put("Bob", 85);

        System.out.println("Alice's score: " + scores.get("Alice"));

        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
  1. HashSet
import java.util.HashSet;

public class HashSetDemo {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Red");
        set.add("Green");
        set.add("Blue");
        set.add("Red");  // 重复元素不会被添加

        System.out.println(set);
    }
}
  1. TreeMap(排序)
import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();  // 按key自然排序
        map.put("Banana", 3);
        map.put("Apple", 1);
        map.put("Cherry", 5);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

四、IO流

  1. 文件读取(字节流)
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("test.txt")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 文件写入(字节流)
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
    public static void main(String[] args) {
        String content = "Hello, File!";
        try (FileOutputStream fos = new FileOutputStream("output.txt")) {
            fos.write(content.getBytes());
            System.out.println("File written successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 文件读取(字符流)
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("test.txt")) {
            int data;
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 文件写入(字符流)
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {
    public static void main(String[] args) {
        String content = "Hello, Character Stream!";
        try (FileWriter fw = new FileWriter("charOutput.txt")) {
            fw.write(content);
            System.out.println("File written successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 缓冲流(BufferedReader)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

五、多线程

  1. 继承Thread类
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread " + Thread.currentThread().getId() + ": " + i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadExtendDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}
  1. 实现Runnable接口
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Runnable " + Thread.currentThread().getId() + ": " + i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class RunnableDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        Thread t2 = new Thread(new MyRunnable());
        t1.start();
        t2.start();
    }
}
  1. 线程同步(synchronized)
class Counter {
    private int count = 0;

    public synchronized void increment() {  // 同步方法
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class SynchronizedDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count: " + counter.getCount());  // 预期2000
    }
}
  1. 线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);  // 固定大小线程池
        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println("Task running in " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }
}
  1. Callable与Future
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值