A little twist

Many Java beginners often ask:

  • Which version of the JDK is better to install?
  • Is Java 8 still good enough?
  • What exactly are the improvements in Java 11?
  • Is the Java version as new as possible?

Well, the official website is now in Java 13 and available for download.

But the major stable releases on the market today are, of course, Java 8 and Java 11, and Java 8 is still the dominant production environment for most companies. So if from the perspective of self-study, I think these two versions are OK, other intermediate versions such as Java 9, Java 10 and other unstable versions do not need to be considered.


Java11 vs Java8

Java 11 does have some evolution over Java 8. In addition to many internal upgrades (such as lower overhead and latency for GC, TLS1.3 enhancements, etc.), there are also some language level evolution for novice users.

Just recently I try on your personal small projects using the Java 11 (company project I also dare not move, also dare not ask, so we have to move his personal items), so this article from the perspective of the actual code to experience personally I use Java roughly 11 after relative Java 8 feel some of the more profound evolution, Speak very clearly as well in the official documentation: https://docs.oracle.com/en/java/javase/11/

The Java 11 version I installed this time is 11.0.6:

Some of the new features I’ll test in the following sections were not just introduced in Java 11; many were introduced in Java 9 and Java 10, but only in the stable version of Java 11.


Variable type inference

The new version of Java introduces a new type keyword var, var to define a variable does not need to write a specific type, the compiler can automatically infer the type of the variable from the actual value assigned to the right of = :

1. Ordinary local variables

var name = "codesheep"; // Automatically infer that name is a String
System.out.println(name);
Copy the code

How’s that? Is there an illusion of using a weakly typed language like JavaScript?

2. Used in the for loop

var upList1 = List.of( "Liu"."Zhao four"."Xie Guangkun" );
var upList2 = List.of( Strong "forever"."Yutian"."Liu ying" );
var upList3 = List.of( "Thank you airplane."."Laney"."Lana" );
var upListAll = List.of( upList1, upList2, upList3 );
for( var i : upListAll ) { // Using var to accept local variables is very succinct!
    for( var j : i ) { System.out.println(j); }}Copy the code

This is where we can see the advantage of using var to define local variables. If the set element type in this example is more complex, such as List >, var definition is very straightforward.

3. Of course, there are situations where you can’t use it

Once a variable of type var is assigned, it is not possible to reassign a value of a different type. For example:

var name = "codesheep";
name = Awesome!;  // The compiler will tell you about incompatible types
Copy the code

It is not possible to define a variable of type var without initializing it, as in:

var foo;  // The type cannot be inferred
foo = "Foo";
Copy the code

Var is not allowed for class member variable types, method input parameter types, and return value types.

public class Test {
    
    private var name; // It prompts that var is not allowed

    public void setName( var name ) { // It prompts that var is not allowed
        this.name = name;
    }

    public var getName(a) { // It prompts that var is not allowed
        returnname; }}Copy the code

Official HTTP Client support

Yes!

HTTP: HTTP: OKHttp; HTTP: OKHttp; HTTP: OKHttp; HTTP: OKHttp; HTTP: OKHttp; HTTP: OKHttp;

Send a synchronization request:

var request = HttpRequest.newBuilder()
        .uri( URI.create("https://www.codesheep.cn") )
        .GET()
        .build();
// Block the current thread until the result is received
var httpResponse = HttpClient.newHttpClient()
        .send( request, HttpResponse.BodyHandlers.ofString());
System.out.println( httpResponse.body() ); // Print the retrieved web page content
Copy the code

Sending asynchronous requests:

CompletableFuture<String> future = HttpClient.newHttpClient().
        sendAsync( request, HttpResponse.BodyHandlers.ofString() )
        .thenApply( HttpResponse::body );
System.out.println("I'll get on with something else...");
System.out.println( future.get() ); // Print the retrieved web page content
Copy the code

Of course, you can also customize the request header, such as carrying the JWT Token permission information to request:

var requestWithAuth = HttpRequest.newBuilder()
        .uri( URI.create("http://www.xxxxxx.com/sth") )
        .header("Authorization"."Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTIwNTE2MTE5NiIsImNyZWF0ZWQiOjE1ODMzMTA2ODk0MzYsImV4cCI6MTU4MzM5NzA4OSwidXNlcmlkIjoxMDA wNH0.OE9R5PxxsvtVJZn8ne-ksTb2aXXi7ipzuW9kbCiQ0uNoW0fJJr_wckLFmgDzxmBs3IdzIhWDAtaSIvmTshK_RQ")
        .GET()
        .build();
var response = HttpClient.newHttpClient()
        .send( requestWithAuth, HttpResponse.BodyHandlers.ofString() );
System.out.println( response.body() ); // Prints the returned contents of the interface
Copy the code

String processing enhancement

The new String type adds convenient String handling methods such as isBlank(), strip(), repeat(), and so on

String myName = " codesheep ";
System.out.println( "".isBlank() ); // Print: true
System.out.println( "".isEmpty() ); // Print: false

System.out.println( myName.strip() );         // Print codesheep with the Spaces removed
System.out.println( myName.stripLeading() );  // Print codesheep with only header Spaces removed
System.out.println( myName.stripTrailing() ); // Print codesheep with only trailing Spaces removed
System.out.println( myName.repeat(2));// Print codesheep codesheep
Copy the code

Set to enhance

Methods such as of() and copyOf() have been added to make it easier to create and copy collection types

var upList = List.of( "Liu"."Zhao four"."Xie Guangkun" );
var upListCopy = List.copyOf( upList );
System.out.println(upList);     // Print [Liu Neng, Zhao Si, Xie Guangkun]
System.out.println(upListCopy); // Print [Liu Neng, Zhao Si, Xie Guangkun]

var upSet = Set.of("Liu"."Zhao four");
var upSetCopy = Set.copyOf( upSet );
System.out.println(upSet);      // Print [Zhao Si, Liu Neng]
System.out.println(upSetCopy);  // Print [Zhao Si, Liu Neng]

var upMap = Map.of("Liu"."58"."Zhao four"."59");
var upMapCopy = Map.copyOf( upMap );
System.out.println(upMap);      // print {liu Neng =58, Zhao Si =59}
System.out.println(upMapCopy);  // print {liu Neng =58, Zhao Si =59}
Copy the code

Functional programming enhancements

What impressed me most was the addition of cut-off methods such as takeWhile() and dropWhile() to Stream:

var upList = List.of( "Liu"."Zhao four"."Xie Guangkun" );

// Remove the elements that meet the criteria from the collection until they do not
var upListSub1 = upList.stream()
        .dropWhile( item -> item.equals("Liu") )
        .collect( Collectors.toList() );
System.out.println(upListSub1);  // Print [Zhao Si, Xie Guangkun]

// Retrieve the elements from the set until the condition is not satisfied
var upListSub2 = upList.stream()
        .takeWhile( item -> item.equals("Liu") )
        .collect( Collectors.toList() );
System.out.println( upListSub2 ); // Print [liu Neng]
Copy the code

File read and write enhancement

1. Files class enhancement

The ability to read a file directly into a String and write a String back to a file is now available via the static methods writeString() and readString() of the Files class:

Path path = Paths.get("/Users/CodeSheep/test.txt");
String content = Files.readString(path, StandardCharsets.UTF_8);
System.out.println(content);
Files.writeString( path, "Wang Lao Qi", StandardCharsets.UTF_8 );
Copy the code

2. InputStream enhancement

InputStream adds a transferTo() method to throw data directly to the OutputStream:

InputStream inputStream = new FileInputStream( "/Users/CodeSheep/test.txt" );
OutputStream outputStream = new FileOutputStream( "/Users/CodeSheep/test2.txt" );
inputStream.transferTo( outputStream );
Copy the code

Support direct running from source files (666!)

Let’s say I write the simplest Hello World program:

public class Hello {
    
    public static void main( String[] args ) {
        System.out.println("hello world"); }}Copy the code

And save as hello. Java file, then you can directly use the Java command to run the Java source file, directly save the previous Javac source file compilation process:

java hello.java
Copy the code

How’s that? Isn’t it a bit like running python source files? That’s a lot of information, so you can imagine


summary

Java 11 does have a lot of improvements, but again, there’s no need for beginners to try new things in Java 8. Stability is the most important thing!