preface

JDK 15 has been released. Let’s review the new features of JDK 5-15

This article has been contributed to Github

Github.com/whx123/Java…

Public number: a boy picking up snails

New features in Java 5

1. The generic

Generics are essentially parameterized types that solve the problem of not knowing the type of a specific object.

 List<String> strList=new ArrayList<String>();
Copy the code

2. Enhancement loops (for-each)

The for-each loop simplifies traversal of collections.

String [] STR = {" 中 国 "," 中 国 "," 中 国 "," 中 国 "}; for (String temp:str) { System.out.println(temp); }Copy the code

3. Automatic sealing and unpacking

  • Automatic boxing: The automatic conversion of the base data type to the corresponding wrapper class.
  • Automatic unpacking: The automatic conversion of the packaging class to the corresponding basic data type.

Packaging types are: Integer, Double, Float, Long, Short, Character, and Boolean

Integer i =666; Int a= I; // Automatic unpackingCopy the code

4. The enumeration

The enum keyword can create a new type from a limited set of named values that can be used as regular program components.

enum SeasonEnum {
    SPRING,SUMMER,FALL,WINTER;
}
Copy the code

5. Variable parameters

When we define method parameters we don’t know how many we’re going to define, we can define mutable parameters, which is essentially an array.

Public static void main(String[] args) throws Exception {String[] STR = {" 中 "," 中 "," 中 "}; testVarargs(str); String str1 = ""; String str1 =" "; testVarargs(str1); } // Variable argument String... args private static void testVarargs(String... args) { for (String arg : args) { System.out.println(arg); }}Copy the code

6. Note

Annotations can be thought of as special tags in code that can be read and processed at compile, classload, and runtime.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
Copy the code

7. Static import

By importing a static class, you can use static variables or methods in the class. Let’s take an example

import static java.lang.System.out; Out public class Test {public static void main(String[] args) throws Exception {String str1 = "Pay attention to the public account, the little boy picking up snails "; System.out.println(str1); Println (str1); // Static import, can use out output}}Copy the code

8. Thread Concurrency Library (JUC)

The java.util.Concurrent package provides the following classes and interfaces:

  • Thread pools: ExecutorService interface
  • Thread repulsion: Lock class
  • Thread communication: Condition interface
  • Synchronous queue: ArrayBlockingQueue class
  • Synchronous collection: ConcurrentHashMap class

New features in Java 6

1.Desktop class and SystemTray class

JDK 6 adds two new classes to the java.awt package: the Desktop class and the SystemTray class

  • Desktop: used to open the system default browser to browse the specified URL, open the system default mail client to send emails, etc
  • SystemTray class: used to create a tray program in the SystemTray area, which on Microsoft Windows is called the “taskbar” status area.
Desktop = desktop.getDesktop (); desktop.browse(URI.create("https://www.baidu.com"));Copy the code

2. Use JAXB2 to map objects to XML

JAXB, or Java Architecture for XML Binding, allows mapping between objects and XML, often annotated as follows:

  • XmlRootElement: The annotation is on top of the class, corresponding to the trailing element of the XML, using the name attribute to define the name of the root node.
  • XmlElement: Specifies the node to which a field or get/set method maps to XML, using the name attribute to define the name of the root node.
  • @XMlattribute: Maps the attributes of a JavaBean object to those of XML, using the name attribute to specify aliases for the generated XML attributes.
  • XmlAccessorType: Define mapping which types in this class need to be mapped to XML.
  • XmlSchema: Map packages to XML namespaces

Let’s take an example

public class JAXB2XmlTest {

    public static void main(String[] args) throws JAXBException, IOException {
        
        List<Singer> list = new ArrayList<>();
        list.add(new Singer("jay", 8));
        list.add(new Singer("eason", 10));

        SingerList singerList = new SingerList();
        singerList.setSingers(list);

        String str = JAXB2XmlTest.beanToXml(singerList, SingerList.class);
        String path = "C:\\jay.txt";
        BufferedWriter bfw = new BufferedWriter(new FileWriter(new File(path)));
        bfw.write(str);
        bfw.close();

    }

    private static String beanToXml(Object obj, Class<?> load) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(load);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj,writer);
        return writer.toString();
    }
}
public class Singer {

    private String name;
    private int age;
    public Singer(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @XmlAttribute(name="name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlAttribute(name="age")
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
@XmlRootElement(name="list")
public class SingerList {

    private List<Singer> singers;
    
    @XmlElement(name="singer")
    public List<Singer> getSingers() {
        return singers;
    }

    public void setSingers(List<Singer> singers) {
        this.singers = singers;
    }
}
Copy the code

Operation effect:

<? The XML version = "1.0" encoding = "GBK" standalone = "yes"? > <list> <singer age="8" name="jay"/> <singer age="10" name="eason"/> </list>Copy the code

3. Lightweight Http Server API

JDK 6 provides a simple Http Server API to build an embedded Http Server that supports both Http and Https protocols. HttpServer calls the callback method of the HttpHandler implementation class to handle the client request. The user only needs to implement the HttpHandler interface.

Public class MyHttpServer {/** * @param args * @throws IOException */ public static void */ Main (String[] args) throws IOException {// Create an HttpServer server. HttpServer HttpServer = httpServer.create (new InetSocketAddress(8080), 10); // Pass /jay to the MyHandler handler for processing httpServer.createconText ("/", new MyHandler()); httpServer.start(); } } public class MyHandler implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { / / request header Headers Headers = httpExchange. GetRequestHeaders (); Set<Map.Entry<String, List<String>>> entries = headers.entrySet(); StringBuffer response = new StringBuffer(); for (Map.Entry<String, List<String>> entry : entries){ response.append(entry.toString() + "\n"); } / / set response headers attribute and the length of the response information httpExchange. SendResponseHeaders (200, response. Length ()); / / get the output stream OutputStream OS. = httpExchange getResponseBody (); os.write(response.toString().getBytes()); os.close(); }}Copy the code

4. Plug-in annotation processing API

JDK 6 provides an plug-in annotation handling API that lets you define annotations at compile time rather than at run time, allowing you to modify bytecode at compile time. The Lombok framework uses this feature to simplify code development by automatically generating constructors, getters/setters, equals, HashCode, toString, and other methods for properties at compile time via annotations.

5. STAX

STAX is an API for processing XML documents in JDK6.

public class STAXTest { public static void main(String[] args) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream("C:\\jay.xml")); XMLEvent event = null; StringBuffer stringBuffer = new StringBuffer(); while (xmlEventReader.hasNext()) { event = xmlEventReader.nextEvent(); stringBuffer.append(event.toString()); } system.out.println (" XML document parsing result: "); System.out.println(stringBuffer); }}Copy the code

Running results:

XML document parsing result: <? The XML version = "1.0" encoding = 'GBK' standalone = 'yes'? ><list> <singer name='jay' age='8'></singer> <singer name='eason' age='10'></singer> </list>ENDDOCUMENTCopy the code

6. Common Annotations

Common Annotations Were originally part of the Java EE 5.0(JSR 244) specification, but SUN has now put some of them into Java SE 6.0. With the Annotation metadata feature added to Java SE 5.0, many Java technologies use the Annotation section instead of XML files to configure run parameters.

Annotations for Common Annotations 1.0:

  • @generated: Source code used for annotation generation
  • @resource: used to annotate dependent resources, from which the container can inject external Resource dependencies, including field-based injection and setter-based injection.
  • @Resources: Annotate multiple external dependencies at the same time. The container will inject all these external dependencies
  • PostConstruct: Annotate methods that are run after the container has injected all its dependencies to perform post-dependency injection initialization. Only one method can be annotated as PostConstruct.
  • PreDestroy: The callback method to be executed before the object instance is deleted from the container should be labeled PreDestroy

7. Compiler API

The Javac Compiler can compile.java source files into.class files, and the Compiler API(JSR 199), a new feature in JDK 6, can dynamically compile Java source files.

public class CompilerApiTest { public static void main(String[] args) throws Exception { JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null,null,null); Iterable<? extends JavaFileObject> javaFileObjects = standardJavaFileManager.getJavaFileObjects("C:\\Singer.java"); javaCompiler.getTask(null, standardJavaFileManager, null, null, null, javaFileObjects).call(); standardJavaFileManager.close(); }}Copy the code

Result: A singer.class file is generated in the C directory

8. Support for scripting languages (e.g. Ruby, Groovy, javascript)

JDK6 adds support for scripting languages (JSR 223), which are compiled to bytecode so that scripting languages can take advantage of many of the advantages of the Java platform, including portability, security, and more. The JDK6 implementation includes a scripting language engine based on Mozilla Rhino, which supports javascript, although the JDK also supports other languages such as Ruby

public class JavaScriptTest { public static void main(String[] args) throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); String script; try { script = "print('Hello')"; engine.eval(script); }catch (Exception e) {e.printStackTrace(); } } } //output HelloCopy the code

New features in Java 7

1. The switch supports String.

String singer = "jay"; Switch (singer) {case "jay" : system.out.println (" jay"); break; Case "eason" : system.out.println (" eason"); break ; Default: system.out.println (" other "); break ; }Copy the code

2. Try-with-resources: Resources are automatically closed

Before JDK 7:

BufferedReader br = new BufferedReader(new FileReader("d:.txt")); try { return br.readLine(); } finally { br.close(); }Copy the code

After JDK 7:

/* * Declare the objects in the try parentheses to be resources, */ try (BufferedReader br = new BufferedReader(new FileReader("d:.txt")) {return br.readline (); }Copy the code

3. Integer types such as byte, short, int, long can be represented in binary

Int a = 0b010; int b = 0B010;Copy the code

4. Numeric constants support underscores

int a = 11_11; // The value of a is 1111. The underscore does not affect the actual value to improve readabilityCopy the code

5. Generic instantiation type automatic inference, i.e. “<>”

Before JDK 7:

Map<String, List<String>> map = new HashMap<String, List<String>>();
Copy the code

After JDK 7:

Map<String, List<String> Map = new HashMap<>();Copy the code

6. A catch catch multiple exception types, with the (|)

JDK 7 before

try{
   //do something
} catch (FirstException e) {
     logger.error(e);
} catch (SecondException e) {
     logger.error(ex);
}
Copy the code

After the JDk 7

try{
   //do something
} catch (FirstException | SecondException e) {
     logger.error(e);
}
Copy the code

Enhanced file system

Java7 provides a new NIO2.0 API to facilitate file management coding. For example, common types such as Path, Paths, Files, and WatchService can be used in the java.nio.file package.

Path Path = path. get("C:\ jay\ jilis.txt "); Byte [] bytes= files.readallBytes (Path); byte[] bytes= files.readallBytes (Path); System.out.println(path.getfilename ())); System.out.println(path.toAbsolutePath()); System.out.println(new String(bytes, "utF-8 "));Copy the code

8. Fork/join framework

Java7 provides a framework for parallel execution of tasks, which is a framework for dividing large tasks into several smaller tasks, and finally summarizing the results of each small task to obtain the results of a large task.

Fork/join calculate 1-1000 accumulative values:

public class ForkJoinPoolTest { private static final Integer DURATION_VALUE = 100; Static Class ForkJoinSubTask extends RecursiveTask<Integer>{private Integer startValue; Private Integer endValue; private ForkJoinSubTask(Integer startValue , Integer endValue) { this.startValue = startValue; this.endValue = endValue; } @override protected Integer compute() {if(endvalue-startvalue < DURATION_VALUE) {if(endvalue-startvalue < DURATION_VALUE) { System.out.println(" startValue = "+ startValue + "; EndValue = "+ endValue"; Integer totalValue = 0; for (int index = this.startValue; index <= this.endValue; index++) { totalValue += index; } return totalValue; } else {ForkJoinSubTask subTask1 = new ForkJoinSubTask(startValue, (startValue + endValue) / 2); subTask1.fork(); ForkJoinSubTask subTask2 = new ForkJoinSubTask((startValue + endValue) / 2 + 1 , endValue); subTask2.fork(); return subTask1.join() + subTask2.join(); } } } public static void main(String[] args) throws ExecutionException, InterruptedException {// Fork/Join the framework's thread pool ForkJoinPool = new ForkJoinPool(); ForkJoinTask<Integer> taskFuture = pool.submit(new ForkJoinSubTask(1,1000)); Integer result = taskFuture.get(); System.out.println(" result :" + result); }}Copy the code

Running results:

. Perform subtask calculation: start value = 189; End value = 250 Perform subtask calculation: Start value = 251; End value = 313 Perform subtask calculation: Start value = 314; End value = 375 Perform subtask calculation: Start value = 376; End value = 438 Perform subtask calculation: Start value = 439; End value = 500 Perform subtask calculation: Start value = 501; End value = 563 Perform subtask calculation: Start value = 564; End value = 625 Perform subtask calculation: Start value = 626; End value = 688 Perform subtask calculation: Start value = 689; End value = 750 Perform subtask calculation: Start value = 751; End value = 813 Perform subtask calculation: Start value = 814; End value = 875 Perform subtask calculation: Start value = 876; End value = 938 Perform subtask calculation: Start value = 939; End value = 1000 Cumulative result :500500Copy the code

New features in Java 8

1. The lambada expression

Lambda allows functions to be passed as arguments to a method

Syntax format:

(parameters) -> expression 或 (parameters) ->{ statements; }
Copy the code

Code examples:

Arrays.asList("jay", "Eason", "SHE").forEach(
       ( String singer ) -> System.out.print( singer + ",") );
Copy the code

2. functional interfaces

Lambda designers designed functional interfaces to make existing functions compatible with Lambda expressions.

  • A functional interface is an interface with a single function that can be implicitly converted to a lambada expression.
  • Java 8 provides the annotation @functionalinterface to declare a FunctionalInterface.
  • Java. Lang. Runnable and Java. Util. Concurrent. Callable are examples of functional interface ~
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
Copy the code

3. Method references

Method references provide a very useful syntax for directly referencing methods or constructors of existing Java classes or objects (instances). It is used in conjunction with Lambda expressions to reduce redundant code and make code more concise.

Consumer<String> Consumer = x -> system.out.println (x); Consumer<String> Consumer = x -> system.out.println (x); consumer.accept("jay"); Consumer = system.out ::println; consumer = system.out ::println; Consumer. Accept (" Concern about the little boy picking up snail ");Copy the code

4. Default method

The default method is a method that has an implementation in the interface. It allows new methods to be added to the interface, but does not force classes that implement the interface to implement the new method.

Public interface ISingerService {// default void sing(){system.out.println (" sing "); } void writeSong(); Public class JaySingerServiceImpl implements ISingerService {// Implements ISingerService (); @override public void writeSong() {system.out.println (" writeSong "); }}Copy the code

5.Stream API

The Stream API, which supports functional manipulation of streams of elements, is integrated into the Collections API and allows bulk manipulation of Collections. Commonly used API:

  • The filter screen
  • The map flow mapping
  • Reduce groups elements in the flow
  • Collect Return collection
  • Sorted order
  • FlatMap flow conversion
  • Limit Returns the specified number of streams
  • Distinct Removes duplicate elements
public class Singer { private String name; private Integer songNum; private Integer age; . } List<Singer> singerList = new ArrayList<Singer>(); singerList.add(new Singer("jay", 11, 36)); singerList.add(new Singer("eason", 8, 31)); singerList.add(new Singer("JJ", 6, 29)); List<String> singerNameList = singerlist.stream (). Filter (singer -> singer.getage () > 30 .sorted(Comparator.comparing(Singer::getSongNum)) // Sort by the number of songs. Map (Singer::getName) // Extract the Singer name .collect(Collectors.toList()); // Convert to ListCopy the code

6. Optional

Java 8 introduces the Optional class to resolve NullPointerExceptions. Optional instead of the if… Else solves the null pointer problem, making the code more concise.

if… The else found empty

Singer singer = getSingerById("666"); if (singer ! = null) { String name = singer.getName(); System.out.println(name); }Copy the code

Optional found empty

Optional<Singer> singer = Optional.ofNullable(getSingerById("666"));
singer.ifPresent(s -> System.out.println(s.getName()));
Copy the code

7. Date Time API

Date API handling prior to JDK 8 had issues such as non-thread-safe and cumbersome time zone handling. Java 8 provides a new date API under the java.time package that simplifies date handling

LocalDate today = LocalDate.now(); int year = today.getYear(); System.out.println(" year is "+ year); System.out.println(" this is a leap year :" + today.isleapYear ()); LocalDateTime todayTime = LocalDateTime.now(); System.out.println(" current time "+ todayTime); Println (" daybreak :" + ZonedDateTime. Of (todayTime, zoneid. of("America/Los_Angeles"))); // Time zone specified system.out. println(" Daybreak :" + ZonedDateTime. LocalDate specailDate = LocalDate.of(2020, 6, 20); LocalDate expectDate = specailDate.plus(100, ChronoUnit.DAYS); System.out.println(" special day "+ specailDate); System.out.println(" expectDate 100 days "+ expectDate);Copy the code

8. Repeat the notes

Repeated annotations, in which an annotation can be used more than once on a class, property, or method; Define Repeatable annotations with @repeatable

@Repeatable(ScheduleTimes.class)
public @interface ScheduleTime {
    String value();
}

public @interface ScheduleTimes {
    ScheduleTime[] value();
}

public class ScheduleTimeTask {
    @ScheduleTime("10")
    @ScheduleTime("12")
    public void doSomething() { }
}
Copy the code

9. Base64

Java 8 adds Base64 encoding support to the official library

String STR = "public id: a boy with a field snail "; String encoded = Base64.getEncoder().encodeToString(str.getBytes( StandardCharsets.UTF_8)); String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);Copy the code

10. New features for the JVM

Metaspace is used instead of PermGen space, and JVM parameters are set to size using -xx :MetaSpaceSize and -xx :MaxMetaspaceSize.

New features in Java 9

1. Java module system

What is modularity?

A large system, such as a mall website, it will contain many modules, such as: order module, user information module, commodity information module, advertising space module and so on. Modules call each other. If each module runs alone and drives all the other modules, performance is very inefficient. However, if a module is running, only the modules it depends on are started, greatly improving performance. This is the idea behind modularity in JDK 9.

What is JDK 9 modularity?

The Java platform module system, or Project Jigsaw, brings modular development practices to the Java platform. With the introduction of a module system, the JDK was reorganized into 94 modules. Java applications can use the new JLink tool to create custom runtime images that contain only the JDK modules they depend on. This can greatly reduce the size of the Java runtime environment.

Key features of the Java 9 module:

  • The root of its artifact contains a module-info.class document describing the module.
  • The format of the artifacts can be a traditional JAR file or a JMOD file added to Java 9.
  • This file is compiled from the source file module-info.java in the root directory.
  • This module declaration file can describe different characteristics of a module.

In the module-info.java file, we can declare a module with the new keyword module, as shown below. Here is the basic module declaration for a module com.mycompany.myModule

Module com.jay-sample {// keywords module to declare a module exports com.jay-sample; // With exports, you can declare packages exported by a module to other modules. requires com.jay.common; // Requires requires to declare a module's dependencies on other modules. }Copy the code

2. Immutable set factory method

To create immutable collections, JDK9 prefixes:

List<String> stringList = new ArrayList<>(); Add (" public id :"); Stringlist. add(" The little boy who Picked up snails "); List<String> unmodifiableList = Collections.unmodifiableList(stringList);Copy the code

JDK 9 provides factory methods such as list.of (), set.of (), map.of (), and map.ofentries () to create immutable collections:

List<String> unmodifiableList = List.Copy the code

3. The interface supports private methods

JDK 8 supports implementing default and static methods in interfaces, but cannot create private methods in interfaces. To avoid code redundancy and improve readability, JDK 9 supports private methods in interfaces.

Public interface IPrivateInterfaceTest {//JDK 7 earlier String a = "jay"; void method7(); //JDK 8 default void methodDefault8(){system.out.println ("JDK 8 new feature default method "); } static void static8 () {system.out.println ("JDk 8 new static method "); Private void method9(){}}Copy the code

4. Diamond operator upgrade

  • The diamond operator was introduced in Java 7 to make code more readable, but it can’t be used for anonymous inner classes.
  • In Java 9, it can be used with anonymous inner classes to improve code readability.
//JDK 56 Map<String,String> map56 = new HashMap<String,String>(); //JDk 7,8 Map<String, String> map78 = new HashMap<>(); Map<String, String> map9 = new HashMap<>(){};Copy the code

5. Optional improvements

In Java 9, java.util.Optional added a number of useful new methods, such as:

  • stream()
  • ifPresentOrElse()
  • or()

The ifPresentOrElse method is improved by adding else and accepting two arguments, Consumer and Runnable.

import java.util.Optional; public class OptionalTest { public static void main(String[] args) { Optional<Integer> optional = Optional.of(1); optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() -> System.out.println("Not Present.")); optional = Optional.empty(); optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() -> System.out.println("Not Present.")); }}Copy the code

6. Jar packages compatible with multiple versions

Many companies are using older JDK versions — JDK6, JDk5, and even JDk4 — not because they don’t want to upgrade, but because they are concerned about compatibility. A new feature in JDK 9, multi-version compatible Jar packages, solves this problem. For example, let’s say you’ve been using Mi 8 for a long time, and you’re used to the process, and then suddenly mi 9 comes out. Even though mi 9 has a lot of interesting new features, some people won’t buy Mi 9 because they’re already used to the process of Mi 8. The same reason why many companies don’t upgrade the JDK is right here. However, JDK 9 is a powerful tool that allows you to upgrade your version to JDK 9, but still inherit new functionality from the old runtime

7. JShell tools

The jShell tool is equivalent to the CMD tool, and then you can run Java methods, Java statements, and so on directly on it just as you would on the CMD tool

Jshell > system.out.println; A boy picking up snailsCopy the code

8. Try-with-resources improvements

The try-with-Resources exception handling mechanism is updated in JDK 9

//JDK 7,8 try (BufferedReader br = new BufferedReader(new FileReader("d:.txt")) {br.readline (); }catch(IOException e){log.error("IO exception,e :{}",e); } //JDk 9 BufferedReader br = new BufferedReader(new FileReader("d:.txt") try(br){br.readline (); }catch(IOException e){log.error("IO exception,e :{}",e); }Copy the code

9. Stream API improvements

JDK 9 enriches the Stream handling operation by introducing the following methods to the Stream API:

  • TakeWhile ()
  • DropWhile ()
  • iterate
  • ofNullable

takeWhile

Using an assertion (Predicate interface) as an argument, returns a subset of the given Stream until the assertion statement returns false for the first time

Default Stream<T> takeWhile(Predicate<? Super T> predicate) // code examples stream.of (1,2,3).takewhile (s-> x<2).foreach (system.out ::println); / / output 1Copy the code

dropWhile

In contrast to takeWhile (), an assertion (Predicate interface) is used as an argument until the Predicate statement returns true for the first time, returning a subset of the given Stream

// Syntax default Stream<T> dropWhile(Predicate<? Super T> predicate) // code examples stream.of (1,2,3).dropwhile (s-> x<2).foreach (system.out ::println); // Output 2, 3Copy the code

iterate

The iterate() method can return a stream of elements that begins with seed (the first argument), matches Predicate (the second argument) until it returns false, and uses the third argument to generate the next element.

// Syntax static <T> Stream<T> iterate(T seed, Predicate<? Super T> hasNext, UnaryOperator<T> next) intstream. iterate(2, x -> x < 10, x -> x*x).forEach(System.out::println); // Output 2 4Copy the code

ofNullable

If the element is specified as non-null, an element is obtained and a single element Stream is generated, and an empty Stream is returned if the element is null.

Static <T> Stream<T> oflable (T T) Stream<Integer> s1= stream.oflable (100); ForEach (system. out::println) Stream<Integer> s2 = stream. ofNullable(null); S2. forEach(system. out::println) // Output 100Copy the code

Other 10.

  • HTTP2 client (supports WebSocket and HTTP2 streams and server push)
  • Process API (Controlling and managing operating system processes)
  • String underlying storage structure changed (char[] replaced by byte[])
  • Adding restrictions to identifiers (String _ =”hello” cannot be used)
  • Reactive Flow API (support for reactive programming in Java 9)

New features in Java 10

Local variable type inference

JDK 10 added local-variable Type Inference, which made it possible for Java to automatically infer data types like VAR in Js. In Java, var is a reserved type name, not a keyword.

The JDK 10 before

List<String> list = new ArrayList<String>();
Stream<Integer> stream = Stream.of(1, 2, 3);
Copy the code

10 after the JDK

var list = new ArrayList<String>(); // ArrayList<String>
var stream =  Stream.of(1, 2, 3);
Copy the code

The use of var variable type inference is also limited to the following scenarios:

  • A local variable with an initializer
  • Index variables in enhanced for loops
  • A local variable declared in a traditional for loop

Instead of being used for

  • Infer method parameter types
  • Constructor parameter type inference
  • Infer the method return type
  • Field type inference
  • Capture expression

2. Improvement of immutable sets

In JDK 10, List, Set, Map provides a new static method copyOf(Collection<? Extends E> coll), which returns an immutable copy of the Collection.

The JDK source code:

static <E> List<E> copyOf(Collection<? extends E> coll) {
    return ImmutableCollections.listCopy(coll);
}
Copy the code

Example:

var oldList = new ArrayList<String>(); Oldlist.add (" welcome to follow the public account: "); Oldlist. add(" The little boy who picked up snails "); var copyList = List.copyOf(oldList); Oldlist.add (" see, reprint, like "); CopyList. Add (double click on the "666"); / / UnsupportedOperationException anomaliesCopy the code

3. Parallel full garbage collector G1

JDK 9 introduced G1 as the default garbage collector, which performs GC using a single-threaded mark-sweep-compact algorithm. To minimize the impact of application pauses caused by Full GC, Java 10 will introduce multithreaded parallel GC for G1, using the same number of parallel worker threads as young and mixed GC, thereby reducing Full GC for better performance and greater throughput.

4. Thread local handshake

Thread control introduced in Java 10, the concept of JVM safety points, will allow thread callbacks to be implemented without running global JVM safety points, either by the thread itself or by the JVM thread, while keeping the thread blocked, which will conveniently make it possible to stop a single thread with or without stopping a thread.

5. Optional added orElseThrow() method

Classes Optional, OptionalDouble, and others add a new method, orElseThrow(), that throws an exception if there is no value

6. Other new features

  • An experimental Java-based JIT compiler
  • Class data sharing
  • Unicode language tag extension
  • Root certificate
  • Time-based version control model

New features in Java 11

1. String operations

The String class is the most commonly used class in Java, and JDK 11 has added a number of handy String handling methods

  • IsBlank () found empty.
  • Strip () removes leading and trailing Spaces
  • StripLeading () works on the string header
  • StripTrailing () removes trailing space from the string
  • Lines () splits the string stream.
  • Repeat () copies the string
// check if the string isBlank "".isblank (); // true // Remove the first and last Spaces "jay ".strip(); // "jay" // Then work "jay". StripLeading (); // "jay "works "jay ". StripLeading (); // "a\nb\nc".lines().count(); // duplicate the string "jay". Repeat (3); // "jayjayjay"Copy the code

2. Local variable syntax for Lambda arguments

Local variable type inference is a new feature introduced in Java 10, but cannot be used in Lambda expressions. Java 11 innovates again by allowing developers to use var for parameter declarations in Lambda expressions.

var map = new HashMap<String, Object>(); Map. Put (" public account ", "a little boy picking up snails "); map.forEach((var k, var v) -> { System.out.println(k + ": " + v); });Copy the code

3. Standardize HTTP clients

Java 9 introduces the Http Client API,Java 10 updates it, and Java 11 standardizes it. After these releases, the Http Client was almost completely rewritten to support Http /1.1 and Http /2, as well as webSockets.

HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://github.com/whx123/JavaHome")) .GET() .build(); / / synchronize HttpResponse < String > response = client. Send (request, HttpResponse. BodyHandlers. OfString ()); System.out.println(response.body()); / / the asynchronous client. SendAsync (request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println);Copy the code

4. Compile and run the source code with a single command

Java 11 enhances the Java launcher to run Java source code from a single file.

  • Prior to Java 11, to run a Java source code you had to compile it, then run it
// Compile javac jay-java // run Java JayCopy the code
  • After Java 11, all you need is a Java command
java Jay.java
Copy the code

5. ZGC: Scalable low-latency garbage collector

ZGC stands for Z Garbage Collector. It is a scalable, low-latency garbage collector. The ZGC is designed to meet the following objectives:

  • The GC pause time does not exceed 10ms
  • It can handle both small heaps of several hundred MEgabytes and large heaps of several terabytes
  • – Application throughput will not drop by more than 15% (compared to G1 recycle)
  • It is easy to introduce new GC features and make use of COLord on this basis
  • Needle and Load barriers optimization lay the foundation
  • Currently, only Linux/ X 64-bit platforms are supported

6. Other features

  • Add the Epsilon garbage collector.
  • Supports TLS 1.3
  • Flight recorder analysis tool
  • Dynamic class file constants
  • Low-overhead Heap Profiling

New features in Java 12

1. Switch expression extension (preview function)

In traditional switch statements, it is easy to miss break and make mistakes, and the writing method is not simple and elegant.

Java before 12

switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}

Copy the code

Since JDk 12, Switch expressions have been enhanced to accept statements and expressions.

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}
Copy the code

2. Compact data format

JDK 12 added NumberFormat to format complex numbers

NumberFormat numberFormat = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT); System.out.println(numberFormat.format(100000)); / / the output 100000Copy the code

3. The character string supports transform and indent

  • Transform string conversion that can be used in conjunction with the functional interface Function
List<String> list1 = list. of("jay", "Little boy "); List<String> list2 = new ArrayList<>(); list1.forEach(element -> list2.add(element.transform(String::strip) .transform((e) -> "Hello," + e)) ); list2.forEach(System.out::println); // Output Hello,jay Hello, little boy picking up snailsCopy the code
  • Indent to add space and remove space at the beginning of each line
String result = "Java\n Python\nC".indent(3); System.out.println(result); // Outputs Java Python CCopy the code

4. Files.mismatch(Path, Path)

Java 12 has a new mismatch method, which returns the first mismatch or -1L if there is no mismatch.

public static long mismatch(Path path, Path path2) throws IOException;
Copy the code

Code examples:

Path file1 = Paths.get("c:\\jay.txt"); Path file2 = path. get("c: \\ little boy. TXT "); try { long fileMismatch = Files.mismatch(file1, file2); System.out.println(fileMismatch); } catch (IOException e) { e.printStackTrace(); }Copy the code

5. Teeing Collector

The Teeing Collector is a new Collector utility introduced in the Streams API to merge the results of two Collectors. the API format is as follows:

public static <T, R1, R2, R> Collector<T, ? , R> teeing(Collector<? super T, ? , R1> downstream1, Collector<? super T, ? , R2> downstream2, BiFunction<? super R1, ? super R2, R> merger)Copy the code

Look directly at the code example, below is the student average and total score example

List<Student> studentList= array. asList(New Student(" Jay ", 90), new Student(" Jay ", 100), new Student(" Face ", 80)); String teeingResult=studentList.stream().collect( Collectors.teeing( Collectors.averagingInt(Student::getScore), Collectors.summingInt(Student::getScore), (s1,s2)-> s1+ ":"+ s2 ) ); System.out.println(teeingResult); / / 90:270Copy the code

6. Other features

  • Unicode 11 support (684 new characters, 11 new blocks, 7 new scripts)
  • JVM constants API (mainly in the new Java. Lang. Invoke. Constant package defines a series of reference types based on the value of the symbol, can describe each loadable constants.)
  • Shenandoah GC (Low pause time garbage collector)
  • G1 collector upgrade (abortive mixed collection collection, timely return of unused allocated memory)
  • Default CDS file
  • JMH benchmark

New features in Java 13

Switch expression extension (introduce yield keyword)

Traditional Switch:

private static String getText(int number) {
    String result = "";
    switch (number) {
        case 1, 2:
        result = "one or two";
        break;
        case 3:
        result = "three";
        break;
        case 4, 5, 6:
        result = "four or five or six";
        break;
        default:
        result = "unknown";
        break;
Copy the code

After Java 13, value break statements are no longer compiled; instead, yield is used to return values

private static String getText(int number) {
    return switch (number) {
        case 1, 2:
            yield "one or two";
        case 3:
            yield "three";
        case 4, 5, 6:
            yield "four or five or six";
        default:
            yield "unknown";
    };
}
Copy the code

2. Upgrade the text block

Prior to Java 13, strings could not be used more than once, and had to be escaped by line breaks or line breaks, etc., which were just too cumbersome and difficult to maintain.

A String of HTML = "< HTML > \ n" + "< body > \ n" + "< p > Hello, pick up tianluo boy < / p > \ n" + "< / body > \ n" + "< / HTML > \ n";Copy the code

After Java 13, it’s much cleaner

A String of HTML = "" "< HTML > < body > < p > Hello, pick up tianluo boy < / p > < / body > < / HTML > "" ";Copy the code

3. SocketAPI refactoring

  • The traditional Java Socket API (java.net.ServerSocket and java.net.Socket) relies on the internal implementation of SocketImpl
  • Prior to Java 13, SocketImpl was implemented by using PlainSocketImpl as a concrete implementation.
  • A new underlying implementation in Java 13, introducing an implementation of NioSocketImpl to replace the PlainSocketImpl implementation of SocketImpl, which shares the same internal infrastructure as the NIO (new I/O) implementation, And integrate with existing buffer caching mechanisms.

A simple Socket example:

import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SocketAPITest { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(8080)){ boolean runFlag = true; while(runFlag){ Socket clientSocket = serverSocket.accept(); }} catch (IOException e) {e.printStackTrace(); }}}Copy the code

Run the above example to see if the following keyword output is ~

[class,load] sun.nio.ch.NioSocketImpl
Copy the code

4. FileSystems. NewFileSystem new methods

The following three new methods have been added to the FileSystems class to make it easier to use file system providers that treat file contents as FileSystems:

  • 1, newFileSystem (Path)
  • NewFileSystem (Path, Map

    )
    ,?>
  • NewFileSystem (Path, Map

    , ClassLoader)
    ,?>

5. Enhance ZGC to free unused memory

  • The most notable garbage collection feature introduced in Java 11 is ZGC, a scalable, low-latency garbage collector. In practice, however, it cannot actively release unused memory to the operating system.
  • Improvements to ZGC in Java 13 include freeing unused memory for the operating system, supporting a maximum heap size of 16TB, and the JVM parameter -xx :SoftMaxHeapSize to soft-limit the heap size

6. Other features

  • Dynamic CDS archiving, which extends the data-like sharing feature introduced in Java 10, makes it easier to use CDS archiving.
  • New string class methods for text blocks, such as formatted(Object… Args), stripIndent(), etc.

New features in Java 14

1. Instanceof pattern matching

Instanceof traditional use:

if (person instanceof Singer) {
    Singer singer = (Singer) person;
    singer.sing();
} else if (person instanceof Writer) {
    Writer writer = (Writer) person;
    writer.write();
}
Copy the code

Java 14 improves pattern matching with Instanceof

if (person instanceof Singer singer) {
    singer.sing();
} else if (person instanceof Writer writer) {
   writer.write();
}
Copy the code

2 Record type (preview function)

Java 14 introduced the Record type as a preview feature, somewhat similar to Lombok’s @data annotation. Here’s an example:

public record Person(String name, int age) { public static String address; public String getName() { return name; }}Copy the code

Decompilation result:

public final class Person extends java.lang.Record { private final java.lang.String name; private final java.lang.String age; public Person(java.lang.String name, java.lang.String age) { /* compiled code */ } public java.lang.String getName() { /* compiled code */ } public java.lang.String toString() { /* compiled code */ } public final int hashCode() { /* compiled code */ } public final boolean equals(java.lang.Object o) { /* compiled code */ } public java.lang.String name() { /* compiled code */ } public  java.lang.String age() { /* compiled code */ } }Copy the code

As you can see, when a class is declared with Record, the class automatically has the following characteristics:

  • A constructor
  • HashCode () method
  • Euqals () method
  • The toString () method
  • Class objects are decorated with the final keyword and cannot be inherited.

3. Switch expressions – normalization

The Switch expression was previewed in Java 12 and Java 13 before being standardized into a stable version in Java 14.

  • Java 12 introduces Lambda syntax for switch expressions
  • Java 13 uses yield instead of the break keyword to return the return value of an expression.
String result = switch (day) { case "M", "W", "F" -> "MWF"; case "T", "TH", "S" -> "TTS"; default -> { if (day.isEmpty()) { yield "Please insert a valid day."; } else { yield "Looks like a Sunday."; }}}; System.out.println(result);Copy the code

4. Improve NullPointerExceptions

Before Java 14:

String name = song. GetSinger (.) getSingerName () / / stack information Exception in the thread "is the main" Java. Lang. NullPointerException ats NullPointerExample.main(NullPointerTest.java:6)Copy the code

Java 14, by introducing the JVM parameter – XX: + ShowCodeDetailsInExceptionMessages, can in a null pointer exception calls for more detailed information.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Singer.getSingerName()" 
because the return value of "rainRow.getSinger()" is null
    at NullPointerExample.main(NullPointerTest.java:6)
Copy the code

5. Other features

  • The G1’s NUMA recognizes memory allocation
  • Delete the CMS garbage collector
  • GC supports MacOS and Windows

New features in Java 15

1.EdDSA digital signature algorithm

  • Edwards-curve digital signature algorithm (EdDSA) is used to implement encrypted signature.
  • Compared with other signature schemes, EdDSA has higher security and performance.
  • It is supported by many other cryptographic libraries such as OpenSSL and BoringSSL.

2.Sealed Classes, Preview

Closed classes, which can be closed classes or closed interfaces, prevent other classes or interfaces from extending or implementing them.

public abstract sealed class Singer
    permits Jay, Eason{
    ...
}
Copy the code

The Singer class is sealed and can only be inherited by two specified subclasses (Jay, Eason).

3. Hidden Classes

  • Hidden classes are inherently designed for frames.
  • Hidden classes can only be accessed through reflection, not directly by bytecode of other classes.

4. Remove the Nashorn JavaScript Engine

  • Nashorn was so difficult to maintain that removing the Nashorn JavaScript engine became a necessity
  • It was already marked deprecated in JDK 11.

5.Reimplement the Legacy DatagramSocket API

  • Re-implement the old DatagramSocket API
  • Change java.net.DatagramSocket and java.net.MulticastSocket to a simpler, more modern underlying implementation.

6. Other

  • Disable and Deprecate Biased Locking
  • Instanceof Automatic Matching mode (preview)
  • ZGC, a scalable, low latency garbage collector. (positive)
  • JDK 13 and 14 preview, 14 is finally positive.
  • Remove the Solaris and SPARC Ports
  • External memory access API (allows Java applications to safely and efficiently access external memory outside of the Java heap.)
  • Second preview of the Record type (previewed in Java 14)

Reference and thanks

  • JDK6 has new features
  • New features in Java 7
  • Overview of new Java 9 features
  • New features in Java 9
  • This section describes new Java 10 features
  • This section describes new Java 11 features
  • Overview of new Java 13 features
  • Overview of new Java 14 features
  • The JDK/Java released 15
  • Java 15 is officially released with 14 new features to refresh your knowledge!!

] (www.cnblogs.com/javastack/p)…

Personal public account