Still don’t understand the colleague code? Fill in a wave of Java 7 syntax features

preface

It has been more than 20 years since the emergence of Java platform. During these 20 years, Java has always been one of the most popular programming languages, constantly facing the challenges and shocks of other emerging programming languages. Java language is a static strongly typed language. Such language features can enable the java compiler to find errors in the compilation stage, which is particularly important for building a stable, safe and robust application. But also because of this feature, java development seems to lack flexibility. When developing applications with some functions, the amount of code may be several times that of other languages. The shortcomings of java development are also reflected in the increasingly complex JDK, which makes it very difficult for developers to fully understand. So that developers sometimes repeatedly implement a function already provided in the JDK.

In order to keep up with the development of Internet application programming, Java has adjusted the rhythm of JDK release since version 9. Each update of JDK focuses on improving production efficiency, improving JVM performance and promoting modularization, so that developers can focus more on the business itself rather than wasting too much time on language features. The update of Java language should find a balance between the rigor and flexibility of the language. After all, flexibility can reduce the complexity of coding, and rigor is the cornerstone of building complex and robust applications.

An important updated version of Java is the Java 5 version, which adds a series of important functions such as generics, enhanced for, automatic boxing and unpacking, enumeration types, variable parameters, annotations and so on, but the subsequent Java 6 does not add new important language features. Java 5 was released in 2004. It has been a long time. Most of the online tutorials on Java are based on Java 6. Therefore, I am going to introduce the new features of each java version from Java 7.

All the running demonstrations of the following code are based on Java 7, so if you try the following code, you need to install and configure JDK 1.7 or previous version.

1. switch String

Before Java 7, the switch syntax only supports the judgment of integer types and the encapsulated classes of these integer types. In Java 7, it supports the judgment of string types. It is very simple to use, but it is very practical.

1.1. Basic usage of switch string

Write a simple switch judgment string test class.

public class SwitchWithString {

    public static void main(String[] args) {
        String gender = "男";
        System.out.println(gender.hashCode());
        switch (gender) {
            case "男":
                System.out.println("先生你好");
                break;
            case "女":
                System.out.println("女士你好");
                break;
            default:
                System.out.println("你好");
        }
    }
}

The switch judgment string is very simple to use, and the result is obvious. It will first output the hashcode of the gender variable, and then output the matching result "Hello, sir".

30007
先生你好

When using switch string, the effect will be better if it is combined with the enumeration class of Java 5. Before Java 7, the enumeration class should be used to encode each value. After Java 7, the string name can be defined directly.

1.2. Implementation principle of switch string

However, this support is only supported at the compiler level, and the JVM still does not support it. When switching a string, the compiler will convert the string to an integer type for judgment. In order to verify that the above is only the compiler level support, we decompile the class file generated (you can use JAD decompile tool or double-click the compiled class in idea) and see that the compiler converts the switch string into a string hashcode judgment. In order to prevent hashcode conflict, we use equals to judge again.

public class SwitchWithString {
    public SwitchWithString() {
    }
    
    public static void main(String[] args) {
        String gender = "男";
        System.out.println(gender.hashCode());
        byte var3 = -1;
        switch(gender.hashCode()) {
        case 22899:
            if (gender.equals("女")) {
                var3 = 1;
            }
            break;
        case 30007:
            if (gender.equals("男")) {
                var3 = 0;
            }
        }

        switch(var3) {
        case 0:
            System.out.println("先生你好");
            break;
        case 1:
            System.out.println("女士你好");
            break;
        default:
            System.out.println("你好");
        }

    }
}

2. try-with-resource

Java is different from C + +. Developers need to manage each piece of memory by themselves. Most of the time, Java virtual machine can help us with resource management, but sometimes we need to manually release some resources, such as database connection, disk file connection, network connection, etc. In other words, as long as the number of resources is limited, we need to release them manually.

2.1. try-catch-finally

Various exceptions may occur when operating limited resources. Problems may occur either in the reading phase or in the process of closing resources. We usually use the following method to try catch finally to ensure the release of resources.

Like this.

/**
 * 释放资源
 *
 * @author www.codingme.net
 */
public class TryCatachFinally {

    /**
     * 异常处理
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream("jdk-feature-7.iml");
        } catch (FileNotFoundException e) {
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
    }
}

Look at this disgusting code structure. In order to catch exceptions, we wrote a catch. In order to ensure the release of resources, we wrote finally to release resources. In order to catch the exceptions thrown when closing, we wrote a try catch. Finally, look at this complex code. If someone tells you that there is a bug in this code, you will not believe it. But it is true. It seems that the strict code logic. When the code logic in the try and the close method generate exceptions at the same time, the exception information in the try will be lost.

You can see the example here.

package net.codingme.feature.jdk7;

import java.io.IOException;

/**
 * 释放资源
 *
 * @author www.codingme.net
 */
public class TryCatachFinallyThrow {

    /**
     * 异常处理
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        read();
    }

    public static void read() throws Exception {
        FileRead fileRead = null;
        try {
            fileRead = new FileRead();
            fileRead.read();
        } catch (Exception e) {
            throw e;
        } finally {
            if (fileRead != null) {
                try {
                    fileRead.close();
                } catch (Exception e) {
                    throw e;
                }
            }
        }

    }
}

class FileRead {

    public void read() throws Exception {
        throw new IOException("读取异常");
    }

    public void close() throws Exception {
        System.out.println("资源关闭");
        throw new IOException("关闭异常");
    }
}

Obviously, both read and close methods in the code will generate exceptions, but the running program finds that it can only receive the exception information of close.

资源关闭
Exception in thread "main" java.io.IOException: 关闭异常
	at net.codingme.feature.jdk7.FileRead.close(TryCatachFinallyThrow.java:51)
	at net.codingme.feature.jdk7.TryCatachFinallyThrow.read(TryCatachFinallyThrow.java:33)
	at net.codingme.feature.jdk7.TryCatachFinallyThrow.main(TryCatachFinallyThrow.java:20)

The exception information is lost. What's terrible is that you think it's just an exception when you close.

2.2. try-autocloseable

In fact, new solutions to the above problems have been provided in Java 7. Try has been enhanced in Java 7 to ensure that resources can always be released correctly. The premise of using the enhanced try is that the classes in the try implement the autoclosable interface. In Java 7, a large number of operations that need to release resources have actually implemented this interface.

The class that implements autocloseable does not have to worry about closing resources when used in the enhanced try. After use, the close method will be called automatically, and exceptions will not be lost.

Let's write a class that simulates resource operations to implement the autoclosable interface, and then enhance try to see the effect.

package net.codingme.feature.jdk7;

/**
 * 自动关闭
 *
 * @author www.codingme.net
 */
public class AutoCloseResource {
    public static void main(String[] args) throws Exception {
        try (MysqL MysqL = new MysqL();
             OracleDatabase oracleDatabase = new OracleDatabase()) {
            MysqL.conn();
            oracleDatabase.conn();
        }
    }
}

class MysqL implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("MysqL 已关闭");
    }

    public void conn() {
        System.out.println("MysqL 已连接");
    }
}

class OracleDatabase implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("OracleDatabase 已关闭");
    }

    public void conn() {
        System.out.println("OracleDatabase 已连接");
    }
}

The test classes MySQL and OracleDatabase both implement autocolosable. Run to view the results.

MysqL 已连接
OracleDatabase 已连接
OracleDatabase 已关闭
MysqL 已关闭

Confirm that the exception information will not be lost when an exception occurs, and write a simulation test class with an exception for testing.

package net.codingme.feature.jdk7;

import java.io.IOException;

/**
 * 释放资源
 *
 * @author www.codingme.net
 */
public class AutoCloseThrow {

    public static void main(String[] args) throws Exception {
        try (FileReadAutoClose fileRead = new FileReadAutoClose()) {
            fileRead.read();
        }
    }
}

class FileReadAutoClose implements AutoCloseable {

    public void read() throws Exception {
        System.out.println("资源读取");
        throw new IOException("读取异常");
    }

    @Override
    public void close() throws Exception {
        System.out.println("资源关闭");
        throw new IOException("关闭异常");
    }
}

Run to view exception information.

资源读取
资源关闭
Exception in thread "main" java.io.IOException: 读取异常
	at net.codingme.feature.jdk7.FileReadAutoClose.read(AutoCloseThrow.java:23)
	at net.codingme.feature.jdk7.AutoCloseThrow.main(AutoCloseThrow.java:14)
	Suppressed: java.io.IOException: 关闭异常
		at net.codingme.feature.jdk7.FileReadAutoClose.close(AutoCloseThrow.java:29)
		at net.codingme.feature.jdk7.AutoCloseThrow.main(AutoCloseThrow.java:15)

Automatic shutdown, with clear exception. The shutdown exception exists in suppressed, which is called suppression exception, and will be described in detail in subsequent articles.

3. try-catch

Before Java 7, a catch can only capture one exception information, which is troublesome when there are many types of exceptions. However, in Java 7, a catch can capture multiple exception information, and | segmentation is used between each exception capture,

package net.codingme.feature.jdk7;

import java.io.IOException;

/**
 * 多异常捕获
 */
public class TryCatchMany {

    public static void main(String[] args) {
        try (TxtRead txtRead = new TxtRead()) {
            txtRead.reader();
        } catch (IOException | NoSuchFieldException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class TxtRead implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("资源释放");
    }

    public void reader() throws IOException,NoSuchFieldException {
        System.out.println("数据读取");
    }
}

It should be noted that when a catch catches multiple exceptions, duplicate exception types cannot occur, nor can one exception type be a subclass of another class.

4. Binary

Starting with Java 7, you can directly specify different hexadecimal numbers.

/**
 * 二进制
 *
 * @author www.codingme.net
 */
public class Binary {
    public static void main(String[] args) {
        // 二进制
        System.out.println("------2进制-----");
        int a = 0b001;
        int b = 0b010;
        System.out.println(a);
        System.out.println(b);
        // 八进制
        System.out.println("------8进制-----");
        int a1 = 010;
        int b1 = 020;
        System.out.println(a1);
        System.out.println(b1);
        // 十六进制
        System.out.println("------16进制-----");
        int a2 = 0x10;
        int b2 = 0x20;
        System.out.println(a2);
        System.out.println(b2);
    }
}

Output results.

------2进制-----
1
2
------8进制-----
8
16
------16进制-----
16
32

5. Numeric underline

Java 7 began to support the use of underscore segmentation when defining numbers, which increased the readability of numbers.

/**
 * 数字下环线
 *
 * @author www.codingme.net
 */
public class NumberLine {
    public static void main(String[] args) {
        int a = 1_000;
        int b = 1_0__0_0_0_____00;
        System.out.println(a);
        System.out.println(b);
    }
}

Get results.

1000
1000000

6. Conclusion

Although Java 7 was released as early as 2011, I found that there are not many new features and syntax that have been used since Java 7. Therefore, my JDK new features series is planned to start from Java 7 and introduce Java 13 that has been released so far. When the new Java version is updated in the future, this new features series will continue to be updated.

The mountains are high and the waters are far away. I hope I can stick to it all the way. I hope you and I can walk together all the way.

< end > personal website: https://www.codingme.net If you love this article, you can pay attention to the official account and grow together. Paying attention to official account recovery resources can not get the most popular Java core knowledge of the whole network: Interview core information.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>