Java简介与安装
Java是一种面向对象的、跨平台的编程语言,由Sun Microsystems于1995年发布。Java以“一次编写,处处运行”(Write Once, Run Anywhere, 简称WORA)的理念,支持在多种操作系统上运行。要开始学习Java,首先需要安装Java开发工具包(Java Development Kit, JDK)和集成开发环境(Integrated Development Environment, IDE)。
Java基本语法
变量与数据类型
Java中的变量用于存储数据,必须先声明数据类型和变量名。数据类型包括int
(整数)、float
(实数)、char
(字符)、String
(字符串)等。
int age = 25;
float price = 99.99f;
char grade = 'A';
String name = "Alice";
运算符
Java支持算术运算、比较运算、逻辑运算等。
int a = 10, b = 5;
int sum = a + b; // 加法
int difference = a - b; // 减法
int product = a * b; // 乘法
int quotient = a / b; // 除法
int remainder = a % b; // 取模(余数)
boolean isGreaterThan = (a > b); // 比较运算
boolean isNotEqual = (a != b); // 逻辑运算
控制结构
Java提供了if
、else if
、else
、switch
、for
、while
等控制结构。
int score = 90;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 70) {
System.out.println("良好");
} else {
System.out.println("及格");
}
for (int i = 0; i < 10; i++) {
System.out.println("循环计数: " + i);
}
面向对象编程
类与对象
面向对象编程(Object-Oriented Programming, OOP)是Java的核心,它基于类(class)和对象(object)的概念。类定义了对象的属性(数据成员)和方法(成员函数),对象是类的实例。
class Person {
String name;
int age;
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Alice";
person.age = 25;
person.sayHello();
}
}
封装、继承与多态
封装是隐藏对象实现细节,只暴露必要的接口。继承允许创建一个类(子类)从另一个类(父类)继承属性和方法。多态允许使用父类引用调用子类特定的实现。
实现接口与抽象类
interface Greeting {
void greet();
}
class Person implements Greeting {
@Override
public void greet() {
System.out.println("Hello, my name is " + name);
}
}
class Student extends Person {
@Override
public void greet() {
System.out.println("Hello, my name is " + name + " and I'm a student.");
}
}
public class Main {
public static void main(String[] args) {
Greeting person = new Person();
person.greet();
Greeting student = new Student();
student.greet();
}
}
构造方法与实例化
构造方法在创建对象时被调用,用于初始化对象的属性。new
关键字用于实例化类。
class Student {
String name;
int grade;
Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
void displayInfo() {
System.out.println("Name: " + name + ", Grade: " + grade);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 10);
student.displayInfo();
}
}
Java集合框架
数组与集合简介
Java提供了一系列集合类,用于存储和操作数据。数组是最基本的集合,而集合类(如List
、Set
、Map
)提供了更高级的数据结构和功能。
List、Set、Map的使用与区别
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names);
Set<String> uniqueNames = new TreeSet<>(names);
System.out.println(uniqueNames);
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);
scores.put("Charlie", 88);
System.out.println(scores);
}
}
Iterator与List接口的操作
迭代器(Iterator)用于遍历集合中的元素。
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
高级集合类
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeSet;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("原始列表: " + numbers);
LinkedList<Integer> linkedList = new LinkedList<>(numbers);
System.out.println("链表: " + linkedList);
TreeSet<Integer> sortedSet = new TreeSet<>(numbers);
System.out.println("排序集合: " + sortedSet);
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println("映射表: " + map);
}
}
Java异常处理
异常与错误的区别
Java中的异常用于处理程序执行时发生的预料之外的事件,而错误则表示程序执行时的严重问题。
常见异常类型
常用的异常类有NullPointerException
、ArrayIndexOutOfBoundsException
、FileNotFoundException
等。
public class Main {
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length()); // 引发NullPointerException
} catch (NullPointerException e) {
System.out.println("捕获到空指针异常: " + e.getMessage());
}
}
}
自定义异常
可以使用throw
关键字抛出异常,或使用throws
关键字声明可能抛出的异常类型。
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void checkAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("用户年龄过小!");
}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (CustomException e) {
System.out.println("捕获到自定义异常: " + e.getMessage());
}
}
}
文件与I/O操作
文件路径与文件对象
操作文件需要通过File
类来构建文件对象,然后通过对象调用相应的方法。
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println("文件路径: " + file.getAbsolutePath());
}
}
文件读写操作
使用BufferedReader
和BufferedWriter
进行文件读写。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileIO {
public static void main(String[] args) {
readFromFile("input.txt");
writeToFile("output.txt", "Hello, file reading and writing!");
}
public static void readFromFile(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeToFile(String fileName, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content);
System.out.println("内容已写入文件: " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java项目实战
选择合适的技术栈
选择合适的技术栈是项目成功的先决条件。对于Java项目,可以考虑使用Spring Boot、MyBatis、Spring Data JPA等框架。
设计模式简介与实际应用
了解设计模式,如单一职责原则、开闭原则、依赖注入等,有助于编写更清晰、更可维护的代码。
项目组建与数据库连接
使用Maven或Gradle进行项目构建,通过JDBC实现与数据库的连接。
import java.sql.Connection;
import java.sql.DriverManager;
public class DatabaseConnection {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
System.out.println("数据库连接成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
单元测试与代码重构
利用JUnit等框架进行单元测试,确保代码的正确性和稳定性。重构代码以提高可读性和可维护性。
项目部署与版本控制
使用Docker进行项目部署,利用Git进行版本控制。
以上内容覆盖了Java项目开发从零开始的实战指南,从基础语法到项目实战,希望能帮助你建立起扎实的Java编程基础。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章