1. Java概述
Java是一种广泛使用的计算机编程语言,拥有”一次编写,到处运行”的特性,适用于构建各种类型的应用程序,包括Web应用、移动应用、桌面应用等。更多学习教程www.fgedu.net.cn
2. Java开发环境搭建
搭建Java开发环境需要安装JDK(Java Development Kit),并配置相关环境变量。
# 1. 下载JDK
$ wget https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.rpm
# 2. 安装JDK
$ sudo rpm -ivh jdk-17_linux-x64_bin.rpm
# 3. 验证安装
$ java -version
openjdk version “17.0.8” 2023-07-18
OpenJDK Runtime Environment (build 17.0.8+7)
OpenJDK 64-Bit Server VM (build 17.0.8+7, mixed mode, sharing)
# 4. 配置环境变量
$ vi ~/.bashrc
# 添加以下内容
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-17.0.8.0.7-1.el7_9.x86_64
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
# 使环境变量生效
$ source ~/.bashrc
# 验证环境变量
$ echo $JAVA_HOME
/usr/lib/jvm/java-17-openjdk-17.0.8.0.7-1.el7_9.x86_64
3. Java基础知识
Java基础知识包括变量、数据类型、运算符、控制语句、方法等。学习交流加群风哥微信: itpux-com
public class HelloWorld {
public static void main(String[] args) {
// 变量声明与初始化
int age = 25;
String name = “Java Developer”;
double salary = 5000.0;
boolean isEmployed = true;
// 输出信息
System.out.println(“Hello, ” + name + “!”);
System.out.println(“Age: ” + age);
System.out.println(“Salary: ” + salary);
System.out.println(“Employed: ” + isEmployed);
// 控制语句
if (age >= 18) {
System.out.println(“Adult”);
} else {
System.out.println(“Minor”);
}
// 循环语句
System.out.println(“Counting from 1 to 5:”);
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// 方法调用
int result = add(10, 20);
System.out.println("Sum: " + result);
}
// 方法定义
public static int add(int a, int b) {
return a + b;
}
}
// 编译和运行
// $ javac HelloWorld.java
// $ java HelloWorld
// 输出:
// Hello, Java Developer!
// Age: 25
// Salary: 5000.0
// Employed: true
// Adult
// Counting from 1 to 5:
// 1
// 2
// 3
// 4
// 5
// Sum: 30
4. 面向对象编程
Java是一种面向对象的编程语言,支持封装、继承、多态等面向对象特性。
// 父类
class Animal {
// 成员变量
private String name;
private int age;
// 构造方法
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// 成员方法
public void eat() {
System.out.println(name + ” is eating”);
}
public void sleep() {
System.out.println(name + ” is sleeping”);
}
// Getter和Setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
// 子类
class Dog extends Animal {
// 子类特有成员变量
private String breed;
// 构造方法
public Dog(String name, int age, String breed) {
super(name, age); // 调用父类构造方法
this.breed = breed;
}
// 重写父类方法
@Override
public void eat() {
System.out.println(getName() + ” (” + breed + “) is eating bones”);
}
// 子类特有方法
public void bark() {
System.out.println(getName() + ” is barking”);
}
}
// 测试类
public class OOPExample {
public static void main(String[] args) {
// 创建Animal对象
Animal animal = new Animal(“Generic Animal”, 5);
animal.eat();
animal.sleep();
// 创建Dog对象
Dog dog = new Dog(“Buddy”, 3, “Golden Retriever”);
dog.eat(); // 调用重写的方法
dog.sleep();
dog.bark(); // 调用子类特有方法
// 多态
Animal animal2 = new Dog(“Max”, 2, “Labrador”);
animal2.eat(); // 调用Dog类的eat方法
// animal2.bark(); // 编译错误,父类引用不能调用子类特有方法
}
}
// 输出:
// Generic Animal is eating
// Generic Animal is sleeping
// Buddy (Golden Retriever) is eating bones
// Buddy is sleeping
// Buddy is barking
// Max (Labrador) is eating bones
5. 集合框架
Java集合框架提供了多种数据结构,如列表、集合、映射等,用于存储和操作数据。
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
// List – 有序,可重复
List
list.add(“Apple”);
list.add(“Banana”);
list.add(“Orange”);
list.add(“Apple”); // 允许重复
System.out.println(“List:”);
for (String fruit : list) {
System.out.println(fruit);
}
// Set – 无序,不可重复
Set
set.add(“Apple”);
set.add(“Banana”);
set.add(“Orange”);
set.add(“Apple”); // 重复元素不会被添加
System.out.println(“\nSet:”);
for (String fruit : set) {
System.out.println(fruit);
}
// Map – 键值对
Map
map.put(“Apple”, 100);
map.put(“Banana”, 50);
map.put(“Orange”, 75);
System.out.println(“\nMap:”);
for (Map.Entry
System.out.println(entry.getKey() + “: ” + entry.getValue());
}
// 集合操作
System.out.println(“\nList size: ” + list.size());
System.out.println(“Set contains ‘Apple’: ” + set.contains(“Apple”));
System.out.println(“Map get ‘Banana’: ” + map.get(“Banana”));
// 排序
Collections.sort(list);
System.out.println(“\nSorted List:”);
for (String fruit : list) {
System.out.println(fruit);
}
}
}
// 输出:
// List:
// Apple
// Banana
// Orange
// Apple
//
// Set:
// Apple
// Banana
// Orange
//
// Map:
// Apple: 100
// Banana: 50
// Orange: 75
//
// List size: 4
// Set contains ‘Apple’: true
// Map get ‘Banana’: 50
//
// Sorted List:
// Apple
// Apple
// Banana
// Orange
6. 异常处理
Java异常处理机制用于处理程序运行过程中出现的错误,提高程序的健壮性。学习交流加群风哥QQ113257174
import java.io.IOException;
public class ExceptionExample {
public static void main(String[] args) {
// try-catch-finally
try {
int result = divide(10, 0);
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Error: ” + e.getMessage());
} finally {
System.out.println(“Finally block executed”);
}
// 多个catch块
try {
String str = null;
System.out.println(str.length());
} catch (ArithmeticException e) {
System.out.println(“Arithmetic error: ” + e.getMessage());
} catch (NullPointerException e) {
System.out.println(“Null pointer error: ” + e.getMessage());
} catch (Exception e) {
System.out.println(“General error: ” + e.getMessage());
}
// 抛出异常
try {
checkAge(-5);
} catch (IllegalArgumentException e) {
System.out.println(“Error: ” + e.getMessage());
}
// 自定义异常
try {
validateEmail(“invalid-email”);
} catch (EmailValidationException e) {
System.out.println(“Email validation error: ” + e.getMessage());
}
}
// 可能抛出异常的方法
public static int divide(int a, int b) {
return a / b;
}
// 抛出异常的方法
public static void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
System.out.println("Valid age: " + age);
}
// 抛出自定义异常的方法
public static void validateEmail(String email) throws EmailValidationException {
if (!email.contains("@")) {
throw new EmailValidationException("Invalid email format");
}
System.out.println("Valid email: " + email);
}
}
// 自定义异常类
class EmailValidationException extends Exception {
public EmailValidationException(String message) {
super(message);
}
}
// 输出:
// Error: / by zero
// Finally block executed
// Null pointer error: Cannot invoke "String.length()" because "str" is null
// Error: Age cannot be negative
// Email validation error: Invalid email format
7. I/O操作
Java I/O操作用于读写文件、网络通信等,包括字节流和字符流。
import java.io.*;
import java.nio.file.*;
public class IOExample {
public static void main(String[] args) {
// 写入文件
try (FileWriter writer = new FileWriter(“example.txt”)) {
writer.write(“Hello, Java I/O!\n”);
writer.write(“This is a test file.\n”);
System.out.println(“File written successfully”);
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try (FileReader reader = new FileReader(“example.txt”)) {
int character;
System.out.println(“File content:”);
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
e.printStackTrace();
}
// 使用BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader(“example.txt”))) {
String line;
System.out.println(“\nUsing BufferedReader:”);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// 使用NIO Paths和Files
try {
Path path = Paths.get(“example.txt”);
System.out.println(“\nUsing NIO:”);
Files.lines(path).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 输出:
// File written successfully
// File content:
// Hello, Java I/O!
// This is a test file.
//
// Using BufferedReader:
// Hello, Java I/O!
// This is a test file.
//
// Using NIO:
// Hello, Java I/O!
// This is a test file.
8. 多线程编程
Java多线程编程允许程序同时执行多个任务,提高程序的执行效率。更多学习教程公众号风哥教程itpux_com
// 方式1:继承Thread类
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(500); // 暂停500毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 方式2:实现Runnable接口
class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MultithreadingExample {
public static void main(String[] args) {
// 使用Thread类
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
// 使用Runnable接口
Thread thread3 = new Thread(new MyRunnable("Thread 3"));
Thread thread4 = new Thread(new MyRunnable("Thread 4"));
thread3.start();
thread4.start();
// 使用Lambda表达式(Java 8+)
Thread thread5 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 5: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread5.start();
}
}
// 输出(顺序可能不同):
// Thread 1: 1
// Thread 2: 1
// Thread 3: 1
// Thread 4: 1
// Thread 5: 1
// Thread 1: 2
// Thread 2: 2
// Thread 3: 2
// Thread 4: 2
// Thread 5: 2
// Thread 1: 3
// Thread 2: 3
// Thread 3: 3
// Thread 4: 3
// Thread 5: 3
// Thread 1: 4
// Thread 2: 4
// Thread 3: 4
// Thread 4: 4
// Thread 5: 4
// Thread 1: 5
// Thread 2: 5
// Thread 3: 5
// Thread 4: 5
// Thread 5: 5
9. Lambda表达式与Stream API
Java 8引入了Lambda表达式和Stream API,使得代码更加简洁和函数式。
import java.util.*;
import java.util.stream.*;
public class LambdaStreamExample {
public static void main(String[] args) {
// 列表
List
// 使用Lambda表达式
System.out.println(“Using Lambda expressions:”);
// 遍历列表
fruits.forEach(fruit -> System.out.println(fruit));
// 使用Stream API
System.out.println(“\nUsing Stream API:”);
// 过滤操作
System.out.println(“Fruits starting with ‘A’:”);
fruits.stream()
.filter(fruit -> fruit.startsWith(“A”))
.forEach(System.out::println);
// 映射操作
System.out.println(“\nFruit lengths:”);
fruits.stream()
.map(fruit -> fruit.length())
.forEach(System.out::println);
// 排序操作
System.out.println(“\nSorted fruits:”);
fruits.stream()
.sorted()
.forEach(System.out::println);
// 收集操作
System.out.println(“\nCollecting to list:”);
List
.sorted()
.collect(Collectors.toList());
System.out.println(sortedFruits);
// 聚合操作
System.out.println(“\nTotal fruit length:”);
int totalLength = fruits.stream()
.mapToInt(String::length)
.sum();
System.out.println(totalLength);
// 查找操作
System.out.println(“\nAny fruit starts with ‘P’:”);
boolean anyStartsWithP = fruits.stream()
.anyMatch(fruit -> fruit.startsWith(“P”));
System.out.println(anyStartsWithP);
System.out.println(“\nAll fruits have length > 3:”);
boolean allLengthGreaterThan3 = fruits.stream()
.allMatch(fruit -> fruit.length() > 3);
System.out.println(allLengthGreaterThan3);
}
}
// 输出:
// Using Lambda expressions:
// Apple
// Banana
// Orange
// Mango
// Pineapple
//
// Using Stream API:
// Fruits starting with ‘A’:
// Apple
//
// Fruit lengths:
// 5
// 6
// 6
// 5
// 9
//
// Sorted fruits:
// Apple
// Banana
// Mango
// Orange
// Pineapple
//
// Collecting to list:
// [Apple, Banana, Mango, Orange, Pineapple]
//
// Total fruit length:
// 31
//
// Any fruit starts with ‘P’:
// true
//
// All fruits have length > 3:
// true
10. Java开发最佳实践
Java开发最佳实践包括代码规范、性能优化、安全性等多个方面。
# 1. 代码规范
– 遵循Oracle Java Code Conventions或Google Java Style Guide
– 使用有意义的变量和方法命名
– 保持代码缩进一致
– 编写清晰的注释
– 避免过长的方法和类
# 2. 性能优化
– 使用StringBuilder进行字符串拼接
– 避免在循环中创建对象
– 使用适当的集合类型
– 合理使用多线程
– 避免过度使用反射
# 3. 安全性
– 防止SQL注入
– 防止XSS攻击
– 使用HTTPS
– 合理处理异常
– 避免硬编码敏感信息
# 4. 测试
– 编写单元测试
– 使用JUnit或TestNG框架
– 实现集成测试
– 进行性能测试
# 5. 工具和框架
– 使用Maven或Gradle进行依赖管理
– 使用IDE(如IntelliJ IDEA、Eclipse)提高开发效率
– 使用版本控制工具(如Git)
– 考虑使用Spring Boot等框架加速开发
author:www.itpux.com
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
