Change Features and Improvements in Java 7

We have already covered many change features and Improvements in Java 7 that were new in the release. In this article, I will create a summary of it so that anyone interested can take a quick look at all the features.

Improved type inference

Before Java 7, when you used generics, you had to supply type parameters for the types of variables and their actual types. Now it has been a bit easier in this new Java 7 feature, and a blank diamond on the right side of the statement will work fine.

The Java 7 compiler is smart enough to recognize that empty diamonds indicate the type defined on the left side of the declaration.

public class ElvisOperatorTest {
    public static void main(String[] args) {
        @SuppressWarnings("unused")
        Map params = new HashMap<>();
    }
}

Automatic resource management with try-with-resources

Before Java 7, we had to use finally blocks to clean up resources. Eventually, the blocks did not require, but cleaning up the resources had to prevent damage to the system. With Java 7, no explicit resource cleanup require. It happens automatically. When resources initialize in the try-with-resources block (try (…) {…}), automatic resource cleanup is carrie out.

The cleanup is based on the new AutoCloseable interface, which is the close method is called by the JVM as soon as they try block ends. You shouldn’t call the close () method in your code. This must be called automatically by the JVM. A manual call can lead to unexpected results.

public class Resource_Management_In_Java7
{
    public static void main(String[] args)
    {
        try (BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt")))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null)
            {
                System.out.println(sCurrentLine);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

NIO 2.0

Java SE 7 introduced the java.nio.file package and the associated java.nio.file.attribute the package provides full support for file I / O and file system access by default. The Path class was an important addition that allowed you to represent every path in the operating system in a consistent way. The new APIs complement the old ones and provide several useful methods for reviewing, deleting, copying, and moving files. The new JDK 7 file API is also able to search for files using wildcards/regex. You can also get help with monitoring changes to a directory.

Go ahead and explore all of these changes on the linked websites.

Exception handling improvements
Java 7 also made some interesting improvements to exception handling. These can be roughly divided into two characteristics:

Suppress Exception

Thrown exceptions, as the name suggests, are exceptions that are thrown in code but kind of ignored. If you remember the execution order of the try-catch-finally block and how they return a value or exceptions, you will remember that the exceptions thrown in the final block are thrown even though an exception is thrown in the try block becomes. Prior to Java 7, logging in would notify you of these exceptions when they were implemented, but you had no control over these exceptions after the last block was completed. With the new features in Java 7, you also have control over these suppressed exceptions

Below is an application example:

public class Suppress_Exception_Demo_With_Try_Finally_New
{
    /**
    * Executable member function demonstrating suppressed exceptions
    * Suppressed expression is added back in primary exception
    */
    public static void memberFunction() throws Exception
    {
        Throwable th = null;
        DirtyResource resource= new DirtyResource();
        try
        {
              resource.accessResource();
        }
        catch(Exception e)
        {
            th = e;
            throw e;
        }
        finally
        {
            try
            {
                resource.close();
            }
            catch(Exception e)
            {
                if(th != null)
                {
                    e.addSuppressed(th); //Add to primary exception
                    throw e;
                }
            }
        }
    }
   /**
    * Executable function demonstrating suppressed exceptions.
    */
   public static void main(String[] arguments) throws Exception
   {
      try
      {
          memberFunction();
      }
      catch(Exception ex)
      {
          err.println("Exception encountered: " + ex.toString());
          final Throwable[] suppressedExceptions = ex.getSuppressed();
          final int numSuppressed = suppressedExceptions.length;
          if (numSuppressed &gt; 0)
          {
              err.println("tThere are " + numSuppressed + " suppressed exceptions:");
              for (final Throwable exception : suppressedExceptions)
              {
                  err.println("tt" + exception.toString());
              }
          }
      }
   }
}

Output

Exception encountered: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!
    There are 1 suppressed exceptions:
        java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!!

Learn more about a related article.

Catch multiple exceptions in the catch block

In this function, you can now catch multiple exceptions in a single catch block. Before Java 7, you were limited to capturing just one. A pipe character (‘|’) is used to specify the list of expected exceptions.

Let’s understand it through an example.

try
{
  //Do some processing which throws NullPointerException; I am sending directly
       throw new NullPointerException();
}
 
//You can catch multiple exception added after 'pipe' character
catch(NullPointerException | IndexOutOfBoundsException ex)
{
       throw ex;
}

Remember, when a catch block handles multiple types of exceptions, the catch parameter is implicitly final. In this example, the catch ex final parameter, so you cannot assign values to it in the catch block.

Improved number formatting

When you need to read the number “1000000”, how convenient it is to read the first page. Not much, is it? We’re used to reading numbers in 10,000,000 formats. The good news is that Java has started to support writing numbers in this format. Well, not exactly that, but a format to match.

You can now write the above number like this: 10_00_000.

/**
 * Supported in int
 * */
int improvedInt = 10_00_000;
/**
 * Supported in float
 * */
float improvedFloat = 10_00_000f;
/**
 * Supported in long
 * */
float improvedLong = 10_00_000l;
/**
 * Supported in double
 * */
float improvedDouble = 10_00_000;

Support for the String class in a switch statement

If you remember the switch statement before Java 7, it only supported int and enum types. With the Java 7 release, support for the String class has also been added. Let’s look at this with an example.

switch (token)
{
    case ("one"):
        return "Token one identified";
 
    case ("two"):
        return "Token one identified";
 
    case ("three"):
        return "Token one identified";
 
    case ("four"):
        return "Token one identified";
 
    default:
        return "No token was identified";
}

Binary literals with the prefix “0b”

In JDK 7, you can express literal values ​​in binary with the prefix “0b” (or “0B”) for integer types (byte, short, int, and long). Before JDK 7, you could only use octal values ​​(with the prefix “0”) or hexadecimal values ​​(with the prefix “0x” or “0X”). For example

int sameVarOne = 0b01010000101;
 
or if use the number formatting feature as well.
 
int sameVarTwo = 0B01_010_000_101;

ForkJoin Frame

The efficient use of parallel cores in a Java program has always been a challenge. There were only a few self-developed frameworks that spread the work across multiple cores and then combine them to return the result set. Java 7 has integrated this function as a fork-and-join framework.

Basically, the fork join divides the task at hand into mini-tasks until the mini-task is so simple that it can be solved without further interruptions. It’s like a divide and conquers algorithm. An important concept to keep in mind in this context is that ideally, no worker thread is idle. They implement a job theft algorithm in which inactive workers steal the work of busy workers.

It is based on the work of Doug Lea, a thought leader in the Java competition. Fork / Join takes care of threading issues; You just tell the framework which parts of the work can be separated and processed recursively. It uses a pseudo-code (taken from Doug Lea’s article on the subject):

Result solve(Problem problem) {
	if (problem is small)
		directly solve problem
	else {
		split problem into independent parts
		fork new subtasks to solve each part
		join all subtasks
		compose result from subresults
	}
}

Automatic reloading with WatchService

Each application has a configuration that must be updated every time the configuration file is changed. Previous approaches to solving this problem were to use a thread that periodically requests file changes based on the “last updated timestamp” in the configuration file.

Change Features and Improvements in Java 7, things have changed. Java 7 introduced a cool feature: WatchService. WatchService is an internal JDK service that monitors changes to registered objects. These registered objects are necessarily the instances of the observable interface. When registering the observable instance with WatchService, we need to specify the type of change events we are interested in.

For an example of using WatchService, see the related article.

Garbage collector G1
JDK 7 introduced a new garbage collector called G1 Garbage Collection, which was initially short for garbage. The G1 Garbage Collector cleans up where most garbage is. To achieve this, it divides the Java heap memory into multiple regions, as opposed to 3 regions before Java version 7 (newer, old, and permanent memory). G1 is fairly predictable and offers higher throughput for memory-intensive applications.

That’s all brief summary of change Features and Improvements in Java 7.

Please share this post:
Posts created 48

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: