New Features
JDK 1.7 Features:
1) Strings in switch statement
2) try with resource statement
3) Handling multiple exceptions with single catch block
4) Generics type inference
1) Strings in switch statement
2) try with resource statement
3) Handling multiple exceptions with single catch block
4) Generics type inference
This feature allows to write strings in a switch statement.
Example:
class Demo
{
public static void main(String args[])
{
switch(args[0])
{
case "mon": System.out.println("Monday");
break;
case "tue": System.out.println("Tuesday");
break;
case "wed": System.out.println("Wednesday");
break;
case "thu": System.out.println("Thursday");
break;
case "fri": System.out.println("Friday");
break;
case "sat": System.out.println("Saturday");
break;
case "sun": System.out.println("Sunday");
break;
default: System.out.println("Invalid")
}}
}
2) try with resource statement:
This feature allows to write a resource with try block.
A class that implements java.io.Closeable interface
or java.lang.AutoCloseable interface only can be
used as a resource.
Syntaxes:
1) try(resource)
{
========
========
}
2) try(resource1; resource2; .......)
{
========
========
}
The above resources are closed automatically even
exception occurs in a program.
This feature is an alternative to a finally block.
Example:
import java.io.*;
class ReadDemo
{
public static void main(String args[])
{
try(FileInputStream fis=
new FileInputStream(args[0])){
int n=fis.available();
byte[] b=new byte[n];
fis.read(b);
String s=new String(b);
System.out.println(s);
}catch(Exception e)
{
System.err.println(e);
}
}
}
Handling multiple exceptions with single catch block:
This feature allows to write more than one exception
in a catch block to handle.
Example:
try
{
}catch(IOException | InterruptedException e)
{
}
Generics Type Inference:
This feature allows write generic object in a new way.
Example1:
ArrayList<Integer> al=new ArrayList<Integer>();
The above statement can be written from JDK 1.7
onwards as follows:
ArrayList<Integer> al=new ArrayList<>();
Example2:
HashMap<Integer, String> hm=
new HashMap<Integer, String>();
The above statement can be written from JDK1.7
onwards as follows:
HashMap<Integer, String> hm=new HashMap<>();
JDK 1.8 Features:
Default methods in interface:
This feature allows to write concrete instance method
in interface by prefixing default keyword.
Static methods in interface:
This feature allows to write concrete class method
in interface.
The above two features are introduced in JDK 1.8
version in 2014.
Example:
interface Test
{
default void show()
{
System.out.println("show() method");
}
static void print()
{
System.out.println("print() method");
}
}
class Demo implements Test
{
public static void main(String args[])
{
Test.print();
Test t=new Demo();
t.show();
}
}