Java零基础入门教程(菜鸟版)
目录
- Java简介
- 第一个Java程序
- Java基础语法
- 变量与数据类型
- 运算符
- 控制流程
- 数组
- 面向对象编程(OOP)
- 类与对象
- 继承与多态
- 封装与抽象
- 接口
- 常用类库
- String类
- 集合框架
- 异常处理
- 进阶内容
- 文件操作
- 多线程
- 网络编程
- 学习资源推荐
1. Java简介
Java是一种面向对象的编程语言,由Sun Microsystems于1995年发布。它具有以下特点:
- 跨平台性:Java程序可以在任何支持Java虚拟机(JVM)的设备上运行。
- 面向对象:Java支持封装、继承、多态等面向对象特性。
- 健壮性:Java有强大的异常处理机制和内存管理。
- 丰富的类库:Java提供了大量的标准类库,方便开发者快速开发。
2. 第一个Java程序
2.1 编写HelloWorld程序
Java程序的基本结构如下:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
public class HelloWorld
:定义一个公共类,类名必须与文件名一致。public static void main(String[] args)
:主方法,程序从这里开始执行。System.out.println()
:输出内容到控制台。
2.2 代码解析
- 类(Class):Java程序的基本单位,所有的代码都必须写在类中。
- 方法(Method):类中的函数,
main
方法是程序的入口。 - 语句(Statement):每行代码以分号
;
结尾。
3. Java基础语法
3.1 变量与数据类型
Java是强类型语言,变量必须先声明后使用。常见数据类型:
- 基本数据类型:
- 整数:
byte
(1字节)、short
(2字节)、int
(4字节)、long
(8字节) - 浮点数:
float
(4字节)、double
(8字节) - 字符:
char
(2字节) - 布尔:
boolean
(1位)
- 整数:
- 引用数据类型:
String
、数组、类、接口等。
示例:
int age = 25; // 整数
double price = 19.99; // 浮点数
char grade = 'A'; // 字符
boolean isJavaFun = true; // 布尔
String name = "John"; // 字符串
3.2 运算符
- 算术运算符:
+
、-
、*
、/
、%
- 比较运算符:
==
、!=
、>
、<
、>=
、<=
- 逻辑运算符:
&&
(与)、||
(或)、!
(非) - 赋值运算符:
=
、+=
、-=
示例:
int a = 10;
int b = 20;
int sum = a + b; // 加法
boolean isEqual = (a == b); // 比较
3.3 控制流程
- 条件语句:
if (a > b) { System.out.println("a is greater"); } else if (a == b) { System.out.println("a equals b"); } else { System.out.println("b is greater"); }
- switch语句:
int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other day"); }
- 循环语句:
for (int i = 0; i < 5; i++) { System.out.println(i); } while (a > 0) { System.out.println(a); a--; } do { System.out.println(a); a--; } while (a > 0);
3.4 数组
数组是存储相同类型数据的集合。
int[] numbers = {1, 2, 3, 4, 5}; // 定义数组
System.out.println(numbers[0]); // 访问第一个元素
numbers[1] = 10; // 修改第二个元素
4. 面向对象编程(OOP)
4.1 类与对象
- 类:是对象的模板,定义了对象的属性和方法。
- 对象:是类的实例。
示例:
class Dog {
String name; // 属性
int age;
void bark() { // 方法
System.out.println(name + " is barking!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // 创建对象
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // 调用方法
}
}
4.2 继承与多态
- 继承:子类可以继承父类的属性和方法。
- 多态:同一个方法在不同对象中有不同的实现。
示例:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
4.3 封装与抽象
- 封装:隐藏对象的内部细节,通过公共方法访问数据。
- 抽象:通过抽象类和接口定义规范。
4.4 接口
接口定义了一组方法规范,类可以实现接口。
interface Animal {
void sound();
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
5. 常用类库
5.1 String类
String
是Java中最常用的类之一,用于操作字符串。字符串是不可变的(immutable),即一旦创建就不能修改。
常用方法
- 长度:
length()
String str = "Hello"; System.out.println(str.length()); // 输出:5
- 拼接:
concat()
或+
String s1 = "Hello"; String s2 = "World"; String s3 = s1.concat(s2); // 或者 s1 + s2 System.out.println(s3); // 输出:HelloWorld
- 比较:
equals()
和equalsIgnoreCase()
String s1 = "Java"; String s2 = "java"; System.out.println(s1.equals(s2)); // 输出:false System.out.println(s1.equalsIgnoreCase(s2)); // 输出:true
- 查找:
indexOf()
和contains()
String str = "Hello World"; System.out.println(str.indexOf("World")); // 输出:6 System.out.println(str.contains("Hello")); // 输出:true
- 截取:
substring()
String str = "Hello World"; System.out.println(str.substring(6)); // 输出:World System.out.println(str.substring(0, 5)); // 输出:Hello
- 替换:
replace()
String str = "Hello World"; System.out.println(str.replace("World", "Java")); // 输出:Hello Java
5.2 集合框架
Java集合框架提供了多种数据结构和算法,常用的集合类包括ArrayList
、LinkedList
、HashSet
、HashMap
等。
ArrayList
- 特点:动态数组,支持快速随机访问。
- 常用方法:
import java.util.ArrayList; ArrayList<String> list = new ArrayList<>(); list.add("Apple"); // 添加元素 list.add("Banana"); System.out.println(list.get(0)); // 获取元素:Apple list.set(1, "Orange"); // 修改元素 list.remove(0); // 删除元素 System.out.println(list.size()); // 获取大小
HashMap
- 特点:键值对存储,键不能重复。
- 常用方法:
import java.util.HashMap; HashMap<String, Integer> map = new HashMap<>(); map.put("Apple", 10); // 添加键值对 map.put("Banana", 20); System.out.println(map.get("Apple")); // 获取值:10 map.remove("Banana"); // 删除键值对 System.out.println(map.containsKey("Apple")); // 检查键是否存在:true
HashSet
- 特点:无序且不重复的集合。
- 常用方法:
import java.util.HashSet; HashSet<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Apple"); // 重复元素不会被添加 System.out.println(set.size()); // 输出:2
5.3 异常处理
Java的异常处理机制通过try-catch-finally
块实现。
基本语法
try {
int result = 10 / 0; // 可能抛出异常的代码
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero"); // 捕获异常
} finally {
System.out.println("This will always run"); // 无论是否异常都会执行
}
自定义异常
可以通过继承Exception
类创建自定义异常。
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
throw new MyException("This is a custom exception");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
6. 进阶内容
6.1 文件操作
Java提供了java.io
包和java.nio
包来处理文件操作。
读写文本文件
- 读取文件:
import java.io.FileReader; import java.io.IOException; try (FileReader reader = new FileReader("example.txt")) { int data; while ((data = reader.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); }
- 写入文件:
import java.io.FileWriter; import java.io.IOException; try (FileWriter writer = new FileWriter("output.txt")) { writer.write("Hello, World!"); } catch (IOException e) { e.printStackTrace(); }
读写二进制文件
- 读取二进制文件:
import java.io.FileInputStream; import java.io.IOException; try (FileInputStream input = new FileInputStream("example.bin")) { int data; while ((data = input.read()) != -1) { System.out.print(data); } } catch (IOException e) { e.printStackTrace(); }
- 写入二进制文件:
import java.io.FileOutputStream; import java.io.IOException; try (FileOutputStream output = new FileOutputStream("output.bin")) { output.write(65); // 写入字节 } catch (IOException e) { e.printStackTrace(); }
6.2 多线程
Java通过Thread
类和Runnable
接口支持多线程编程。
创建线程
- 继承
Thread
类: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(); // 启动线程 } }
- 实现
Runnable
接口:class MyRunnable implements Runnable { public void run() { System.out.println("Thread is running"); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // 启动线程 } }
线程同步
使用synchronized
关键字实现线程同步。
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) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount()); // 输出:2000
}
}
6.3 网络编程
Java通过Socket
和ServerSocket
类实现网络通信。
客户端
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
out.println("Hello, Server");
String response = in.readLine();
System.out.println("Server: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is listening on port 8080");
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String message = in.readLine();
System.out.println("Client: " + message);
out.println("Hello, Client");
} catch (IOException e) {
e.printStackTrace();
}
}
}