Interpretation of the new features of Java9-17, if you know less than 3, you may be out of touch

foreword

Java8 has become the most mature and stable version of the enterprise after so many years. I believe that most companies still use this version. However, Java19 has come out this year in the blink of an eye. I believe that many Java engineers are busy with learning and work and do not know much about new features. The words are also limited to a certain block.

This article is a case verification and a brief description of the new features that the blogger feels are useful, and they are integrated and shared with everyone.

特别说明:Java17是继Java8之后的一个重要里程碑,像SpringBoot3.0、IDEA2022、Jenkins新版、Kafka4.0等等很多生态都强制绑定支持这个版本,等于是给它背书,博主建议大家有必要花时间去了解一下。

If you don't have time to read it, you can 收藏一下read it while drinking tea when you are free.


your harvest

First of all, you can understand the overall future development trend of Java after Java8 through a simple, continuous, and intuitive article, laying the foundation for adapting to Java-related work in the next few years;

Secondly, you can add points for future interviews by understanding the new features of Java9-17. After all, a programmer who loves to learn and has an attitude will be more favored by enterprises;

Finally, you can take a look at bloggers' superficial views on the future development trend of Java, which may bring benefits to you who are confused.


Preparation

First of all, you need to install the Java17 version, the environment variable configuration is still the same as before, this is my version.

insert image description here

Secondly, it is recommended to install IDEA2022.3. The new version of IDEA takes up much less memory than before, and has some enhanced support.

After installation, you need to do a Java17 configuration, see the picture.

setting配置
insert image description here
Project Structure配置
insert image description here
这里特别说明一下,最好选择预览版本,因为Java17包含一些预览功能,这里不选预览版本会编译报错。
insert image description here
insert image description here

new features

It is divided into 8 parts in total, and they are described in the order of versions. The last one is taken out separately because several versions have been continuously enhanced.

1. Interface private

1), description

The new feature of Java9, the private method declared in the interface will not be implemented externally.

2), case

Declare an interface, a default method, and two private methods.

/**
 * <p>
 * 用户信息接口
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 15:03
 */
public interface UserInterface {
    
    
   private void getUsername() {
    
    
      System.err.println("你好,我是王小飞!");
   }

   private void getPassword() {
    
    
      System.err.println("你好,我是徐西圆!");
   }

   default void getData() {
    
    
      getUsername();
      getPassword();
   }
}

Implementing this interface, you can see that only the default method can be implemented, and the private method cannot be implemented.

/**
 * <p>
 * JDK9新特性:接口private方法
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 15:10
 */
public class UserImpl implements UserInterface {
    
    

   @Override
   public void getData() {
    
    
      UserInterface.super.getData();
   }

   public static void main(String[] args) {
    
    
      UserImpl user = new UserImpl();
      user.getData();
   }
}

Ctrl+Insert can view the method to be implemented
insert image description here

3), pay attention

The private interface is automatically default, so there must be a method body, otherwise the compilation will fail.


2. Type inference

1), description

A new feature of Java 11, using the var keyword to declare a property or object inside a method, can be automatically judged by the compiler.

2), case

The case contains two tests, one is to directly test whether the variable declared by var can infer the type by itself, and the other is the effect of using it in the loop.

/**
 * <p>
 * JDK11新特性:类型推断
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 11:52
 */
public class TypeInferenceDemo {
    
    

   public static void main(String[] args) {
    
    
      TypeInferenceDemo demo = new TypeInferenceDemo();
      // 测试类型推断
//    demo.testVar();

      // 循环中使用
      List<UserInfo> userList = new ArrayList<>();
      UserInfo userInfo = new UserInfo();
      userInfo.setUsername("张三");
      userInfo.setPassword("123456");
      userList.add(userInfo);
      for (var user : userList) {
    
    
         System.err.println(user.getUsername() + " | " + user.getPassword());
      }
   }

   public void testVar() {
    
    
      var name = "张三";
      var age = 33;
      var id = 1001L;
      var amount = BigDecimal.ZERO;
      var user = new UserInfo();
      System.err.println("-------------------------------------------------");
      System.err.println(name);
      System.err.println(age);
      System.err.println(id);
      System.err.println(amount);
      System.err.println(user);
   }

   public static class UserInfo {
    
    
      private String username;
      private String password;

      public String getUsername() {
    
    
         return username;
      }

      public void setUsername(String username) {
    
    
         this.username = username;
      }

      public String getPassword() {
    
    
         return password;
      }

      public void setPassword(String password) {
    
    
         this.password = password;
      }
   }
}

The effect of the test is shown in the figure

insert image description here
insert image description here

3), pay attention

1), can only be used inside the method (local variables);

2), must have an initialization value and cannot be null;

3) It cannot be defined as the return type of a method.


3. Null pointer optimization

1), description

The new feature of Java15 is to optimize the log of NullPointerException exception and print it more humanely.

2), case

It can be seen that the prompt will be more directional, which means that you will probably not be bothered by null pointer exceptions in the complex production environment troubleshooting process in the future.

insert image description here

3), pay attention

nothing to notice


4. Text block

1), description

The new feature of JDK15 is to replace the concise version of a bunch of line breaks and double quotation marks in the previous String. I believe you will find it hard not to like it.

2), case

It can be seen that the triple quotes replace the double quotes, because the content of the double quotes will contain a bunch of newline characters, and the inside of the triple quotes is simply the content, which is very clear, and the double quotes need a bar n to break the line, while the triple quotes directly wrap the line. can take effect.

/**
 * <p>
 * JDK15新特性:文本块
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 23:36
 */
public class TextBlockDemo {
    
    
   private static final String str =
         "本以为大S和汪小菲的事情就这样告一段落,彼此都过着属于自己的幸福小日子,但是,被骂9天后,汪小菲口中的“窝囊废”,终于有所行动了!\n"
         + "\n"
         + "也许具俊晔再也忍受不了别人骂自己窝囊废,更不愿意住在别人房子内,所以11月30日,据媒体爆料,具俊晔这次要男人一把,决定买一套属于自己的房子,"
         + "属于自己的床垫,搬出汪小菲买的豪宅,来证明自己的实力。";

   private static final String newStr = """
            本以为大S和汪小菲的事情就这样告一段落,彼此都过着属于自己的幸福小日子,但是,被骂9天后,汪小菲口中的“窝囊废”,终于有所行动了!
            
            也许具俊晔再也忍受不了别人骂自己窝囊废,更不愿意住在别人房子内,所以11月30日,据媒体爆料,具俊晔这次要男人一把,决定买一套属于自己的房子,
            属于自己的床垫,搬出汪小菲买的豪宅,来证明自己的实力。
         """;

   public static void main(String[] args) {
    
    
      System.err.println(str);
      System.err.println("------------------------------------------------");
      System.err.println(newStr);
   }
}
3), pay attention

There is only one thing to pay attention to in the text block, that is, the content inside the triple quotes is not indented by default. If you want to indent, you must use the trailing triple quotes as a reference to offset backwards to determine the amount of indentation.

The following picture will show you the effect directly:

insert image description here

5. Intelligent Transformation

1), description

The new feature of Java16 is to help you enhance instanceof and intelligently convert variable types.

2), case

You can compare the two writing methods of old and new. The second method simplifies the first method. Type conversion + variable declaration + subsequent logical judgment can be done together.

/**
 * <p>
 * JDK16新特性:智能转型
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/3 14:02
 */
public class InstanceofMatching {
    
    
   /**
    * 旧写法
    * @param obj 未知对象
    */
   static void testOld(Object obj) {
    
    
      if (obj instanceof String) {
    
    
         String s = (String) obj;
         if ("模式匹配".equals(s)) {
    
    
            System.err.println(s);
         }
      }
   }

   /**
    * 新写法
    * @param obj 未知对象
    */
   static void testNew(Object obj) {
    
    
      if (obj instanceof String s && "模式匹配".equals(s)) {
    
    
         System.err.println(s);
      }
   }

   public static void main(String[] args) {
    
    
      testOld("Hello, Java!");
      testNew("模式匹配");
   }
}
3), pay attention

If you need to enhance the judgment after instanceof, you must use && instead of ||, because instanceof is for type matching. Java can ensure that the variables after && must exist, but it cannot judge that the variables after || must exist, so it will report an error.

insert image description here

6. Record class

1), description

The new feature of Java16, simply put, is that with it, declaring a final class becomes more concise and readable.

2), case

first look at the writing

/**
 * <p>
 * JDK16新特性:record类
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 21:52
 */
public record RecordDemo(int type, String typeName) {
    
    
   private void test() {
    
    
      System.err.println(type + " | " + typeName);
   }
   public static void main(String[] args) {
    
    
      // 这里new的时候带的参数其实就是类的属性,等于声明属性+访问构造方法二合一。
      RecordDemo recordDemo = new RecordDemo(100, "葡萄牙");
      recordDemo.test();
   }
}

The above new way of writing is equivalent to the old way of writing below, which can be understood at a glance.

/**
 * <p>
 * RecordDemo的写法等同于这个类
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 21:55
 */
public final class RecordCustomDemo {
    
    
   final int type;
   final String typeName;

   public int type() {
    
    
      return type;
   }

   public String name() {
    
    
      return typeName;
   }

   public RecordCustomDemo(int type, String typeName) {
    
    
      this.type = type;
      this.typeName = typeName;
   }

   @Override
   public boolean equals(Object o) {
    
    
      if (this == o)
         return true;
      if (o == null || getClass() != o.getClass())
         return false;
      RecordCustomDemo that = (RecordCustomDemo) o;
      return type == that.type && Objects.equals(typeName, that.typeName);
   }

   @Override
   public int hashCode() {
    
    
      return Objects.hash(type, typeName);
   }
}
3), pay attention

Nothing to notice, it's almost like using a normal class, except that the following is automatically generated:

1) The parameters in the brackets are the attributes of the class and are of final type;

2) Automatically generate a constructor with this attribute;

3) Automatically generate accessors for this attribute, such as xx.type(), xx.typeName();

4) Generate equals and hashCode methods.

If you still don’t understand, just understand it as the @Data annotation in lombok, the same meaning.


7. Sealed classes and interfaces

1), description

Java17 new features, sealed classes and sealed interfaces.

A class declared with the sealed keyword can control which subclasses can inherit it by setting the permits keyword.

Using the interface declared with the sealed keyword, you can control which classes can implement it by setting the permits keyword. .

To put it simply, the father stipulates which son can inherit the property.

2), case

Look at the wording of the sealed class

Declare a class with sealed, and set the permits to authorize which subclasses can inherit it.

/**
 * <p>
 * JDK17新特性:密封类
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 17:20
 */
public sealed class Daddy permits Son1, Son2 {
    
    
}

first son can inherit

/**
 * <p>
 *
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 17:22
 */
public final class Son1 extends Daddy {
    
    
}

second son can inherit

/**
 * <p>
 *
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 17:23
 */
public final class Son2 extends Daddy {
    
    
}

The third son is probably an unfilial son

It can be seen that IDEA has an error prompt, which means that it is not allowed by the parent class of the sealed declaration.

insert image description here

Then, we look at the sealing interface.

In fact, it is similar to the sealed class, but it can also be combined with the record mentioned above to simplify the code.

/**
 * <p>
 * JDK17新特性:密封接口
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 18:03
 */
public sealed interface DaddyInterface permits Son4, Son5 {
    
    
   void test();
}

The fourth son can realize his father's wish. After using record, the declaration of variables and the realization of some built-in methods are simplified.

/**
 * <p>
 *
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 17:23
 */
public record Son4(int age, String name) implements DaddyInterface {
    
    
   @Override
   public void test() {
    
    

   }
}

Fifth son can fulfill father's wish

/**
 * <p>
 *
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/2 17:23
 */
public record Son5(int age, String name) implements DaddyInterface {
    
    
   @Override
   public void test() {
    
    

   }
}

The sixth son is a bit stupid and cannot realize his father's wish. He can see the same error message as the previous sealed class.

insert image description here

3), pay attention

1), the parent class of the sealed declaration, its subclasses can only be modified with final, sealed, non-sealed;

2) The parent class declared by sealed must have at least one subclass;

3) A subclass that is not authorized in permits cannot inherit the parent class;

4) There is no difference between the sealed interface and the sealed type;

4) Sealing interfaces combined with records can save more code and make it more concise.

Here is a special point, sealed and record are actually very meaningful in the pattern matching of new Java features, but I think pattern matching is a bit obscure for Java programmers who have never known it. Combined with sealed, it feels like a nesting doll pyramid scheme. If it is difficult to understand, it is not our original purpose, so there is no dedicated chapter to go into details. At the end, I will briefly talk about my views on pattern matching.


8. Switch enhancement

1), description

Why put switch alone at the end, because Java14-17 has enhanced it respectively, and it is more intuitive to put it at the end.

There are three changes in total:

1), support arrow syntax;

2), support expressions;

3), support case null.

2), case

Arrow syntax, in fact, is to replace the colon and break in the old writing with arrows instead, which is more concise.

/**
 * <p>
 * JDK14新特性:switch箭头语法
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/3 11:05
 */
public class SwitchDemo1 {
    
    
   private static void foods(int i) {
    
    
      switch (i) {
    
    
         case 1:
            System.err.println("青椒肉丝");
            break;
         case 2:
            System.err.println("番茄炒蛋");
            break;
         default:
            System.err.println("米饭");
      }
   }

   private static void fruits(int i) {
    
    
      switch (i) {
    
    
         case 1 -> System.err.println("香蕉");
         case 2 -> System.err.println("猕猴桃");
         default -> System.err.println("苹果");
      }
   }

   public static void main(String[] args) {
    
    
      foods(1);
      fruits(3);
   }
}

Support expressions, in fact, can write a single or multiple expressions to return.

/**
 * <p>
 * JDK14新特性:switch支持表达式
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/3 11:05
 */
public class SwitchDemo3 {
    
    

   /**
    * 单表达式
    */
   private static String fruits(int i) {
    
    
      return switch (i) {
    
    
         case 1 -> "香蕉";
         case 2 -> "猕猴桃";
         default -> "苹果";
      };
   }

   /**
    * 多表达式
    */
   private static String fruitsNew(int i) {
    
    
      return switch (i) {
    
    
         case 1, 2 -> {
    
    
            System.err.println("----------------------------------");
            System.err.println("来一个香蕉");
            yield "香蕉来咯";
         }
         case 3, 4 -> {
    
    
            System.err.println("----------------------------------");
            System.err.println("来一个猕猴桃");
            yield"猕猴桃来咯";
         }
         default -> {
    
    
            System.err.println("----------------------------------");
            System.err.println("没的选就来个苹果吧");
            yield "苹果来咯";
         }
      };
   }

   public static void main(String[] args) {
    
    
//    System.err.println(fruits(2));
//    System.err.println(fruits(3));

      System.err.println(fruitsNew(2));
      System.err.println(fruitsNew(4));
      System.err.println(fruitsNew(5));
   }
}

Support case null, in fact, the case can receive null value.

/**
 * <p>
 * JDK17新特性(预览):switch支持case null
 * </p>
 *
 * @author 程序员济癫,公众号:【Java分享客栈】
 * @since 2022/12/3 11:05
 */
public class SwitchDemo2 {
    
    
   private static void foods(String s) {
    
    
      if (s == null) {
    
    
         return;
      }
      switch (s) {
    
    
         case "1":
            System.err.println("青椒肉丝");
            break;
         case "2":
            System.err.println("番茄炒蛋");
            break;
         default:
            System.err.println("米饭");
      }
   }

   private static void fruits(String s) {
    
    
      switch (s) {
    
    
         case "1" -> System.err.println("香蕉");
         case null -> System.err.println("null");
         default -> System.err.println("苹果");
      }
   }

   public static void main(String[] args) {
    
    
      foods("1");
      fruits(null);
   }
}

You can see the effect, passing null directly will not report an error.

insert image description here

3), pay attention

1), Arrow syntax, colon and arrow cannot exist at the same time;

2) For expressions, curly braces should be used for multiple expressions and the yield keyword should be used to return;

3), case null is a preview function, select Language Level 17 (Preview) in IDEA - Project Structure - Modules to compile and pass, refer to the previous preparations.


Summarize

1), the new features of Java9-17 are not only here, but also some very characteristic content, such as immutable collection, modularization, API enhancement of String and Stream, etc., but I personally think it is not representative, either Tools can directly help you convert, or you probably won’t be able to use them, so they are not listed;

2) Pattern matching is the focus of many Java programmers. The contents of record, switch, sealed class and interface in this article are actually the basis of pattern matching, but pattern matching is not mature for Java. "Thinking The author of "In Java" also said that it may take several years to see the complete form of Java pattern matching, so there is no need to spend too much time on researching an incomplete version now. Compared with Python, Kotlin, and Scala, this feature is actually inferior not far off.


Java development trend

Finally, let me talk about this issue that many people care about. I think as long as you understand the new features and preview features of these versions after Java8, you can definitely find that Java is trying to change, which is a good signal.

For example, the above new features, you can even find many shadows of Python, JavaScript and other languages. As a new language, Go language was developed on the shoulders of giants, absorbing the excellent features of many languages.

Now, Java is also taking a similar path. It can be clearly seen that it is incorporating the highlights of some excellent languages ​​into its new version. This trend represents a meaning: Java is constantly improving.

The Internet has been filled with some comments that look down on Java. There is no need to take it seriously. You have to experience the ecology and understand the dynamics of domestic IT companies to feel it.

Java is still the most widely used language in China and has the largest ecology. This cannot be replaced overnight, but is the result of the development of market laws.

SpringBoot3.0 supports Java17, the new version of Jenkins supports Java17, Kafka4.0 directly abandons Java8, ElasticSearch8.x supports JDK17 at least, and IDEA2022 supports Java17 by default. Microsoft has announced that it fully embraces Java, which is not only an improvement at the technical level, but also a more beneficial appeal and bundling.

From this point of view, learning Java is completely worthwhile. As a mature, excellent and rigorous language, it is sitting upright like a white-collar worker.

I also think that engineers who learn and master Java now will not have pressure to switch to other languages ​​in the future. The new features above illustrate this direction, and it is absorbing the highlights of other languages.

What can be expected in the future is that when you switch to other languages, it will gradually become less strange and obscure. This is a direction I see. The general direction of future programming language development is great integration (big plagiarism, cough cough) , you There is me, and there is you in me.



The original article is purely hand-typed, typed out one by one, 键盘上全是血if you think it is helpful, please click 赞和收藏~

I am committed to sharing my work experience and interesting stories. If you like it, you can enter the homepage 关注一下~

Guess you like

Origin blog.csdn.net/xiangyangsanren/article/details/128166322