Female colleague: brother ha, we used java8 before, but now we use Java11. What are the new features?
Me: Oh, we improved the JDK version in order to improve the compatibility and stability with other subsystem programs.
Female colleague: Oh? That means you don't know what's new.
I:( 😳😳?? Do you think so clearly after 00) cough, well, I only know a little;
Female colleague: tell me about it. I want to know~
Me: no problem ~ let's go and cook first. (unique skill: Fan Dun)
when you mention the new features of JDK8, you may think of Lambda, functional interface, Stream, Optional, date and time API enhancements, etc;
Admittedly, these are the features we use every day. However, what you don't care about is that JDK has been silently updated to JDK16 (an average version every 6 months), and JDK17 will be released in a few months. Hahaha! Alas, it's really a big dish.
when the students of the fan group shared the interview questions two days ago, I saw that the interview questions included: what are the new features of JDK8 to JDK11?. I'm surprised. It's all rolled up like this?
although I am also using JDK11, I still stay in JDK8 for new features.. Are we old or young? 😳😳
in this article, we'll sort out some new features that can be used in daily programming. Maybe you'll find a new world. Update your code quickly ~ ~ of course, don't change the code for online maintenance, you know.
JDK9 (September 2017)
9-1. Example factory method
with a new feature of Java 9, the collection factory method, we can easily create immutable collections with predefined data. You only need to use the of method on a specific collection type.
List<String> fruits = List.of("apple", "xiaomi", "13xiang"); Map<Integer, String> numbers = Map.of(1, "one", 2,"two", 3, "three"); Set<String> colors = Set.of("yellow", "red", "baoqiang");
before Java 9, if we want to create an immutable set, we need to create a variable set first, and then use unmodifiable set to create an immutable set, which is obviously very troublesome.
public List<String> fruits() { List<String> fruitsTmp = new ArrayList<>(); fruitsTmp.add("apple"); fruitsTmp.add("xiaomi"); fruitsTmp.add("13xiang"); return Collections.unmodifiableList(fruitsTmp); } public Map<Integer, String> numbers() { Map<Integer, String> numbersTmp = new HashMap<>(); numbersTmp.put(1, "one"); numbersTmp.put(2, "two"); numbersTmp.put(3, "three"); return Collections.unmodifiableMap(numbersTmp); } public Set<String> setStr() { Set<String> colors = new HashSet<>(); colorsTmp.add("A"); colorsTmp.add("B"); colorsTmp.add("C"); colorsTmp = Collections.unmodifiableSet(colors); System.out.println(colorsTmp); return colorsTmp; }
similarly, you can use arrays only by creating from the ArrayList object table asList(…)method.
public List<String> fruitsFromArray() { String[] fruitsArray = {"apple", "xiaomi", "13xiang"}; return Arrays.asList(fruitsArray); }
9-2. Private methods can be added to the interface
based on JAVA 8, the default method support is added to the interface. This function is further upgraded in JAVA 9. Private methods can be defined in the interface, and private methods of the interface can be called in the default method.
​
ublic interface testInterface { String test(); // Interface default method default String defaultTest() { staticTest(); return "default"; } private String privateTest() { System.out.println("private method staticTest"); return "static"; } }
9-3. Improve try with resources
in Java 9, there is no need to define an additional variable in try. Before Java 9, you need to use try with resources as follows:
InputStream inputStream = new StringBufferInputStream("Ha ha Chen"); try (InputStream in = inputStream) { in.read(); } catch (IOException e) { e.printStackTrace(); }
in Java 9, you can directly use the inputStream variable in the try without defining a new variable.
InputStream inputStream = new StringBufferInputStream("Ha ha Chen"); try (inputStream) { inputStream.read(); } catch (IOException e) { e.printStackTrace(); }
9-4. Multi version compatible jar package
Java 9 supports maintaining different versions of Java classes and resources in the same JAR.
9-5. The diamond operator < > is enhanced and can be used in anonymous inner classes.
in fact, JAVA 5 introduced generics, and JAVA 7 began to support the diamond operator, < >, which can automatically infer the type of generics.
Before Java 9, generic types need to be specified for internal anonymous classes, as follows:
List<Integer> numbers = new ArrayList<Integer>() { }
In Java 9, type derivation can be done automatically, as follows:
List<Integer> numbers = new ArrayList<>() { }
9-6. Enhanced JDK8 features
the features of JDK8 are enhanced, such as Stream, Optional and Process API
JDK10 (March 2018)
10-1. Automatic type inference of local variables (var)
var a = "Hello, Java 10"; System.out.println(a);
JAVA 10 brings an interesting syntax var, which can automatically infer the type of local variables. In the future, there is no need to write the type, and there is no need to enhance it by lombok's var annotation
however, this is only a syntax sugar. Variables after compilation still have types. Maintainability should be considered when using them. Emphasize that the var keyword can only be used in local variables and for loop variable declarations at present.
10-2. Enhanced Optional
starting with Java 9 and Java 10, there are several useful methods for Optional. The two most interesting ones are orElseThrow and ifpresentoelse.
if there is no value, use the orElseThrow method to throw NoSuchElementException. Otherwise, it returns a value.
public Person getPersonById(Long id) { Optional<Person> personOpt = repository.findById(id); return personOpt.orElseThrow(); }
therefore, we can avoid using if statements with parameters with isPresentmethod.
public Person getPersonByIdOldWay(Long id) { Optional<Person> personOpt = repository.findById(id); if (personOpt.isPresent()) return personOpt.get(); else throw new NoSuchElementException(); }
the second interesting method is ifpresentoelse. If a value exists, it will use it to perform the given operation. Otherwise, it will perform the given null based operation.
public void printPersonById(Long id) { Optional<Person> personOpt = repository.findById(id); personOpt.ifPresentOrElse( System.out::println, () -> System.out.println("Person not found") ); }
in Java 8, we can use if else directly with isPresent method.
public void printPersonByIdOldWay(Long id) { Optional<Person> personOpt = repository.findById(id); if (personOpt.isPresent()) System.out.println(personOpt.get()); else System.out.println("Person not found"); }
Java 11 (September 2018)
11-1. var is used in Lambda
public String sumOfString() { BiFunction<String, String, String> func = (var x, var y) -> x + y; return func.apply("abc", "efg"); }
11-2. String API enhancement
Java 11 adds a series of string processing methods, such as:
// Judge whether the string is blank, and judge whether it is blank " ".isBlank(); "".isEmpty(); " Java11 ".stripTrailing(); // " Java11" " Java11 ".stripLeading(); // "Java11 "
11-3. javac + java command normalization
before compiling a java file, you need to compile javac into class, and then execute it in Java. Now you can put it together for execution, Xiang!
$ java HelloWorld.java Hello Java 11!
JDK 12 (March 2019)
12-1. Switch expression
we can define multiple case labels and use the arrow to return the value, which is called the switch using case L - > arrow label.
this function is available from JDK 12. It makes Switch expressions really easier to access.
public String newSwitch(int day) { return switch (day) { case 1, 2, 3 -> "Fishing day"; case 4 -> "Little Friday"; case 5, 6, 7 -> "Rest Day"; default -> "invalid"; }; }
The following code:
newSwitch(1); newSwitch(4); newSwitch(6);
The results are as follows:
Fishing day Little Friday Rest Day
For Java below 12, the same example is much more complex.
public String oldSwitch(int day) { switch (day) { case 1: case 2: case 3: return "Fishing day"; case 4: return "Little Friday"; case 5: case 6: case 7: return "Rest Day"; default: return "invalid"; } }
do you feel a lot of confusion about our definitions of rest days and small Fridays? Not surprisingly, in our SQL thigh group, little Friday and Friday have become a traditional festival every week, which is worth celebrating~~
12-2. instanceof + type forced conversion in one step
when a dynamic type needs to be forcibly converted before processing, you need to judge instanceof first, and then forcibly convert to this type:
Object obj = "Hello Java 12!"; if (obj instanceof String) { String s = (String) obj; int length = s.length(); }
now instanceof supports direct type conversion, and there is no need for another forced conversion:
Object obj = "Hello Java 12!"; if (obj instanceof String str) { int length = str.length(); }
JDK 13 (September 2019)
13-1. Text Block support
text blocks are multiline string literals that avoid escape sequences and automatically format strings in a predictable manner. It also allows developers to control the format of strings. Starting with Java 13, text blocks can be used as preview functions. They begin with three double quotes ("" "). Let's see how we can easily create and format JSON messages.
public String getNewPrettyPrintJson() { return """ { "name": "chenhaha", "sex": "undefined" } """; }
creating the same JSON string before Java 13 is much more complex.
public String getOldPrettyPrintJson() { return "{\n" + " \"name\": \"chenhaha\",\n" + " \"sex\": \"undefined\"\n" + "}"; }
13-2. Enhanced switch syntax:
although swtich syntax is enhanced in JAVA 12, complex logic cannot be written after - > JAVA 13 brings a more perfect experience of swtich. Just like lambda, you can write logic and then return:
int j = newSwitch (day) { case 1, 2, 3 -> "Fishing day"; case 4 -> "Little Friday"; case 5, 6, 7 -> "Rest Day"; default -> { var k = day.toString().length(); var res = f(k); yield res; } };
JDK14 (March 2020)
14-1. Add Record class
starting with Java 14, a new record class is introduced. When we define the record class, we use the keyword record;
using Records, you can define immutable pure data classes (getter s only), also known as record classes. It will automatically create toString, equals and hashCode methods. In fact, you only need to define the fields shown below.
public record Person(String name, int age) {}
classes with similar functions, such as record, include fields, constructors, getter s and toString, equals and hashCode methods.
public class PersonOld { private final String name; private final int age; public PersonOld(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersonOld personOld = (PersonOld) o; return age == personOld.age && name.equals(personOld.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "PersonOld{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
14.2. Add jpackage packaging tool
add jpackage packaging tool to directly package binary programs, and you don't need to install JRE anymore!
before, if you want to build an executable program, you also need to use three-party tools to package JRE together, or let the client computer install a JRE to run our JAVA program.
now JAVA has a directly built-in jpackage packaging tool to help you package binary packages with one click without any more fuss.
JDK15 (September 2020)
15-1. ZGC and Shenandoah garbage collectors are officially launched
in JAVA 15, ZGC and Shenandoah are no longer experimental functions, but they are officially logged in (but G1 is still the default). If you upgrade to a version after JAVA 15, try it quickly, with stronger performance and lower latency.
15-2. Sealed
use the sealed class function to limit the use of superclasses. Using the new keyword, sealed can define which other classes or interfaces can extend or implement the current class.
public abstract sealed class Pet permits Cat, Dog {}
allowed subclasses must define a modifier. If you do not want to allow any other extensions, you need to use the final keyword.
public final class Cat extends Pet {}
on the other hand, you can open the extension class. In this case, the non sealed modifier should be used.
public non-sealed class Dog extends Pet {}
of course, the following visible statements are not allowed.
public final class Tiger extends Pet {}
JAVA 16 (March 2021)
JAVA 16 doesn't change much where users can see it. It's basically the experimental content of 14 / 15;
Summary
so why do developers insist on using java 8?
perhaps it is because there will be unexpected bugs in the code and maintenance level of the upgrade. Many enterprises seek stability, and leaders are unwilling to change at will. If the promotion is OK, the leader can get more commission. In case of any problem, the leader can carry the pot for you??
in other words, programmers themselves don't necessarily have time to learn new features and deeply understand new technical features. Don't they have time to look at more interview questions?
Java will have a Long Term Support release (LTS) every three years, which will provide support for three years. Java 8 is an LTS, so it is trustworthy. It has been widely used in the industry, and the next lts are Java11 and Java17 respectively. Mark.
however, most of the current tier 1 java developers should still use the java 8 version. According to statistics, 80% of people are still using JDK8, and even some companies are still using JDK7.
here comes the problem? What is the Java version you use?