Java,作为一门流行多年的编程语言,始终占据着软件开发领域的重要位置。无论是初学者还是经验丰富的程序员,掌握Java中常见的代码和概念都是至关重要的。本文将列出30个Java常用代码示例,并提供相应解释,助力你从Java小白成长为架构师。
// 1. Hello World程序
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// 2. 变量和数据类型
public class VariableTypes {
public static void main(String[] args) {
int num = 10;
double decimal = 3.14;
char symbol = 'A';
boolean flag = true;
System.out.println("整数: " + num + ", 浮点数: " + decimal + ", 字符: " + symbol + ", 布尔值: " + flag);
}
}
// 3. 运算符使用
public class Operators {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("加法: " + (a + b));
System.out.println("减法: " + (a - b));
System.out.println("乘法: " + (a * b));
System.out.println("除法: " + (a / b));
System.out.println("取余: " + (a % b));
System.out.println("自增: " + (a++));
System.out.println("自减: " + (--b));
}
}
// 4. if-else语句
public class IfElseExample {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
}
}
// 5. switch语句
public class SwitchExample {
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("其他");
}
}
}
// 6. for循环
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
// 7. while循环
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
}
}
// 8. do-while循环
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 11;
do {
System.out.println(i);
i++;
} while (i <= 10);
}
}
// 9. 方法定义和调用
public class MethodExample {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("结果: " + result);
}
}
// 10. 类和对象
class Person {
String name;
int age;
public void introduce() {
System.out.println("我叫 " + name + ",年龄是 " + age + " 岁。");
}
}
public class ClassObjectExample {
public static void main(String[] args) {
Person person = new Person();
person.name = "Alice";
person.age = 25;
person.introduce();
}
}
// 11. 封装示例
class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
age = 18;
return age;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
public class EncapsulationExample {
public static void main(String[] args) {
Student student = new Student();
student.setName("Bob");
student.setAge(20);
System.out.println("姓名: " + student.getName() + ",年龄: " + student.getAge());
}
}
// 12. 继承示例
class Animal {
public void eat() {
System.out.println("动物在吃东西");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("汪汪汪");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
// 13. 多态示例
class Shape {
public void draw() {
System.out.println("绘制图形");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
shape1.draw();
shape2.draw();
}
}
// 14. 抽象类示例
abstract class AbstractShape {
public abstract double getArea();
public void display() {
System.out.println("这是一个抽象图形");
}
}
class Square extends AbstractShape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public double getArea() {
return side * side;
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Square square = new Square(5);
System.out.println("正方形面积: " + square.getArea());
square.display();
}
}
// 15. 接口示例
interface Flyable {
void fly();
}
class Bird implements Flyable {
@Override
public void fly() {
System.out.println("鸟儿在飞翔");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Bird bird = new Bird();
bird.fly();
}
}
// 16. 内部类示例
class Outer {
private int outerVar = 10;
class Inner {
public void accessOuter() {
System.out.println("外部类变量: " + outerVar);
}
}
}
public class InnerClassExample {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.accessOuter();
}
}
// 17. 数组使用
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
}
}
// 18. 集合框架 - ArrayList
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("苹果");
list.add("香蕉");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
// 19. 集合框架 - HashMap
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
}
}
// 20. 异常处理
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("捕获到异常: " + e.getMessage());
} finally {
System.out.println("无论是否有异常,都会执行这里");
}
}
}
// 21. 文件读取
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadingExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("读取文件时出错: " + e.getMessage());
}
}
}
// 22. 文件写入
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileWritingExample {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("这是写入文件的内容");
} catch (IOException e) {
System.out.println("写入文件时出错: " + e.getMessage());
}
}
}
// 23. 多线程基础
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程运行: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
for (int i = 0; i < 5; i++) {
System.out.println("主线程运行: " + i);
}
}
}
// 24. 实现Runnable接口创建线程
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Runnable线程运行: " + i);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
for (int i = 0; i < 5; i++) {
System.out.println("主线程运行: " + i);
}
}
}
// 25. 线程同步 - 使用synchronized关键字
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
public class SynchronizedExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("最终计数: " + counter.count);
}
}
// 26. 线程池示例
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++) {
executor.submit(() -> {
System.out.println(Thread.currentThread().getName() + " 执行任务");
});
}
executor.shutdown();
}
}
// 27. 生产者-消费者模型
import java.util.LinkedList;
import java.util.Queue;
class ProducerConsumerExample {
private static final int CAPACITY = 5;
private Queue<Integer> queue = new LinkedList<>();
public synchronized void produce() throws InterruptedException {
while (queue.size() == CAPACITY) {
wait();
}
int num = (int) (Math.random() * 100);
queue.add(num);
System.out.println("生产者生产: " + num);
notifyAll();
}
public synchronized void consume() throws InterruptedException {
while (queue.isEmpty()) {
wait();
}
int num = queue.poll();
System.out.println("消费者消费: " + num);
notifyAll();
}
}
class Producer implements Runnable {
private ProducerConsumerExample example;
public Producer(ProducerConsumerExample example) {
this.example = example;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
example.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private ProducerConsumerExample example;
public Consumer(ProducerConsumerExample example) {
this.example = example;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
example.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumerMain {
public static void main(String[] args) {
ProducerConsumerExample example = new ProducerConsumerExample();
Thread producerThread = new Thread(new Producer(example));
Thread consumerThread = new Thread(new Consumer(example));
producerThread.start();
consumerThread.start();
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 28. JDBC连接数据库并查询数据(以MySQL为例)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users")) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", 姓名: " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 29. JDBC插入数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBCInsertExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement("INSERT INTO users (name, age) VALUES (?,?)")) {
statement.setString(1, "Charlie");
statement.setInt(2, 28);
int rowsInserted = statement.executeUpdate();
System.out.println(rowsInserted + " 条数据插入成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 30. JDBC更新数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBCUpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement statement = connection.prepareStatement("UPDATE users SET age =? WHERE name =?")) {
statement.setInt(1, 30);
statement.setString(2, "Charlie");
int rowsUpdated = statement.executeUpdate();
System.out.println(rowsUpdated + " 条数据更新成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
以下从代码层面、算法和数据结构层面、内存管理层面、并发编程层面以及框架和工具层面,为你分享 Java 代码优化的经验:
代码层面
减少不必要的对象创建
- 解释:频繁创建对象会增加垃圾回收的负担,消耗更多的内存和 CPU 资源。可以通过复用对象来优化。
- 示例:
// 优化前
for (int i = 0; i < 1000; i++) {
StringBuilder sb = new StringBuilder();
sb.append("Number: ").append(i);
System.out.println(sb.toString());
}
// 优化后
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.setLength(0);
sb.append("Number: ").append(i);
System.out.println(sb.toString());
}
使用局部变量
- 解释:局部变量存储在栈上,访问速度比成员变量快,因为访问成员变量需要通过对象引用。
- 示例:
// 优化前
public class SlowClass {
private int value;
public void slowMethod() {
for (int i = 0; i < 1000; i++) {
value += i;
}
}
}
// 优化后
public class FastClass {
public void fastMethod() {
int localValue = 0;
for (int i = 0; i < 1000; i++) {
localValue += i;
}
}
}
避免使用魔法数字
- 解释:魔法数字是指代码中直接出现的常量,不利于代码的理解和维护。应使用常量来代替。
- 示例:
// 优化前
if (score > 90) {
grade = 'A';
}
// 优化后
public static final int A_GRADE_THRESHOLD = 90;
if (score > A_GRADE_THRESHOLD) {
grade = 'A';
}
算法和数据结构层面
选择合适的数据结构
- 解释:不同的数据结构适用于不同的场景,选择合适的数据结构可以显著提高代码的性能。
- 示例:如果需要频繁查找元素,使用
HashMap
比ArrayList
更高效;如果需要保持元素的插入顺序,使用LinkedHashMap
。
// 使用 HashMap 进行快速查找
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
int value = map.get("apple");
System.out.println(value);
}
}
优化算法复杂度
- 解释:尽量使用时间复杂度低的算法,避免使用暴力枚举等低效算法。
- 示例:计算斐波那契数列时,使用迭代算法比递归算法更高效。
// 递归算法,时间复杂度 O(2^n)
public class FibonacciRecursive {
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
// 迭代算法,时间复杂度 O(n)
public class FibonacciIterative {
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
int a = 0, b = 1, c;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
}
内存管理层面
及时释放资源
- 解释:对于文件、数据库连接、网络连接等资源,使用完后应及时关闭,避免资源泄漏。
- 示例:使用
try-with-resources
语句自动关闭资源。
import java.io.FileInputStream;
import java.io.IOException;
public class ResourceManagement {
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.util.ArrayList;
import java.util.List;
public class MemoryLeakExample {
private static final List<Object> staticList = new ArrayList<>();
public static void addObject(Object obj) {
staticList.add(obj);
}
public static void removeObject(Object obj) {
staticList.remove(obj);
}
}
并发编程层面
减少锁的粒度
- 解释:锁的粒度越大,线程竞争就越激烈,会影响程序的并发性能。应尽量减少锁的范围。
- 示例:
// 优化前
public class CoarseGrainedLock {
private final Object lock = new Object();
private int value;
public void updateValue() {
synchronized (lock) {
// 一些不需要同步的操作
// ...
value++;
}
}
}
// 优化后
public class FineGrainedLock {
private final Object lock = new Object();
private int value;
public void updateValue() {
// 一些不需要同步的操作
// ...
synchronized (lock) {
value++;
}
}
}
使用并发容器
- 解释:在多线程环境下,使用
ConcurrentHashMap
、CopyOnWriteArrayList
等并发容器可以避免使用锁,提高并发性能。 - 示例:
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentMapExample {
private static final ConcurrentMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
public static void main(String[] args) {
concurrentMap.put("key1", 1);
int value = concurrentMap.get("key1");
System.out.println(value);
}
}
框架和工具层面
合理使用缓存
- 解释:对于频繁访问且不经常变化的数据,可以使用缓存来减少数据库或其他数据源的访问次数。
- 示例:使用
Guava Cache
作为本地缓存。
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class GuavaCacheExample {
private static final Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
public static String getData(String key) {
String data = cache.getIfPresent(key);
if (data == null) {
// 从数据源获取数据
data = fetchDataFromSource(key);
cache.put(key, data);
}
return data;
}
private static String fetchDataFromSource(String key) {
// 模拟从数据源获取数据
return "Data for " + key;
}
}
利用日志框架优化日志输出
- 解释:避免在生产环境中输出大量的调试日志,使用合适的日志级别可以减少日志输出对性能的影响。
- 示例:使用
SLF4J
和Logback
作为日志框架。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingExample {
private static final Logger logger = LoggerFactory.getLogger(LoggingExample.class);
public static void main(String[] args) {
logger.info("This is an info message");
logger.debug("This is a debug message"); // 在生产环境中可配置为不输出
}
}
Java学习路线规划图
需要完整版PDF的,
请官住VX粽号:【灰灰聊架构】,回复:049,
勉废零取哦~~~~