JAVA主流技术学习涵盖基础精讲、面向对象编程、集合框架、I/O流与NIO技术、多线程编程及网络编程等关键领域,提供全面的代码示例,旨在深入理解JAVA语言并应用于实际项目中。
JAVA基础精讲
JAVA概述与历史
JAVA是一种面向对象、基于类的、强类型编程语言。该语言由Sun Microsystems(现为Oracle)开发,首次发布于1995年,旨在实现“一次编写,处处运行”的理念。JAVA广泛应用于开发各种应用,包括服务器端应用、移动应用(如Android)、网络应用等。
JDK安装与环境配置
为了开始JAVA编程,首先需要安装Java Development Kit(JDK)。以下是以Windows操作系统为例的安装步骤:
% cd %PATH_TO_DOWNLOADS%
% tar zxf jdk-11.0.10_linux-x64_bin.tar.gz
% sudo cp jdk-11.0.10/bin/* /usr/local/bin
完成安装后,配置环境变量以确保系统能定位JAVA路径:
% vim /etc/profile
在文件尾部添加以下内容:
export JAVA_HOME=/usr/local/java
export PATH=$JAVA_HOME/bin:$PATH
执行source /etc/profile
以使配置生效。
JAVA基本语法与数据类型
public class Hello {
public static void main(String[] args) {
int age = 25;
String name = "John Doe";
System.out.println("My name is " + name + " and I am " + age + " years old.");
}
}
上述代码展示了JAVA中基本的数据类型(整型和字符串)以及如何使用System.out.println()
进行输出。
控制结构与方法编写
控制结构包括条件语句(if
, else if
, else
)和循环(for
, while
, do-while
)。方法定义包括返回类型、方法名、参数列表和方法体。
public class ControlFlow {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5.");
} else {
System.out.println("Number is less than or equal to 5.");
}
int sum = sumNumbers(3, 4);
System.out.println("Sum of 3 and 4 is: " + sum);
}
public static int sumNumbers(int a, int b) {
return a + b;
}
}
异常处理与文件操作
JAVA采用异常处理机制,通过try
, catch
, finally
块来处理可能发生的异常。
import java.io.*;
public class FileHandling {
public static void main(String[] args) {
try {
File file = new File("example.txt");
if (!file.exists()) {
System.out.println("File does not exist.");
} else {
System.out.println("File exists.");
}
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
面向对象编程(OOP)在JAVA中的应用
类与对象的概念
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("John", 30);
person.greet();
}
}
封装、继承与多态
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println("This animal does not have a specific sound.");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal genericAnimal = new Animal("Generic Animal");
Dog dog = new Dog("Buddy");
genericAnimal.speak();
dog.speak();
}
}
接口与抽象类
interface Animal {
void speak();
}
abstract class Mammal implements Animal {
@Override
public void speak() {
System.out.println("Mammal base sound");
}
}
public class Dog extends Mammal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal genericAnimal = new Mammal();
Dog dog = new Dog();
genericAnimal = dog;
genericAnimal.speak();
}
}
设计模式简介
设计模式是为了解决特定问题的一组良好的实践。在JAVA中应用设计模式可以提高代码的可读性、可维护性和可扩展性。
JAVA集合框架
ArrayList、LinkedList与Vector的区别
import java.util.*;
public class CollectionComparisons {
public static void main(String[] args) {
// ArrayList, dynamic, fast for random access
ArrayList<String> list1 = new ArrayList<>();
list1.add("First");
list1.add("Second");
System.out.println(list1.get(1));
// LinkedList, dynamic, fast for insertion and deletion
LinkedList<String> list2 = new LinkedList<>();
list2.add("First");
list2.add("Second");
System.out.println(list2.getFirst());
// Vector, synchronized, typically used in multi-threaded environments
Vector<String> list3 = new Vector<>();
list3.add("First");
list3.add("Second");
System.out.println(list3.get(1));
}
}
HashMap、HashSet与TreeMap的应用
import java.util.*;
public class CollectionUsage {
public static void main(String[] args) {
// HashMap, key-value pairs, fast access
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("First", 1);
map1.put("Second", 2);
System.out.println(map1.get("First"));
// HashSet, unique elements, no order
HashSet<String> set1 = new HashSet<>();
set1.add("First");
set1.add("Second");
System.out.println(set1.contains("Third"));
// TreeMap, sorted elements, key-based
TreeMap<String, Integer> map2 = new TreeMap<>();
map2.put("Second", 2);
map2.put("First", 1);
System.out.println(map2.firstEntry().getKey());
}
}
JAVA I/O流与NIO技术
文件读写与缓冲流
import java.io.*;
public class FileIO {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
PrintWriter writer = new PrintWriter(new FileWriter("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Reading: " + line);
writer.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字节流与字符流的使用
import java.io.*;
public class StreamUsage {
public static void main(String[] args) {
try (InputStream in = new FileInputStream("example.bin");
OutputStream out = new FileOutputStream("example-copy.bin")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
NIO包介绍与文件通道
import java.nio.*;
import java.nio.channels.*;
public class NIOUsage {
public static void main(String[] args) throws IOException {
FileChannel channel = FileChannel.open(new File("example.txt").toPath(), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
channel.close();
}
}
JAVA多线程编程
线程概念与生命周期
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println("Thread ID: " + Thread.currentThread().getId() + ", Iteration: " + i);
}
});
thread.start();
System.out.println("Thread ID: " + Thread.currentThread().getId() + ", Main thread continues.");
}
}
同步机制与线程安全
public class SynchronizationExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized void decrement() {
count--;
}
public static void main(String[] args) {
SynchronizationExample example = new SynchronizationExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.decrement();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + example.count);
}
}
线程池与并发工具类
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<Integer> future1 = executor.submit(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
});
Future<Integer> future2 = executor.submit(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 200;
});
try {
System.out.println("Sum: " + (future1.get() + future2.get()));
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
}
JAVA网络编程与Socket应用
基础网络概念与Socket API
import java.io.*;
import java.net.*;
public class SocketExample {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client said: " + inputLine);
out.println("Echo: " + inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class SocketClientExample {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
out.println("Hello, Server!");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Server said: " + inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
总结
通过上述示例,我们探索了JAVA语言的多个方面,包括基础语法、面向对象编程、集合框架、I/O流、多线程编程和网络编程。每一部分都通过具体的代码示例进行了展示,旨在帮助你从概念理解过渡到实际应用。学习JAVA编程的旅程既充满了挑战也充满乐趣,希望这篇文章能为你的编程之旅提供坚实的基础。
共同学习,写下你的评论
评论加载中...
作者其他优质文章