首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[教程]揭秘Java编程:50个实操细节,让你的代码飞起来!

发布于 2025-06-19 21:42:27
0
9

1. Java基础语法

1.1 变量声明

int number = 10;
String name = "John Doe";

1.2 数据类型

Java有基本数据类型和引用数据类型。基本数据类型包括int、float、double、char、boolean等。

1.3 运算符

Java支持算术运算符、关系运算符、逻辑运算符等。

2. 面向对象编程

2.1 类和对象

public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public void displayInfo() { System.out.println("Name: " + name + ", Age: " + age); }
}

2.2 继承和多态

public class Employee extends Person { private String jobTitle; public Employee(String name, int age, String jobTitle) { super(name, age); this.jobTitle = jobTitle; } public void displayJobTitle() { System.out.println("Job Title: " + jobTitle); }
}

3. 控制结构

3.1 条件语句

int number = 10;
if (number > 5) { System.out.println("Number is greater than 5");
} else { System.out.println("Number is not greater than 5");
}

3.2 循环语句

for (int i = 0; i < 5; i++) { System.out.println("Iteration " + i);
}

4. 集合框架

4.1 List

List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

4.2 Set

Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");

4.3 Map

Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);

5. 异常处理

5.1 try-catch

try { int result = 10 / 0;
} catch (ArithmeticException e) { System.out.println("Cannot divide by zero");
}

6. Java 8新特性

6.1 Lambda表达式

List list = Arrays.asList("Apple", "Banana", "Cherry");
list.forEach(name -> System.out.println(name));

6.2 Stream API

List list = Arrays.asList("Apple", "Banana", "Cherry");
list.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);

7. Java Web开发

7.1 Servlet

@WebServlet("/hello")
public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello, World!"); }
}

7.2 JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

 Hello, World!

 

Hello, World!

8. Java并发编程

8.1 线程

public 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(); }
}

8.2 同步

public class Counter { private int count = 0; public synchronized void increment() { count++; }
}

9. Java数据库连接

9.1 JDBC

public class Main { public static void main(String[] args) { try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM users"); while (resultSet.next()) { System.out.println(resultSet.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } }
}

10. Java性能优化

10.1 内存泄漏

public class MemoryLeakExample { private static List list = new ArrayList<>(); public static void main(String[] args) { while (true) { list.add(new Object()); } }
}

10.2 懒加载

public class LazyInitializationExample { private static Object instance; public static Object getInstance() { if (instance == null) { instance = new Object(); } return instance; }
}

11. Java设计模式

11.1 单例模式

public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }
}

11.2 工厂模式

public class Factory { public static Object createObject(String type) { if (type.equals("A")) { return new A(); } else if (type.equals("B")) { return new B(); } return null; }
}

12. Java测试框架

12.1 JUnit

import org.junit.Test;
import static org.junit.Assert.*;
public class MyTest { @Test public void testAdd() { assertEquals(5, 2 + 3); }
}

12.2 Mockito

import org.mockito.Mockito;
import static org.mockito.Mockito.*;
public class MockitoExample { @Test public void testMockito() { MyService service = Mockito.mock(MyService.class); when(service.getName()).thenReturn("Mockito"); assertEquals("Mockito", service.getName()); }
}

13. Java构建工具

13.1 Maven

 4.0.0 com.example myapp 1.0-SNAPSHOT

13.2 Gradle

plugins { id 'java'
}
repositories { mavenCentral()
}
dependencies { implementation 'org.example:mylib:1.0'
}

14. Java安全

14.1 加密

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionExample { public static void main(String[] args) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); byte[] keyBytes = secretKey.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encryptedBytes = cipher.doFinal("Hello, World!".getBytes()); System.out.println("Encrypted: " + new String(encryptedBytes)); }
}

14.2 数字签名

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class SignatureExample { public static void main(String[] args) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update("Hello, World!".getBytes()); byte[] signatureBytes = signature.sign(); System.out.println("Signature: " + new String(signatureBytes)); Signature verifySignature = Signature.getInstance("SHA256withRSA"); verifySignature.initVerify(publicKey); verifySignature.update("Hello, World!".getBytes()); boolean isVerified = verifySignature.verify(signatureBytes); System.out.println("Is verified: " + isVerified); }
}

15. Java微服务

15.1 Spring Boot

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); }
}

15.2 Spring Cloud

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); }
}

16. Java人工智能

16.1 TensorFlow

import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class TensorFlowExample { public static void main(String[] args) throws Exception { try (Graph graph = new Graph()) { graph.opBuilder("Const", "const") .setAttr("value", Tensor.create(1.0)) .build(); try (Session session = new Session(graph)) { Tensor tensor = session.runner().fetch("const").run().get(0); System.out.println("Tensor value: " + tensor.getDouble(0)); } } }
}

16.2 Deeplearning4j

import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.lossfunctions.LossFunctions;
public class Deeplearning4jExample { public static void main(String[] args) { MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .seed(12345) .weightInit(WeightInit.XAVIER) .updater(new Adam(0.01)) .list() .layer(0, new DenseLayer.Builder().nIn(10).nOut(50) .activation(Activation.RELU) .build()) .layer(1, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) .activation(Activation.SOFTMAX) .nIn(50).nOut(2).build()) .build(); MultiLayerNetwork model = new MultiLayerNetwork(conf); model.init(); }
}

17. Java大数据

17.1 Apache Hadoop

 4.0.0 com.example hadoop-project 1.0-SNAPSHOT   org.apache.hadoop hadoop-client 3.3.0  

17.2 Apache Spark

 4.0.0 com.example spark-project 1.0-SNAPSHOT   org.apache.spark spark-core_2.11 2.4.7  

18. Java云计算

18.1 Amazon Web Services (AWS)

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
public class AWSExample { public static void main(String[] args) { BasicAWSCredentials awsCredentials = new BasicAWSCredentials("accessKey", "secretKey"); AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .build(); s3Client.listBuckets().forEach(bucket -> System.out.println(bucket.getName())); }
}

18.2 Microsoft Azure

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
public class AzureExample { public static void main(String[] args) { CloudStorageAccount storageAccount = CloudStorageAccount.parse("your_connection_string"); CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); CloudBlobContainer container = blobClient.getContainerReference("your_container_name"); container.listBlobs().forEach(blob -> System.out.println(blob.getName())); }
}

19. Java边缘计算

19.1 Apache Edgent

 4.0.0 com.example edgent-project 1.0-SNAPSHOT   org.apache.edgent edgent-api 0.1.0  

19.2 Microsoft Azure IoT Edge

 4.0.0 com.example azure-iot-edge-project 1.0-SNAPSHOT   com.microsoft.azure.iot iot-device-client 1.6.0  

20. Java物联网

20.1 Arduino

int ledPin = 13;
void setup() { pinMode(ledPin, OUTPUT);
}
void loop() { digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000);
}

20.2 Raspberry Pi

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
public class RaspberryPiExample { public static void main(String[] args) throws InterruptedException { GpioController gpio = GpioFactory.getInstance(); GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, PinState.HIGH); while (true) { pin.setPinState(PinState.HIGH); Thread.sleep(1000); pin.setPinState(PinState.LOW); Thread.sleep(1000); } }
}

21. Java性能测试

21.1 JMeter

”`java import org.apache.jmeter.config.PropertiesConfiguration; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.services.Services; import org.apache.jmeter.testelement.TestPlan;

public class JMeterExample {

public static void main(String[] args) { PropertiesConfiguration config = new PropertiesConfiguration(); config.setProperty("jmeter.save.saveservice.output_format", "xml"); Services.configure(config); FileServer fs = Services.getFileServer(); fs.addDirectory("path/to/your/jmx/file"); TestPlan testPlan = new TestPlan("Test Plan"); testPlan.addTestElement(new ThreadGroup("Thread Group")); testPlan.addTestElement(new LoopController("Loop Controller")); testPlan.add
评论
一个月内的热帖推荐
csdn大佬
Lv.1普通用户

452398

帖子

22

小组

841

积分

赞助商广告