基础语法

变量与数据类型

基本数据类型(8种)

  • 整数类型:byte(1字节)、short(2字节)、int(4字节,默认)、long(8字节)
    byte b = 100;
    int num = 1000;
    long bigNum = 10000000000L; // 需加L后缀
  • 浮点类型:float(4字节)、double(8字节,默认)
    float f = 3.14f; // 需加f后缀
    double d = 3.1415926;
  • 字符类型:char(2字节,Unicode字符)
    float f = 3.14f; // 需加f后缀
    double d = 3.1415926;
  • 布尔类型:boolean(true/false)
    boolean isTrue = true;

引用数据类型

  • 类、接口、数组、枚举等(如String)
    String str = "Hello, Java!";

运算符

  • 算术运算符:+、-、*、/、%(取模)
    int a = 10, b = 3;
    System.out.println(a / b); // 输出3(整数除法)
    System.out.println(a % b); // 输出1(余数)
  • 关系运算符:==、!=、>、<、>=、<=
    boolean isEqual = (5 == 5); // true
  • 逻辑运算符:&&(与)、||(或)、!(非)
    boolean result = (5 > 3) && (2 < 4); // true
  • 位运算符:&、|、^、~、<<、>>
    int x = 5; // 二进制0101
    System.out.println(x << 1); // 左移1位,输出10(二进制1010)
  • 三元运算符:条件 ? 表达式1 : 表达式2
    int max = (a > b) ? a : b;

流程控制

条件语句

  • if-else
    int score = 85;
    if (score >= 90) {
        System.out.println("优秀");
    } else if (score >= 60) {
        System.out.println("及格");
    } else {
        System.out.println("不及格");
    }
  • switch-case(Java 12+支持->简化语法)
int day = 3;
switch (day) {
    case 1 -> System.out.println("周一");
    case 2 -> System.out.println("周二");
    default -> System.out.println("其他");
}

循环语句

  • for循环
for (int i = 0; i < 5; i++) {
    System.out.println(i); // 输出0到4
}
  • while循环
int j = 0;
while (j < 5) {
    System.out.println(j);
    j++;
}
  • do-while循环(至少执行一次)
int k = 0;
do {
    System.out.println(k);
    k++;
} while (k < 5);

循环控制

  • 循环控制:break(跳出循环)、continue(跳过本次循环)
for (int i = 0; i < 10; i++) {
    if (i == 5) break; // 当i=5时终止循环
    if (i % 2 == 0) continue; // 跳过偶数
    System.out.println(i); // 输出1, 3
}

面向对象编程(OOP)

类与对象

// 定义类
public class Person {
    // 属性(字段)
    String name;
    int age;

    // 方法
    public void sayHello() {
        System.out.println("Hello, my name is " + name);
    }
}


// 创建对象
Person p = new Person();
p.name = "Alice";
p.age = 25;
p.sayHello(); // 调用方法

构造方法

public class Person {
    String name;
    int age;

    // 构造方法
    public Person(String name, int age) {
        this.name = name; // this指代当前对象
        this.age = age;
    }
}

// 使用构造方法创建对象
Person p = new Person("Bob", 30);

封装

  • 通过private修饰属性,提供公共方法(getter/setter)访问
public class Account {
    private double balance; // 私有属性

    public double getBalance() {
        return balance;
    }

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

继承

  • 使用extends关键字实现代码复用
// 父类
class Animal {
    public void eat() {
        System.out.println("Eating...");
    }
}

// 子类
class Dog extends Animal {
    public void bark() {
        System.out.println("Woof!");
    }
}

// 使用
Dog d = new Dog();
d.eat(); // 继承自Animal的方法
d.bark();

多态

  • 方法重载(Overload):同名方法参数不同
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}
  • 方法重写(Override):子类重写父类方法
class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cat is eating fish!");
    }
}

抽象类与接口

  • 抽象类
abstract class Shape {
    public abstract double area(); // 抽象方法
}

class Circle extends Shape {
    double radius;

    public Circle(double r) {
        radius = r;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}
  • 接口(Java 8+支持默认方法)
interface Flyable {
    void fly(); // 抽象方法

    default void land() { // 默认方法
        System.out.println("Landing...");
    }
}

class Bird implements Flyable {
    @Override
    public void fly() {
        System.out.println("Bird is flying!");
    }
}

其他核心语法

数组

  • 一维数组
int[] arr = new int[5]; // 声明并初始化长度为5的数组
arr[0] = 10; // 赋值
  • 增强for循环遍历
for (int num : arr) {
    System.out.println(num);
}

包装类

  • 基本类型与对象转换
Integer numObj = Integer.valueOf(100); // 装箱
int num = numObj.intValue(); // 拆箱
// 自动装箱/拆箱(Java 5+)
Integer autoBox = 200; // 自动装箱
int autoUnbox = autoBox; // 自动拆箱

字符串处理

String str = "Hello";
System.out.println(str.length()); // 长度:5
System.out.println(str.substring(1, 3)); // 截取:"el"
System.out.println(str.toUpperCase()); // 转大写:"HELLO"

StringBuilder sb = new StringBuilder();
sb.append("Java").append(" is").append(" fun!");
System.out.println(sb.toString()); // 输出:"Java is fun!"

异常处理

  • 捕获异常
try {
    int result = 10 / 0; // 抛出ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("除数不能为零!");
} finally {
    System.out.println("执行清理操作"); // 无论是否异常都会执行
}
  • 自定义异常
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

throw new MyException("自定义错误!");

集合

List

import java.util.*;

public class ListExample {
    public static void main(String[] args) {
        // ArrayList示例
        List<String> arrayList = new ArrayList<>();
        arrayList.add("A");
        arrayList.add("B");
        arrayList.add(1, "C"); // 在索引1插入
        System.out.println(arrayList); // 输出:[A, C, B]

        // LinkedList示例
        List<String> linkedList = new LinkedList<>();
        linkedList.add("X");
        linkedList.addFirst("Y"); // 头部插入
        linkedList.addLast("Z");  // 尾部插入
        System.out.println(linkedList); // 输出:[Y, X, Z]
    }
}

Set

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        // HashSet示例(无序)
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Apple"); // 重复元素不会被添加
        System.out.println(hashSet); // 输出顺序可能为:[Banana, Apple]

        // TreeSet示例(有序)
        Set<Integer> treeSet = new TreeSet<>();
        treeSet.add(3);
        treeSet.add(1);
        treeSet.add(2);
        System.out.println(treeSet); // 输出:[1, 2, 3]
    }
}

Map

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        // HashMap示例
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Alice", 25);
        hashMap.put("Bob", 30);
        hashMap.put("Alice", 26); // 键重复,值覆盖
        System.out.println(hashMap); // 输出:{Bob=30, Alice=26}

        // TreeMap示例(键有序)
        Map<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(3, "Three");
        treeMap.put(1, "One");
        treeMap.put(2, "Two");
        System.out.println(treeMap); // 输出:{1=One, 2=Two, 3=Three}
    }
}

Collections工具类

List<Integer> list = Arrays.asList(3, 1, 2);
Collections.sort(list); // 升序排序
System.out.println(list); // 输出:[1, 2, 3]

Collections.reverse(list); // 反转列表
System.out.println(list); // 输出:[3, 2, 1]

List<String> syncList = Collections.synchronizedList(new ArrayList<>());


List<String> unmodifiableList = Collections.unmodifiableList(Arrays.asList("A", "B"));
// unmodifiableList.add("C"); // 抛出UnsupportedOperationException

int max = Collections.max(Arrays.asList(1, 3, 2)); // 返回3

其他

  • 泛型(Generics)
// 泛型类
class Box<T> {
    private T value;
    public void set(T value) { this.value = value; }
    public T get() { return value; }
}

// 使用
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String s = stringBox.get(); // 无需强制转换
  • 通配符(Wildcards)
import java.util.*;

public class WildcardExample {
    // 上界通配符:只能读取,不能写入(除null)
    public static double sumOfList(List<? extends Number> list) {
        double sum = 0.0;
        for (Number num : list) {
            sum += num.doubleValue();
        }
        return sum;
    }

    // 下界通配符:只能写入,不能读取(需强制转换)
    public static void addNumbers(List<? super Integer> list) {
        list.add(1);
        list.add(2);
    }

    public static void main(String[] args) {
        List<Integer> intList = Arrays.asList(1, 2, 3);
        System.out.println(sumOfList(intList)); // 输出6.0

        List<Object> objList = new ArrayList<>();
        addNumbers(objList);
        System.out.println(objList); // 输出:[1, 2]
    }
}
  • 注解(Annotation)
    • 内置注解:
      • @Override:标识重写父类方法。
      • @Deprecated:标记过时代码。
      • @SuppressWarnings:抑制编译器警告。
// 定义注解
@Retention(RetentionPolicy.RUNTIME) // 注解保留到运行时
@Target(ElementType.METHOD) // 只能用于方法
public @interface TestAnnotation {
    String value() default "default";
}

// 使用注解
public class AnnotationExample {
    @TestAnnotation("custom")
    public void testMethod() {
        System.out.println("Annotated method");
    }
}

    // 反射读取注解
    Method method = AnnotationExample.class.getMethod("testMethod");
if (method.isAnnotationPresent(TestAnnotation.class)) {
        TestAnnotation annotation = method.getAnnotation(TestAnnotation.class);
        System.out.println(annotation.value()); // 输出:custom
        }
  • 反射(Reflection)
public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        // 获取Class对象
        Class<?> clazz = Class.forName("java.util.ArrayList");

        // 创建实例
        Object list = clazz.getDeclaredConstructor().newInstance();

        // 调用方法
        Method addMethod = clazz.getMethod("add", Object.class);
        addMethod.invoke(list, "Hello");

        System.out.println(list); // 输出:[Hello]
    }
}

并发编程

  • 创建线程
// 继承Thread类
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread running");
    }
}
new MyThread().start();

// 实现Runnable接口
Runnable task = () -> System.out.println("Runnable running");
new Thread(task).start();

// 使用Lambda表达式(Java 8+)
new Thread(() -> System.out.println("Lambda running")).start();
  • 线程同步与锁
    • synchronized关键字
    • ReentrantLock(更灵活的锁控制)
public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}
import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private final ReentrantLock lock = new ReentrantLock();
    private int value = 0;

    public void increment() {
        lock.lock(); // 加锁
        try {
            value++;
        } finally {
            lock.unlock(); // 释放锁
        }
    }
}
  • 线程池(ExecutorService)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3); // 固定大小线程池

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executor.execute(() -> {
                System.out.println("Task " + taskId + " is running on " + Thread.currentThread().getName());
            });
        }

        executor.shutdown(); // 关闭线程池
    }
}
  • 并发集合(Concurrent Collections)
    • ConcurrentHashMap:线程安全的哈希表。
    • CopyOnWriteArrayList:写时复制的线程安全列表。
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("a", 1);
        map.putIfAbsent("a", 2); // 键存在则不更新
        System.out.println(map.get("a")); // 输出1
    }
}
  • 原子类(Atomic Classes)
    • 通过CAS(Compare-And-Swap)实现无锁并发。
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        counter.incrementAndGet(); // 原子操作:counter++
        System.out.println(counter.get()); // 输出1
    }
}

设计模式

单例模式(Singleton)

  • 饿汉式(线程安全)
public class EagerSingleton {
    private static final EagerSingleton INSTANCE = new EagerSingleton();
    private EagerSingleton() {}
    public static EagerSingleton getInstance() { return INSTANCE; }
}
  • 懒汉式(双重检查锁)
public class LazySingleton {
    private static volatile LazySingleton INSTANCE; // volatile防止指令重排序
    private LazySingleton() {}
    public static LazySingleton getInstance() {
        if (INSTANCE == null) {
            synchronized (LazySingleton.class) {
                if (INSTANCE == null) {
                    INSTANCE = new LazySingleton();
                }
            }
        }
        return INSTANCE;
    }
}

工厂模式(Factory)

  • 简单工厂
interface Shape { void draw(); }
class Circle implements Shape { @Override public void draw() { System.out.println("Circle"); } }
class Square implements Shape { @Override public void draw() { System.out.println("Square"); } }

public class ShapeFactory {
    public static Shape createShape(String type) {
        if ("circle".equalsIgnoreCase(type)) return new Circle();
        else if ("square".equalsIgnoreCase(type)) return new Square();
        return null;
    }
}

// 使用
Shape shape = ShapeFactory.createShape("circle");
shape.draw(); // 输出:Circle

. 观察者模式(Observer)

  • Java内置实现(java.util.Observable和java.util.Observer已废弃,推荐使用属性监听或事件总线)
import java.util.ArrayList;
import java.util.List;

interface Observer { void update(String message); }

class Subject {
    private List<Observer> observers = new ArrayList<>();
    public void addObserver(Observer observer) { observers.add(observer); }
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

public class ObserverExample implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Received: " + message);
    }

    public static void main(String[] args) {
        Subject subject = new Subject();
        ObserverExample observer = new ObserverExample();
        subject.addObserver(observer);
        subject.notifyObservers("Hello!"); // 输出:Received: Hello!
    }
}
层级框架/工具作用
核心Spring Boot + Spring MVC构建RESTful API服务
持久层MyBatis(或Hibernate/JPA)数据库操作
持久层Druid数据库连接池
安全Spring Security + JWTAPI鉴权
缓存Redis缓存用户会话、热点数据
监控Spring Boot Actuator + Prometheus应用健康检查、性能监控
文档knife4jAPI文档
日志Log4j2日志
方便开发Lombok / Hutool快速开发
框架/工具作用
Android移动端开发
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐