Document new features of Java7 language

Although I have been doing JAVA development for several years, the systems developed for work reasons are all developed under java6. I recently looked at the grammar of kotlin. There are some things in the grammar that really caught my eye. I was developing with java6 before. There are better solutions in kotlin that are troublesome to deal with, such as null safety, method and property coverage, lambda expression syntax, if is an expression and in java is a statement, and expressions can bring the benefits of expressions , the list goes on and on. So let me have a look at the new features of the version after java6.

Record the new features of the JavaSE7 language:

Official website reference address: https://docs.oracle.com/javase/7/docs/technotes/guides/language/enhancements.html

Binary representation of integer types

In Java SE7 integer types (byte, short, int and long) can also be represented using the binary number system. To specify a binary literal, prefix the value with 0b or 0B. The hexadecimal value means adding 0x

E.g:

// an 8-bit value of type 'byte':
byte aByte = (byte)0b00100001;

// a 16-bit value of type 'short':
short aShort = (short)0b1010000101000101;

// a 32-bit value of type 'int':
int anInt1 = 0b10100001010001011010000101000101;

// A 64-bit value of type 'long'. Longs end in L:
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

Underscore in numeric literals

You can use underscore (_) to make numeric constants more readable. The following example shows valid underscores in numeric literals:

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 	3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

The following points are easy to understand where underscores cannot be placed in the following places in numeric literals:

  1. at the beginning or end of a number
  2. adjacent to the decimal point in floating point numbers
  3. before the F or L suffix
  4. It is impossible to add 0_x7fff in 0x7fff like this

Use String class in expression of switch statement

E.g:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

Infer generic type parameters

You can replace a generic parameter with an empty pair of angle brackets <> as long as the compiler can infer the type parameter from the context. You can use type inference only if the parameterized type of the constructor is explicitly declared in the context, otherwise you can't.

E.g:

Map<String, List<String>> myMap = new HashMap<>();
Map<String, List<String>> myMap = new HashMap();// compile warning

try-with-resources statement

try-with-resources is a try statement that defines one or more resources. This resource is the object that needs to be closed after the program has processed it. try-with-resources ensures that each resource is closed after processing is complete. 
Any object that implements the java.lang.AutoCloseable and java.io.Closeable interfaces can use try-with-resources resources.
The classes java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statement, and ResultSet implement the AutoCloseable interface and can be used in try-with-resources statements.

E.g:

public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {

    java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
    java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with try-with-resources statement

    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {

      // Enumerate each entry

      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

        // Get the entry name and write it to the output file

        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
      }
    }
}

Before JAVA7, the closing of resources was in finally, the purpose is to see whether the development has the awareness of closing the resources used for application.

Catch multiple exceptions and re-throw after adding type checking

In Java SE7, a catch can catch multiple exceptions, and each exception is separated by |.

......
catch (IOException|SQLException ex) {
    logger.log(ex);
throw ex;
}
JavaSE7 can more accurately analyze the type of exception you throw, and you can throw more specific exception types on throws, which is not possible in JavaSE7.
public void rethrowException(String exceptionName) throws FirstException, SecondException {
	try {
		// ...
	} catch (Exception e) {
		throw e;
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325836842&siteId=291194637
Recommended