Java 是一种广泛使用的面向对象的编程语言,以其“编写一次,到处运行”的特性而闻名。
每个 Java 程序至少包含一个类,并且程序从 main
方法开始执行。
javapublic class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
public class HelloWorld
:定义了一个名为 HelloWorld
的公共类。public static void main(String[] args)
:这是 Java 应用程序的入口点。System.out.println()
:用于打印输出到控制台。Java 有两大类数据类型:基本类型和引用类型(对象)。
byte
, short
, int
, long
float
, double
char
boolean
javaint age = 25;
double height = 5.7;
char initial = 'J';
boolean isStudent = true;
变量存储数据,可以随时改变其值;常量使用 final
关键字声明,一旦赋值后不可更改。
javafinal double PI = 3.14159; // 常量
int x = 10; // 变量
x = 20; // 合法
// PI = 3.14; // 错误,不能修改常量
Java 支持多种运算符,包括算术运算符、关系运算符、逻辑运算符等。
javaint a = 10, b = 5;
System.out.println(a + b); // 输出: 15
System.out.println(a > b); // 输出: true
System.out.println((a > b) && (a != b)); // 输出: true
javaif (age >= 18) {
System.out.println("Adult");
} else if (age >= 13) {
System.out.println("Teenager");
} else {
System.out.println("Child");
}
for
循环:javafor (int i = 0; i < 5; i++) {
System.out.println(i);
}
while
循环:javaint count = 0;
while (count < 5) {
System.out.println(count);
count++;
}
do...while
循环:javaint number = 0;
do {
System.out.println(number);
number++;
} while (number < 5);
数组是一种容器对象,用于存储固定大小的同种类型的元素。
javaint[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
System.out.println(numbers[0]); // 输出: 1
// 或者直接初始化
int[] nums = {1, 2, 3, 4, 5};
在 Java 中称为方法,用于封装代码块以实现特定功能。
javapublic 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: " + result); // 输出: Result: 8
}
Java 是面向对象的语言,支持类、对象、继承、封装、多态等概念。
javaclass Person {
String name;
int age;
void introduce() {
System.out.println("My name is " + name + " and I am " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Alice";
person.age = 30;
person.introduce(); // 输出: My name is Alice and I am 30 years old.
}
}
javaclass Student extends Person {
String grade;
void study() {
System.out.println(name + " is studying in grade " + grade);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.name = "Bob";
student.age = 15;
student.grade = "10";
student.introduce(); // 调用了父类的方法
student.study(); // 调用了子类的方法
}
}
Java 提供了异常处理机制来捕获并处理错误。
javatry {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This block always executes.");
}
使用 Scanner
类进行输入操作,System.out
进行输出操作。
javaimport java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
}
}
Java 提供了丰富的标准库,例如 java.util
包中的集合框架、日期时间 API 等。
ArrayList
示例:javaimport java.util.ArrayList;
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits.get(0)); // 输出: Apple
HashMap
示例:javaimport java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
System.out.println(map.get("Alice")); // 输出: 30
使用 java.io
包中的类来进行文件读写操作。
javaimport java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, File!");
writer.close();
}
}
javaimport java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
泛型允许你在定义类、接口和方法时使用类型参数,使得代码可以在多种数据类型上复用,同时保持类型安全。
javapublic class Box<T> {
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
public static void main(String[] args) {
Box<Integer> integerBox = new Box<>();
integerBox.set(10);
System.out.println(integerBox.get()); // 输出: 10
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
System.out.println(stringBox.get()); // 输出: Hello
}
}
javapublic class Util {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
String[] stringArray = {"A", "B", "C"};
Util.printArray(intArray); // 输出: 1 2 3
Util.printArray(stringArray); // 输出: A B C
}
}
Java 提供了丰富的集合框架,包括 List
, Set
, Map
等接口及其具体实现。
ArrayList
javaimport java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // 输出: Apple
}
}
HashSet
javaimport java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // 重复元素不会被添加
System.out.println(set.size()); // 输出: 2
}
}
HashMap
javaimport java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
System.out.println(map.get("Alice")); // 输出: 30
}
}
Java 提供了多种方式来实现多线程编程,包括继承 Thread
类和实现 Runnable
接口。
Thread
类javaclass MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
Runnable
接口javaclass MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
Java 提供了丰富的并发工具包 java.util.concurrent
,用于简化并发编程。
ExecutorService
javaimport java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
executor.execute(new MyRunnable());
}
executor.shutdown();
}
}
CountDownLatch
javaimport java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is working.");
latch.countDown();
}).start();
}
latch.await(); // 等待所有线程完成
System.out.println("All tasks are done.");
}
}
Java 提供了多种 I/O 流用于处理文件和其他外部资源的读写操作。
BufferedReader
和 BufferedWriter
javaimport java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("example.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write("Hello, File!");
bufferedWriter.close();
FileReader reader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
}
反射允许在运行时动态地获取类的信息或调用对象的方法。
javaimport java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Class<?> cls = Class.forName("Person");
Object obj = cls.getDeclaredConstructor().newInstance();
Method method = cls.getMethod("setName", String.class);
method.invoke(obj, "Alice");
Method getNameMethod = cls.getMethod("getName");
System.out.println(getNameMethod.invoke(obj)); // 输出: Alice
}
}
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
注解提供了一种元数据机制,可用于编译时检查或运行时处理。
javaimport java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface TestAnnotation {
String value();
}
public class Main {
@TestAnnotation(value = "TestMethod")
public void myMethod() {
System.out.println("This is a test method.");
}
public static void main(String[] args) throws Exception {
Method method = Main.class.getMethod("myMethod");
if (method.isAnnotationPresent(TestAnnotation.class)) {
TestAnnotation annotation = method.getAnnotation(TestAnnotation.class);
System.out.println(annotation.value()); // 输出: TestMethod
}
}
}
Java 8 引入了 Lambda 表达式,简化了匿名内部类的编写,并支持函数式编程。
java@FunctionalInterface
interface MyFunction {
void apply();
}
public class Main {
public static void main(String[] args) {
MyFunction function = () -> System.out.println("Lambda expression");
function.apply(); // 输出: Lambda expression
}
}
javaimport java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
// 或者使用方法引用
names.forEach(System.out::println);
}
}