Java 7 new features

23
JAVA 7.0 NEW JAVA 7.0 NEW FEATURES FEATURES AN OVERVIEW AN OVERVIEW

description

This is targeted to be a short tutorial for familiarising the new programming concepts introduced in Java 1.7 or Java 7.0 I contains working code snippets to familiarise with new syntax as well.... Hope you will like it !!!! h

Transcript of Java 7 new features

Page 1: Java 7 new features

JAVA 7.0 NEW FEATURESJAVA 7.0 NEW FEATURESJAVA 7.0 NEW FEATURESJAVA 7.0 NEW FEATURES

AN OVERVIEWAN OVERVIEW

Page 2: Java 7 new features

New Language features in Java 7.0

• Underscores in Numeric Literals• Strings in switch Statements• Binary Literals• Catching Multiple Exception Types• Rethrowing Exceptions with Improved Type

Checking• The try-with-resources Statement• Type Inference for Generic Instance Creation

Page 3: Java 7 new features

Underscores in Numeric Literals

• In Java SE 7, Any number of underscore(_) can appear anywhere between digits in numeric literal.

• The advantage of this feature is to improve the readability of the numeric literals. Compiler ignores these underscores.

• Few Valid Examples– long creditCardNumber = 1234_5678_9012_3456L;– 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;

Page 4: Java 7 new features

Underscores in Numeric Literals

• Underscore can’t be used in following scenarios

• At the beginning or end of a number

• Adjacent to a decimal point in a floating point literal

• Prior to an F or L suffix

• In positions where a string of digits is expected like 0x

Page 5: Java 7 new features

A little Quiz – Valid or Invalid

• float pi1 = 3_.1415F;• float pi2 = 3._1415F;• long socialSecurityNumber = 999_99_9999_L;• int x1 = _52;• int x2 = 5_2;• int x3 = 52_;• int x4 = 5_______2;• int x5 = 0_x52;• int x6 = 0x_52;• int x7 = 0x5_2;• int x8 = 0x52_;• int x9 = 0_52;• int x10 = 05_2;• int x11 = 052_;

Page 6: Java 7 new features

Strings in switch Statements

• In Java SE 7, String object can also be used in the expression of switch statement.

• Uses String.equals() method to compare String object expression and expression in case labels.

• Advantages :• No need to write too many if-else statements• JVM generates efficient bytecode for switch than

multiple if-else statements• Various different type of objects also could be used

depending on their implementation of toString() method.

Page 7: Java 7 new features

An Example• 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;• }

Page 8: Java 7 new features

Binary Literals• In Java SE 7,  the integral types (byte, short, int, and long) can also be expressed using the

binary number system. • To specify a binary literal, add the prefix 0b or 0B to the number.• Examples• // An 8-bit 'byte' value:• byte aByte = (byte)0b00100001;

• // A 16-bit 'short' value:• short aShort = (short)0b1010000101000101;

• // Some 32-bit 'int' values:• int anInt1 = 0b10100001010001011010000101000101;• int anInt2 = 0b101;• int anInt3 = 0B101; // The B can be upper or lower case.

• // A 64-bit 'long' value. Note the "L" suffix:• long aLong =

0b1010000101000101101000010100010110100001010001011010000101001L;

Page 9: Java 7 new features

Binary Literals• Advantages (See footnotes for examples):

• Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal.

• We can use binary integral constants in code that you can verify against a specifications document, such as a simulator for a hypothetical 8-bit microprocessor.

• We can use binary literals to make a bitmap more readable.

Page 10: Java 7 new features

Catching Multiple Exception Types

• The catch clause can specify the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

• Prior to Java 7.0• catch (IOException ex) {• logger.log(ex);• throw ex;• catch (SQLException ex) {• logger.log(ex);• throw ex;• }• In Java 7.0• catch (IOException|SQLException ex) {• logger.log(ex);• throw ex;• }

Page 11: Java 7 new features

Catching Multiple Exception Types

Contd…• Advantages• Contains less duplicate code and ultimately reduced

amount of bytecode.• Bytecode generated by compiling a catch block that

handles multiple exception types will be smaller and thus superior.

• Constraint• If a catch block handles more than one exception type,

then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Page 12: Java 7 new features

Rethrowing Exceptions with More Inclusive Type

Checking• Prior to Java 7.0 if we had to rethrow an exception from a method then we will have to do

either of the following ways• Putting multiple catch blocks

• public void rethrowException(String exceptionName) throws FirstException,SecondException {

• try {• if (exceptionName.equals("First")) {• throw new FirstException();• } else {• throw new SecondException();• }• } catch (FirstException e) {• throw e;• } catch (SecondException e) {• throw e;• }• }

Page 13: Java 7 new features

Rethrowing Exceptions with More Inclusive Type

Checking Contd…• 2. Widening the Exception i.e. catching parent Exception class• public void rethrowException(String exceptionName) throws

Exception {• try {• if (exceptionName.equals("First")) {• throw new FirstException();• } else {• throw new SecondException();• }• } catch (Exception e) {• throw e;• }• }

Page 14: Java 7 new features

Rethrowing Exceptions with More Inclusive Type

Checking Contd…• Now Java 7.0 has improved in a way that you can catch wide level of

Exception and still keep the narrow exceptions in method defination. Just like below code

• public void rethrowException(String exceptionName) throws FirstException,SecondException {

• try {• if (exceptionName.equals("First")) {• throw new FirstException();• } else {• throw new SecondException();• }• } catch (Exception e) {• throw e;• }• }

Page 15: Java 7 new features

Rethrowing Exceptions with More Inclusive Type

Checking Contd…• Advantages :• Fewer lines of code• Calling method of rethrowException(String s)

has to only catch narrow and specific exception• Compiler can determine that the exception

thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException

• This analysis is disabled if the catch parameter is assigned to another value in the catch block.

Page 16: Java 7 new features

Rethrowing Exceptions with More Inclusive Type

Checking Contd…• In Java SE 7 and later, when we declare one or more

exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

• The try block is able to throw it.• There are no other preceding catch blocks that can

handle it. • It is a subtype or supertype of one of the catch clause's

exception parameters.

Page 17: Java 7 new features

try-with-resources• A resource is defined as an object that must be closed after the program is

finished with it like streams, connections etc.• Any object that implements java.lang.AutoCloseable or java.io.Closeable

interface, can be used as a resource• The try-with-resources statement is a try statement that declares one or more

resources and closes them automatically even if the block completes abruptly.• Syntax :• try(<resource Declaration A>;<resource Declaration B>;<resource

Declaration C>)• {• …• …• }• catch{} //Use it to catch other exceptions like

IllegalArgumentException• finally{} //For different business logics

Page 18: Java 7 new features

try-with-resources - Example

• public String readFirstLineFromFile(String path) throws IOException {• try (BufferedReader br = new BufferedReader(new FileReader(path))) {• return br.readLine();• }• }

• Java 1.6 code• public String readFirstLineFromFileWithFinallyBlock(String path) throws

IOException {• BufferedReader br = new BufferedReader(new FileReader(path));• try {• return br.readLine();• } finally {• if (br != null) br.close();• }• }

Page 19: Java 7 new features

try-with-resources – Contd…

• Note that the close methods of resources are called in the opposite order of their creation i.e. C , B and then A

• In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

• Connection, ResultSet and Statement of JDBC 4.1 and higher could be used with try-with-resources statement for automatic closure.

• Using try-with-resources statement code can be written precisely without writing obvious lines of code like closing a stream.

Page 20: Java 7 new features

Type Inference for Generic Instance Creation• We can replace the type arguments required to invoke

the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context.

• This pair of angle brackets is informally called the diamond.

• In Java 6.0• Map<String, List<String>> myMap = new

HashMap<String, List<String>>(); • In Java 7.0• Map<String, List<String>> myMap = new

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

unchecked conversion warning

Page 21: Java 7 new features

Type Inference for Generic Instance Creation

Contd…• But Java SE 7 supports limited type inference for generic instance

creation i.e. we can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

• List<String> list = new ArrayList<>();• list.add("A");

• // The following statement should fail since addAll expects• // Collection<? extends String>

• list.addAll(new ArrayList<>());• In comparison, the following example compiles:

• List<? extends String> list2 = new ArrayList<>();• list.addAll(list2);

Page 22: Java 7 new features

Other Good To know Enhancements

• Multithreaded class loading modifies the locking mechanism to avoid deadlock.

• Concurrency The fork/join framework is introduced to efficiently run a large number of tasks using a pool of worker threads

• Supports Unicode 6.0 and can accommodate new currencies that are identified by their ISO 4217 codes

• Java virtual machine support for non-Java languages Java SE 7 introduces a new JVM instruction that simplifies the implementation of dynamically typed programming languages on the JVM.

• Garbage-first collector a server-style garbage collector that replaces the Concurrent Mark-Sweep Collector (CMS).

• Java HotSpot virtual machine performance enhancements

Page 23: Java 7 new features

Thanks !!

Any Queries ??Write to

[email protected]