Java 7 Features and Enhancements

Diamond Operator

  • Old code: Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();
  • New code: Map<String, List<Trade>> trades = new TreeMap <> ();

Using strings in switch statements

  • Switch statements work either with primitive types or enumerated types before 1.7

Automatic resource management

  • Resources such as Connections, Files, Input/OutStreams, etc. should be closed manually by the developer. Behind the scenes, the resources that should be auto closed must implement java.lang.AutoCloseable interface.
		try {
			fos = new FileOutputStream("movies.txt");
			dos = new DataOutputStream(fos);
			dos.writeUTF("Java 7 Block Buster");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
				dos.close();
			} catch (IOException e) {
				// log the exception
			}
		}
	}

	public void newTry() {

		try (FileOutputStream fos = new FileOutputStream("movies.txt");
				DataOutputStream dos = new DataOutputStream(fos)) {
			dos.writeUTF("Java 7 Block Buster");
		} catch (IOException e) {
			// log the exception
		}
	}

Numeric literals with underscores

  • 1000000 (one million) as follows: int million  =  1_000_000

Improved exception handling

	public void newMultiCatch() {
		try {
			methodThatThrowsThreeExceptions();
		} catch (ExceptionOne | ExceptionTwo | ExceptionThree e) {
			// log and deal with all Exceptions
		}

	}

	public void newMultiMultiCatch() {
		try {
			methodThatThrowsThreeExceptions();
		} catch (ExceptionOne e) {
			// log and deal with ExceptionOne

		} catch (ExceptionTwo | ExceptionThree e) {
			// log and deal with ExceptionTwo and ExceptionThree
		}

	}

	public void oldMultiCatch() {
		try {
			methodThatThrowsThreeExceptions();
		} catch (ExceptionOne e) {
			// log and deal with ExceptionOne
		} catch (ExceptionTwo e) {
			// log and deal with ExceptionTwo
		} catch (ExceptionThree e) {
			// log and deal with ExceptionTwo
		}
	}

New file system API (NIO 2.0)

  • File change notifications using WatchService API

Fork and Join
Supporting dynamism

Ref:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s