以下是50个Java常见代码示例,涵盖基础语法、面向对象、集合框架、IO流、多线程、网络编程、设计模式等核心知识点,从入门到进阶逐步深入,助力从Java小白向架构师进阶:
一、基础语法
- Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- 变量与数据类型
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);
}
}
- 条件语句(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("不及格");
}
}
}
- 循环语句(for)
public class ForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("i = " + i);
}
}
}
- 循环语句(while)
public class WhileLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println("i = " + i);
i++;
}
}
}
- 循环语句(do-while)
public class DoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("i = " + i);
i++;
} while (i <= 10);
}
}
- 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("其他星期");
}
}
}
- 数组定义与遍历
public class ArrayDemo {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
for (int num : nums) {
System.out.println(num);
}
}
}
- 二维数组
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();
}
}
}
- 方法定义与调用
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);
}
}
二、面向对象
- 类与对象
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();
}
}
- 构造方法
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();
}
}
- 封装
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());
}
}
- 继承
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();
}
}
- 多态
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();
}
}
- 抽象类
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();
}
}
- 接口
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();
}
}
- 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));
}
}
- final关键字
public class FinalDemo {
public static void main(String[] args) {
final int MAX = 100;
// MAX = 200; // 编译错误,final变量不可修改
System.out.println(MAX);
}
}
final class FinalClass {
// 此类不能被继承
}
- 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());
}
}
三、集合框架
- 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);
}
}
}
- 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);
}
}
- 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());
}
}
}
- 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);
}
}
- 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流
- 文件读取(字节流)
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();
}
}
}
- 文件写入(字节流)
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();
}
}
}
- 文件读取(字符流)
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();
}
}
}
- 文件写入(字符流)
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();
}
}
}
- 缓冲流(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();
}
}
}
五、多线程
- 继承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();
}
}
- 实现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();
}
}
- 线程同步(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
}
}
- 线程池
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();
}
}
- Callable与Future
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService