Your SlideShare is downloading. ×
Java 7 new features
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Java 7 new features

2,302
views

Published on

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.... …

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

Published in: Technology, News & Politics

3 Comments
2 Likes
Statistics
Notes
No Downloads
Views
Total Views
2,302
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
94
Comments
3
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • It can be used like a comma generally used for punctuation in numbers or separating a number in groups only for readability purposes 0xCAFEBABE is in the class file format, and 0xCAFEDEAD is in the persistent object format.
  • Underscore can’t be used in following scenarios
  • float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal point float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point long socialSecurityNumber = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffix int x1 = _52; // This is an identifier, not a numeric literal int x2 = 5_2; // OK (decimal literal) int x3 = 52_; // Invalid; cannot put underscores at the end of a literal int x4 = 5_______2; // OK (decimal literal) int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefix int x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a number int x7 = 0x5_2; // OK (hexadecimal literal) int x8 = 0x52_; // Invalid; cannot put underscores at the end of a number int x9 = 0_52; // OK (octal literal) int x10 = 05_2; // OK (octal literal) int x11 = 052_; // Invalid; cannot put underscores at the end of a number
  • Paste an example for 3 rd advantage as well
  • 1. public static final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001, 0b00010011, 0b00100110, 0b01001100, 0b10011000 } In hexadecimal, the relationship among the numbers is not readily apparent: public static final int[] phases = { 0x31, 0x62, 0xC4, 0x89, 0x13, 0x26, 0x4C, 0x98 } 2. public State decodeInstruction(int instruction, State state) { if ((instruction & 0b11100000) == 0b00000000) { final int register = instruction & 0b00001111; switch (instruction & 0b11110000) { case 0b00000000: return state.nop(); case 0b00010000: return state.copyAccumTo(register); case 0b00100000: return state.addToAccum(register); case 0b00110000: return state.subFromAccum(register); case 0b01000000: return state.multiplyAccumBy(register); case 0b01010000: return state.divideAccumBy(register); case 0b01100000: return state.setAccumFrom(register); case 0b01110000: return state.returnFromCall(); default: throw new IllegalArgumentException(); } } else { final int address = instruction & 0b00011111; switch (instruction & 0b11100000) { case 0b00100000: return state.jumpTo(address); case 0b01000000: return state.jumpIfAccumZeroTo(address); case 0b01000000: return state.jumpIfAccumNonzeroTo(address); case 0b01100000: return state.setAccumFromMemory(address); case 0b10100000: return state.writeAccumToMemory(address); case 0b11000000: return state.callTo(address); default: throw new IllegalArgumentException(); } } } 3. public static final short[] HAPPY_FACE = { (short)0b0000011111100000; (short)0b0000100000010000; (short)0b0001000000001000; (short)0b0010000000000100; (short)0b0100000000000010; (short)0b1000011001100001; (short)0b1000011001100001; (short)0b1000000000000001; (short)0b1000000000000001; (short)0b1001000000001001; (short)0b1000100000010001; (short)0b0100011111100010; (short)0b0010000000000100; (short)0b0001000000001000; (short)0b0000100000010000; (short)0b0000011111100000; }
  • The Closeable interface extends theAutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all. Multiple resource declarations are separated by semicolon(;) in try() Normal catch and finally block could be used as well in the same manner as prior to Java 7.0
  • However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the tryblock; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, we can retrieve suppressed exceptions.
  • Transcript

    • 1. JAVA 7.0 NEW FEATURES AN OVERVIEW
    • 2. 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
    • 3. 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;
    • 4. 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
    • 5. 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_;
    • 6. 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.
    • 7. 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;
      • }
    • 8. 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;
    • 9. 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.
    • 10. 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;
      • }
    • 11. 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.
    • 12. 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;
      • }
      • }
    • 13. 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;
      • }
      • }
    • 14. 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;
      • }
      • }
    • 15. 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.
    • 16. 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.
    • 17. 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
    • 18. 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();
      • }
      • }
    • 19. 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.
    • 20. 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
    • 21. 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(&quot;A&quot;);
      • // 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);
    • 22. 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
    • 23.
      • Thanks !!
      • Any Queries ??
      • Write to
      • [email_address]