Colleagues also read the code? Come up syntax features a wave of Java 7

Foreword

Java platform since appeared so far, has more than 20 years, it has been 20 years Java programming language as one of the most popular, and constantly faced with the challenges and the impact of other emerging programming languages. Java is a static strongly typed language, such a language feature allows Java compiler at compile phase error is found, which for building a stable and secure and robust applications, it is particularly important. But also because of this feature, allow Java developers seem to become less flexible, development and application of certain functions, may be several times the amount of code in other languages. The shortcomings of Java development is also reflected on the increasingly complex JDK, increasingly complex JDK let developers fully understand the difficulty becomes very large. So that developers can sometimes achieve a repeat JDK functionality already provided.

In order to keep pace with the development of Internet applications programming, Java version from 9 began to adjust the tempo of the JDK, JDK each update are focused on improving production efficiency , improve JVM performance , the implementation of modular , so that developers can focus more the business itself, rather than wasting too much time on the language features. Update the Java language to be found on the rigor and flexibility of a language balance, after all, flexibility can reduce the complexity of coding, but rigor is to build complex and robust applications cornerstone.

Java 7 language features

Java is a significant increase in the updated version of Java 5 version, this version of such generics, enhanced for, automatic boxing and unboxing, a series of enumerated types, variable parameters, notes and other important functions , but then in the Java 6 and no new major language features. Java 5 was released in 2004, it has been very long, and online tutorials on Java are also mostly based on Java 6, and therefore I am going to start from Java 7 introduces new features in each version of Java.

Run demonstrate all of the following code is based on the Java 7 , so if you try the following code, you need to install and configure Jdk 1.7 or already on version.

1. switch String

Before Java 7, switch only supports integer syntax type integer and these types of packages is determined classes, in Java 7, support string String type determination, is very simple to use, but the practicality is high.

1.1. Switch String basic usage

Write a simple string determination test class switch.

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("你好");
        }
    }
}

switch judgment string is simple to use, the results are obvious will first output hashCode gender variables, then matching result output "Hello sir."

30007
先生你好

In the string when using the switch, if combined with Java 5 enumeration class, then the effect will be better, use the enumeration class digital code to be compiled for each value before Java 7, Java 7 can be defined directly after the string name.

1.2. Switch String implementation principle

But this support is just the compiler level of support , JVM is still not supported. When the string switch, the compiler will convert the string to an integer type then determined. In order to verify says only compiler level of support, we decompile (Jad decompiler tool can be used, you can also double-click the class compiled in Idea in) generated class file, see the compiler to switch string converted to character string hashCode judgment, in order to prevent conflict hashCode, and equals judge used 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 differs from C ++, developers need to manage each piece of memory, most of the time the Java virtual machine can be a good resource to help us manage, but also sometimes need to manually free up some resources, such as database connections, disk file access, network connections, etc. . In other words, as long as the limited amount of resources, we need to be manually released.

2.1. try-catch-finally

When operating with limited resources, various exceptions may occur, whether it is reading stage or in the process of final closure resource, there may be problems, we usually use the following way try-catch-finallyto 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 the exception, we write a catch, in order to ensure the release of resources, we wrote a finallyresource release, when resources are released in order to capture the closethrown exception, we wrote a try-catch. Finally, look at this complex code, if someone told you have this code bug, you will not believe. But indeed it seemed so strict code logic, when the trycode logic and the closemethod when an abnormality occurs at the same time, trythe abnormality information is lost.

You can see an 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("关闭异常");
    }
}

Clearly code readand closemethods generate an exception, but run the program found only receive closeinformation about the exception.

资源关闭
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)

Abnormal loss of information , and the frightening thing is that you thought it was only closewhen an abnormality has occurred only.

2.2. try-autocloseable

The above problems in Java 7 is already providing new solutions, in Java 7 to trybe enhanced to ensure that resources can always be properly released . Using enhanced trythe premise that trythe class implements AutoCloseablethe interface, operating in Java 7 release of resources in a large number of needs in fact already implements this interface up.

AutoCloseable implementation class

To achieve a AutoCloseableclass at enhancing trythe use of, do not worry shut resources, the call will automatically use the completed closemethod, and an exception is not lost .

Let us write the class analog resources to achieve operational AutoCloseableinterface and enhanced time tryto see results.

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 已连接");
    }
}

Mysql and OracleDatabase test class are realized AutoCloseable, run see the results.

mysql 已连接
OracleDatabase 已连接
OracleDatabase 已关闭
mysql 已关闭

Confirmed abnormal when abnormal information is not lost, write a simulation of abnormal test class 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 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)

Automatically shut down, very clear, there is an exception to shut down Suppressed, called to suppress abnormal, follow-up article will detail.

3. try-catch

Before Java 7, a catch can catch an exception information, when so many types of abnormal time is very troublesome, but in Java 7, a catch multiple exceptions can capture information, use exception caught between each |division,

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("数据读取");
    }
}

Note that, when capturing a plurality of catch exceptions, repeated exception type can not occur, nor an exception type is a case where a subclass of another class.

4. Binary

Java 7 start, you can specify a different hexadecimal numbers directly.

  1. Binary specify numeric values, only you need to use 0bor OBat the beginning.
  2. Octal value specified number, use 0the beginning.
  3. Specified in hexadecimal numeric values, use 0xthe beginning.
/**
 * 二进制
 *
 * @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.

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

The figures underscore

Java 7 support the use of an underscore start in the digital segmented defined time, increasing numbers of readability.

/**
 * 数字下环线
 *
 * @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);
    }
}

got the answer.

1000
1000000

6. Conclusion

Although Java 7 as early as 2011 has been released, but as far as I found, to use the new features of Java 7 to start the new syntax is not much, so my new series of articles JDK Java program from the beginning 7, has been introduced to the current It has released Java 13, after the new version of the Java updates at the same time, this new series of articles will be continuously updated.

This went high mountains far, is willing to stick all the way, I wish you a ride.

<Ends>
Website: https://www.codingme.net
If you enjoyed this article, you can focus the public number, grow together.
No public attention can not respond to routine access to resources of the whole network hottest knowledge of core Java interview finishing & core information.
the public

Guess you like

Origin www.cnblogs.com/niumoo/p/12164767.html