int number = 10;
String name = "John Doe";Java有基本数据类型和引用数据类型。基本数据类型包括int、float、double、char、boolean等。
Java支持算术运算符、关系运算符、逻辑运算符等。
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); }
}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); }
}int number = 10;
if (number > 5) { System.out.println("Number is greater than 5");
} else { System.out.println("Number is not greater than 5");
}for (int i = 0; i < 5; i++) { System.out.println("Iteration " + i);
}List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry"); Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry"); Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3); try { int result = 10 / 0;
} catch (ArithmeticException e) { System.out.println("Cannot divide by zero");
}List list = Arrays.asList("Apple", "Banana", "Cherry");
list.forEach(name -> System.out.println(name)); List list = Arrays.asList("Apple", "Banana", "Cherry");
list.stream().filter(name -> name.startsWith("A")).forEach(System.out::println); @WebServlet("/hello")
public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello, World!"); }
}<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Hello, World!
Hello, World!
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(); }
}public class Counter { private int count = 0; public synchronized void increment() { count++; }
}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(); } }
}public class MemoryLeakExample { private static Listpublic class LazyInitializationExample { private static Object instance; public static Object getInstance() { if (instance == null) { instance = new Object(); } return instance; }
}public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }
}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; }
}import org.junit.Test;
import static org.junit.Assert.*;
public class MyTest { @Test public void testAdd() { assertEquals(5, 2 + 3); }
}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()); }
} 4.0.0 com.example myapp 1.0-SNAPSHOT
plugins { id 'java'
}
repositories { mavenCentral()
}
dependencies { implementation 'org.example:mylib:1.0'
}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)); }
}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); }
}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); }
}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); }
}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)); } } }
}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(); }
} 4.0.0 com.example hadoop-project 1.0-SNAPSHOT org.apache.hadoop hadoop-client 3.3.0
4.0.0 com.example spark-project 1.0-SNAPSHOT org.apache.spark spark-core_2.11 2.4.7
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())); }
}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())); }
} 4.0.0 com.example edgent-project 1.0-SNAPSHOT org.apache.edgent edgent-api 0.1.0
4.0.0 com.example azure-iot-edge-project 1.0-SNAPSHOT com.microsoft.azure.iot iot-device-client 1.6.0
int ledPin = 13;
void setup() { pinMode(ledPin, OUTPUT);
}
void loop() { digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000);
}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); } }
}”`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