JDK 1.7 (Java SE 7 or Java 7), code named as Dolphin was released on July 28, 2011.
As on today (Sept 1, 2013) the latest update 25 of Java 7 was released on June 18, 2013.
Following is the list JDK 1.7 Features added, of daily importance.
1. String in Switch Expression
2. Underscores Between Digits in Numeric Literals
3. Integral Types as Binary Literals
4. Handling multiple exceptions in a single catch block
5. Try-with-resources Statement
6. Automatic Type Inference in Generic object instantiation
1. String in Switch Expression
Earlier to JDK 1.7, switch expression takes int values or convertible to int. From JDK 1.7, switch accepts string objects also as expression.
public class SwitchStrings
{
public static void main(String args[])
{
String str1 = "August";
String str2 = "";
switch(str1)
{
case "January": str2 = "1st"; break;
case "February": str2 = "2nd"; break;
case "March": str2 = "3rd"; break;
case "April": str2 = "4th"; break;
case "May": str2 = "5th"; break;
case "June": str2 = "6th"; break;
case "July": str2 = "7th"; break;
case "August": str2 = "8th"; break;
case "September": str2 = "9th"; break;
case "October": str2 = "10h"; break;
case "November": str2 = "11th"; break;
case "December": str2 = "12th"; break;
}
System.out.println(str1 + " is " + str2 + " month in the year");
}
}
The switch can be used also as follows while accessing command-line arguments.
public class SwitchStrings
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();
for(String str : args)
{
switch(str)
{
case "Idly": sb.append(str +", "); break;
case "Dosa": sb.append(str +", "); break;
case "Puri": sb.append(str +", "); break;
case "Vada": sb.append(str); break;
default: sb.append("No breakfast menu");
}
}
System.out.println("Your breakfast menu: " + sb);
}
}
Switch does case-sensitive comparison with case statements. Switch gives a more efficient and cleaner code than if-else if-else code.
2. Underscores Between Digits in Numeric Literals
Underscores are permitted in numeric literals. You can place underscores where you feel required to increase readability; like between hundreds and thousands, thousands and lakhs etc.
This is used to group numbers in a bigger literal value (especially of long data type).
Note: Do not place underscore at the beginning or ending of the literal value.
public class Demo
{
public static void main(String args[])
{
int flatCost = 48_87_653;
float buildingCost = 6_47_812.25_67f;
System.out.println("Flat cost Rs. " + flatCost);
System.out.println("Building cost Rs. " + buildingCost);
}
}
Note: But following does not work (cannot parse with underscores).
String str ="12_34";
int x = Integer.parseInt(str);
The above parsing raises NumberFormatException.
3. Integral Types as Binary Literals
With JDK 1.7, the integer whole numbers like byte, short, int and long can be expressed in binary format also with a prefix of 0b or 0B. Earlier, we have 0 prefix for octal and 0x prefix for hexa and no prefix for binary. JDK 1.7, introduced 0b to represent binary literals.
public class Demo
{
public static void main(String args[])
{
int mangoCost = 0b00111011;
System.out.println("Mango cost Rs. " + mangoCost);
int intValue = 0b100_000_01;
byte byteValue = (byte) 0b10000001;
System.out.println("0b10000001 as int: " + intValue);
System.out.println("0b10000001 as byte: " + byteValue);
}
}
The mango cost statement can be written as follows also with underscores.
int mangoCost = 0b001_110_11;
4. Handling multiple exceptions in a single catch block
Before JDK 1.7, it is required to write multiple catches to handle different exceptions raised in the code. Now in a single catch statement, multiple exceptions can be included separated by pipe ( | ) symbol.
Following is the earlier to JDK 1.7 code which you are well familiar with.
public class Demo
{
public static void main(String args[])
{
int b =0, x[] = { 10, 20, 30 };
try
{
int c = x[3]/b;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
The above multiple catches can be replaced with single catch as follows in JDK 1.7.
public class Demo
{
public static void main(String args[])
{
int b =0, x[] = { 10, 20, 30 };
try
{
int c = x[3]/b;
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
Observe the pipe symbol.
catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
Note: Following does not work:
try
{
int x = 10/0;
}
catch(ArithmeticException | RuntimeException e) { }
Super class exception must be caught separately (it is a constraint).
5. Try-with-resources Statement
(try statement defining resources)
With JDK 1.7, no finally block is required to close (with close() methods) the resources of files or sockets or JDBC handles (objects) etc. The resources (say objects) opened in try block automatically close when the execution control passes out try block (say, at the close brace of try block).
Your Earlier code:
import java.io.*;
public class Demo
{
public static void main(String args[])
{
FileReader fr = null;
FileWriter fw = null;
try
{
fr = new FileReader("abc.txt");
fw = new FileWriter("def.txt");
// some file copying code
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(fr != null) fr.close();
if(fw != null) fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
Your Present code with JDK 1.7:
import java.io.*;
public class Demo
{
public static void main(String args[])
{
try (
FileReader fr = new FileReader("abc.txt");
FileWriter fw = new FileWriter("def.txt");
)
{
// some file copying code
} // at this point fr and fw are closed
catch (IOException e)
{
e.printStackTrace();
}
}
}
A new interface AutoCloseable is introduced with JDK 1.7 for this purpose.
public interface java.lang.AutoCloseable
{
public abstract void close() throws java.lang.Exception;
}
Any resource (class) that implements interface "java.lang.AutoCloseable" is eligible as a resource statement to write in try block. From JDK 1.7, many classes implement AutoCloseable interface, like BufferedReader, PrintStream, Scanner, Socket etc.
The close() method of AutoCloseable is called implicitly to close the handles. Observe, the close() method throws Exception which you may or may not catch if your code does not demand, or replace with problem specific exception class. In the above code, I used IOException. Note that close() method java.lang.Closeable interface is very different from this.
JDBC 4.1 can make use of this try-catch-resource management. Following is the snippet of code.
try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
PreparedStatement pst = con.prepareStatement("update Employee set empsal=empsal+500 where empid=?");) {
pst.setInt(1, 100);
int x = pst.executeUpdate();
System.out.println("No. of records inserted: " + x);
}
}
catch (SQLException ex)
{
ex.printStackTrace();
}
6. Automatic Type Inference in Generic object instantiation
(Diamond operator, <> , in collection classes)
In JDK 1.7, empty angle brackets (known as diamond operator), <>, can be used in specifying generic type instead of writing the exact one. But remember, the compiler should be able to judge the type from the generics statement you write.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
// List namesList = new ArrayList(); // Earlier style before JDK 1.7
List namesList = new ArrayList<>(); // JDK 1.7 style
namesList.add("India S N Rao");
namesList.add("Canada Jyostna");
namesList.add("USA Jyothi");
for (String name: namesList)
{
System.out.println(name);
}
}
}
Other improvements are in the fields of java.nio, Phasers and TransferQueue in Concurrency API, Pools and Tasks in Fork Join Framework, java.util.ThreadLocalRandom, ClassLoader Improvements – Deadlock Avoidance, URLClassLoader Improvements, Unicode 6.0 to include thousands of new characters to support Japanese Telcos and Indic scripts, Extensible Currency Codes, NumericShaper for number shaper enhancements, Locale enhancement – Categories, Nimbus Look and Feel for Swing components (better than earlier Metal), Standardize JLayer Component for easy enriching Swing components, Standardize Translucent Windows etc. I have not discussed the above as they are are not for daily usage in coding.
7. Static blocks
Earlier to JDK 1.7, to print static blocks no main() method is required. But from JDK 1.7, if no main() exists, static blocks will not be executed.
Would like to see JDK 1.8 Features also?
Refer for all Java Versions.
Following links gets you JDK 1.7 version download
1. http://java.com/en/download/index.jsp
2. http://www.herongyang.com/JDK/JDK-170-Windows-Download-Installation.html
For different miscellaneous topics on Java, refer View All Java Examples
Simple but elegant… Thanks for the nice explanations
Thanks for your great explaination
Please send me each & every update Related to java
nice explanation on new features. :-)
can anyone tell me the special features of java1.7 and does they support the eclipse kepler(software).
nice explanation !!!!!!!!!!
Please take the help of your friend. I do not find time to write queries for all. It is tutorial site and I get hundreds of queries per day. Pl do not think otherwise.
Sir Data Hiding and Encapsulation both same or different?
See this link from way2java.com
http://way2java.com/oops-concepts/what-is-the-difference-between-encapsulation-and-abstraction/
Sorry, this reply is supposed to be posted to a different query.
New features explained with program helps great to understand the concept quickly… thanks
Good explanation of new features,
Thanks for your great answers…!!!