Java实战技巧:从入门到进阶的50个核心代码示例
引言
Java作为一门广泛应用的编程语言,其强大的功能和灵活性使得它成为众多开发者的首选。无论是初学者还是有一定经验的开发者,掌握一些核心的代码示例和实战技巧,都能在学习和工作中事半功倍。本文将为大家详细介绍50个从入门到进阶的Java核心代码示例,帮助大家更好地理解和应用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 number = 10;
double decimal = 3.14;
char letter = ‘A’;
boolean flag = true;
System.out.println(“Number: ” + number);
System.out.println(“Decimal: ” + decimal);
System.out.println(“Letter: ” + letter);
System.out.println(“Flag: ” + flag);
}
}
条件语句
public class IfElse {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println(“You are an adult.”);
} else {
System.out.println(“You are not an adult.”);
}
}
}
循环语句
public class Loops {
public static void main(String[] args) {
// For loop
for (int i = 0; i < 5; i++) {
System.out.println("For loop: " + i);
}
// While loop
int j = 0;
while (j < 5) {
System.out.println("While loop: " + j);
j++;
}
}
}
数组操作
public class Arrays {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
}
}
二、面向对象编程
类的定义和对象创建
“`java
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("Alice", 25);
person.display();
}
}
7. **封装**
```java
public class Employee {
private String name;
private int salary;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getSalary() {
return salary;
}
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee();
employee.setName("Bob");
employee.setSalary(50000);
System.out.println("Name: " + employee.getName() + ", Salary: " + employee.getSalary());
}
}
继承
“`java
public class Animal {
public void eat() {
System.out.println(“This animal eats food.”);
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
9. **多态**
```java
public class Shape {
public void draw() {
System.out.println("Drawing a shape.");
}
}
public class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}
public class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle.");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
shape1.draw();
shape2.draw();
}
}
接口
public interface Animal {
void eat();
void travel();
}
public class Mammal implements Animal {
@Override
public void eat() {
System.out.println("Mammal eats.");
}
@Override
public void travel() {
System.out.println("Mammal travels.");
}
}
public class Main {
public static void main(String[] args) {
Mammal mammal = new Mammal();
mammal.eat();
mammal.travel();
}
}
三、核心Java编程
字符串操作
public class StringOperations {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println("Length: " + str.length());
System.out.println("Uppercase: " + str.toUpperCase());
System.out.println("Lowercase: " + str.toLowerCase());
System.out.println("Substring: " + str.substring(7));
}
}
集合框架
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Collections {
public static void main(String[] args) {
// ArrayList
ArrayList
list.add(“Apple”);
list.add(“Banana”);
list.add(“Cherry”);
System.out.println(“ArrayList: ” + list);
// HashSet
HashSet
set.add(“Apple”);
set.add(“Banana”);
set.add(“Cherry”);
System.out.println(“HashSet: ” + set);
// HashMap
HashMap
map.put(“Apple”, 1);
map.put(“Banana”, 2);
map.put(“Cherry”, 3);
System.out.println(“HashMap: ” + map);
}
}
文件输入输出
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileIO {
public static void main(String[] args) {
// Writing to a file
try (FileWriter writer = new FileWriter(“output.txt”)) {
writer.write(“Hello, World!”);
} catch (IOException e) {
e.printStackTrace();
}
// Reading from a file
try (Scanner scanner = new Scanner(new File(“output.txt”))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
异常处理
public class ExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Cannot divide by zero.”);
} finally {
System.out.println(“This block is always executed.”);
}
}
}
泛型
public class GenericClass
private T data;
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
public class Main {
public static void main(String[] args) {
GenericClass
stringData.setData(“Generic String”);
System.out.println(stringData.getData());
GenericClass
integerData.setData(123);
System.out.println(integerData.getData());
}
}
四、进阶Java编程
多线程
public class MyThread extends Thread {
public void run() {
System.out.println(“Thread is running.”);
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
同步与锁
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
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("Count: " + counter.getCount());
}
}
网络编程
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class URLReader {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
数据库连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
System.out.println("User ID: " + resultSet.getInt("id"));
System.out.println("User Name: " + resultSet.getString("name"));
}
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
反射
public class ReflectionExample {
public static void main(String[] args) {
try {
Class> clazz = Class.forName(“java.util.ArrayList”);
System.out.println(“Class Name: ” + clazz.getName());
System.out.println(“Superclass: ” + clazz.getSuperclass());
java.lang.reflect.Method[] methods = clazz.getMethods();
for (java.lang.reflect.Method method : methods) {
System.out.println(“Method: ” + method.getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
五、高级应用
Web开发(Servlet)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html”);
response.getWriter().println(“
Hello, World!
“);
}
}
Spring框架
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloWorldController {
@GetMapping(“/hello”)
@ResponseBody
public String helloWorld() {
return “Hello, World!”;
}
}
Maven项目构建
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
assertEquals(5, calculator.add(2, 3));
}
}
日志管理(Log4j)
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoggingExample {
private static final Logger logger = LogManager.getLogger(LoggingExample.class);
public static void main(String[] args) {
logger.info(“This is an info message.”);
logger.error(“This is an error message.”);
}
}
六、实践项目与进阶学习
简单的计算器
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a – b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException(“Cannot divide by zero.”);
}
return (double) a / b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(“Addition: ” + calculator.add(5, 3));
System.out.println(“Subtraction: ” + calculator.subtract(5, 3));
System.out.println(“Multiplication: ” + calculator.multiply(5, 3));
System.out.println(“Division: ” + calculator.divide(5, 3));
}
}
待办事项列表
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TodoList {
private List
public void addTask(String task) {
tasks.add(task);
}
public void removeTask(int index) {
if (index >= 0 && index < tasks.size()) {
tasks.remove(index);
} else {
System.out.println("Invalid task index.");
}
}
public void displayTasks() {
if (tasks.isEmpty()) {
System.out.println("No tasks in the list.");
} else {
for (int i = 0; i < tasks.size(); i++) {
System.out.println((i + 1) + ". " + tasks.get(i));
}
}
}
}
public class Main {
public static void main(String[] args) {
TodoList todoList = new TodoList();
Scanner scanner = new Scanner(System.in);
String input;
while (true) {
System.out.println("Enter a task (or 'exit' to quit): ");
input = scanner.nextLine();
if ("exit".equalsIgnoreCase(input)) {
break;
}
todoList.addTask(input);
}
todoList.displayTasks();
}
}
简单的Web服务器
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class SimpleWebServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/hello", new HelloHandler());
server.setExecutor(null);
server.start();
System.out.println("Server started on port 8080");
}
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello, World!";
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
数据库CRUD操作
“`java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseCRUD {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
// Create
String createSQL = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement createStatement = connection.prepareStatement(createSQL);
createStatement.setString(1, "Alice");
createStatement.setInt(2, 25);
createStatement.executeUpdate();
// Read
String readSQL = "SELECT * FROM users";
PreparedStatement readStatement = connection.prepareStatement(readSQL);
ResultSet resultSet = readStatement.executeQuery();
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id"));
System.out.println("Name: " + resultSet.getString("name"));
System.out.println("Age: " + resultSet.getInt("age"));
}
// Update
String updateSQL = "UPDATE users SET