The most distinctive features of the Java language summarized by ChatGPT

Original link: https://fugary.com/?p=503

The following are code examples of several of the most distinctive features of the Java language, grouped by feature:

Object-Oriented Programming (OOP)

Java is an object-oriented programming language that supports object-oriented features such as encapsulation, inheritance, and polymorphism.

 // 封装class Car { private String brand; private int price; public void setBrand(String brand) { this.brand = brand; } public void setPrice(int price) { this.price = price; } public void displayInfo() { System.out.println("Brand: " + brand); System.out.println("Price: " + price); } } // 继承class ElectricCar extends Car { private int batteryCapacity; public void setBatteryCapacity(int batteryCapacity) { this.batteryCapacity = batteryCapacity; } public void displayInfo() { super.displayInfo(); System.out.println("Battery Capacity: " + batteryCapacity); } } // 多态public class Main { public static void main(String[] args) { Car car1 = new Car(); car1.setBrand("Toyota"); car1.setPrice(20000); car1.displayInfo(); ElectricCar car2 = new ElectricCar(); car2.setBrand("Tesla"); car2.setPrice(50000); car2.setBatteryCapacity(75); car2.displayInfo(); } }

Exception Handling¶

Java uses the exception handling mechanism to handle abnormal situations that may occur during the running of the program.

 import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) { try { File file = new File("input.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("File not found."); } } }

Multithreading

Java provides support for multi-threaded programming, which can execute multiple threads at the same time to achieve concurrent operations.

 class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + ": " + i); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Main { public static void main(String[] args) { MyThread thread1 = new MyThread("Thread 1"); MyThread thread2 = new MyThread("Thread 2"); thread1.start(); thread2.start(); } }

Generics

Java’s generic mechanism allows type parameters to be specified at compile time, increasing code reusability and type safety.

 import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); for (String name : names) { System.out.println(name); } } }

certainly! Here are more code examples of the most distinctive coding features of the Java language, grouped by feature:

Lambda expression

Java 8 introduced Lambda expressions, which allow anonymous functions to be written concisely and are used in functional programming and collection operations.

 import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(name -> System.out.println(name)); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream() .filter(n -> n % 2 == 0) .mapToInt(n -> n) .sum(); System.out.println("Sum of even numbers: " + sum); } }

Stream API

Java 8 introduces the Stream API, which provides a way to stream-operate collections and supports functional programming and parallel processing.

 import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); long count = names.stream() .filter(name -> name.length() > 4) .count(); System.out.println("Count of names with more than 4 characters: " + count); } }

Optional class

Java 8 introduces the Optional class to handle values ​​that may be null, avoiding null pointer exceptions.

 import java.util.Optional; public class Main { public static void main(String[] args) { Optional<String> name = Optional.ofNullable(getName()); if (name.isPresent()) { System.out.println("Name: " + name.get()); } else { System.out.println("Name not found"); } } public static String getName() { return "Alice"; } }

Annotations

Java supports the use of annotations (Annotations) to add metadata to program elements, and provides some built-in annotations, such as @Override and @Deprecated.

 import java.util.ArrayList; import java.util.List; @SuppressWarnings("unused") public class Main { @Deprecated public static void oldMethod() { System.out.println("This method is deprecated."); } public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); // 使用了@SuppressWarnings注解,忽略编译器的警告names.forEach(System.out::println); // 使用了@Deprecated注解,表示该方法已经过时oldMethod(); } }

certainly! Here are more code examples of the most distinctive coding features of the Java language, grouped by feature:

Reflection

Java’s reflection mechanism allows inspection and manipulation of information such as classes, objects, and methods at runtime.

 import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws Exception { // 获取类的信息Class<?> clazz = Class.forName("com.example.Person"); System.out.println("Class Name: " + clazz.getName()); // 获取构造函数Constructor<?> constructor = clazz.getConstructor(String.class, int.class); Object person = constructor.newInstance("Alice", 25); // 获取字段Field nameField = clazz.getDeclaredField("name"); nameField.setAccessible(true); System.out.println("Name: " + nameField.get(person)); // 调用方法Method helloMethod = clazz.getDeclaredMethod("hello"); helloMethod.invoke(person); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } private void hello() { System.out.println("Hello, " + name); } }

Serialization

Java’s serialization mechanism allows converting an object into a stream of bytes for storage or transmission, and reconstructing the object when needed.

 import java.io.*; public class Main { public static void main(String[] args) throws IOException, ClassNotFoundException { // 对象序列化Person person = new Person("Alice", 25); FileOutputStream fileOut = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); out.close(); fileOut.close(); // 对象反序列化FileInputStream fileIn = new FileInputStream("person.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Person deserializedPerson = (Person) in.readObject(); in.close(); fileIn.close(); System.out.println("Name: " + deserializedPerson.getName()); System.out.println("Age: " + deserializedPerson.getAge()); } } class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }

This article is transferred from: https://fugary.com/?p=503
This site is only for collection, and the copyright belongs to the original author.