Java 7 New Features

Java 7: Features & Enhancements

1)    Strings in switch

switch (database) {

case “oracle”:

case “sqlserver”:

break;

case “postgres”:

break;

case “mysql”:

break;

default:

}

2)    try-with-resources statement

try (InputStream is = new FileInputStream(new File(“data.txt”))) {

// read file

// …

}

catch (IOException ex) {

// handle this error

–          try can now have multiple statements in the parenthesis and each statement should create an object which implements the new java.lang.AutoClosable interface. The AutoClosable interface consists of just one method.

void close() throws Exception {}

3)    Throw statement precisely

public void display(String[] args) throws IOException {

try {

loadFileToDb();

} catch (final Exception ex) {

System.err.print(ex.getMessage());

throw ex;

}

4)    Multiple catch statement

try {

doSomething();

} catch (Exception1 | Exception2 ex) {

printException1();

} catch (Exception3 | Exception4 ex) {

printException2();

 

5)    Binary integral literals

–          We can create numerical literals by adding binary notation prefix “0b”

int no = 0b1010;

System.out.println(“no = ” + no);

Output

no = 10

6)    Underscores in numeric literals

–          We  can include underscores in numeric literals to make them more readable. The underscore is only present in the representation of the literal in Java code, and will not show up when you print the value.

int tenMillion = 10_999_999_0;

System.out.println(“Amount is “ + tenMillion);

Output

109999990

7)    Improved type interface for generic instance creation

–          Java 7 tries to get rid of this redundancy by introducing a left to right type inference. You can now rewrite the same statement by using the <> construct.

Map<String, List<String>> retVal = new HashMap<>();

8)    Advanced new I/O API

– This addition is also known as New I/O API (NIO).

See http://download.java.net/jdk7/docs/api/java/nio/file/Files.html

9)    Watch Service

–          It provides an API that lets you “listen” to a certain type of file system events. Your code gets called automatically when those events occur.

–          See http://download.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html

Why Serialization ?

I know java serialization is required when you want to save state of an object outside JVM. My thinking was why don’t Sun make all classes as Serializable by default? Why Serializable interface required to persist an object?

Many of them gave definition as “It tells JVM to serialize object that are ready to transfer over outside JVM, also it make object as JVM independent.”

Understanding on serialization concept in Java.

  1. java.io.Serializable interface doesn’t add any overhead to JVM nor it does any magic in JVM processing.
  2. Using serialization concept an object can be exposed outside jvm it intern exposes private variables’ value which is violation of OOPS concept. By marking a class as Serializable, developers understand the security concern.
  3. JVM serializes complete object navigation graph. Sometime developer might intent to persist only top level object and forget to mark member variables as transient. In this case Serializable interface enforces developer to make conscious decision to persistent required classes.

java.io.Serializable interface is an design decision in Java to enforce developers to make conscious decision before exposing private variable.

To know more about serialization click here…

Hope now you have clear concept about serialization 🙂

New Features and Enhancements J2SE 5.0

New Language Features

o Covariant return types

o Generics

o Enumerated types (enum )

o Auto boxing

o Enhanced for loop

o Variable arguments

o Annotations

o Static imports

New Classes

o java.lang.StringBuilder

o java.lang.Formatter

o java.util.Queue

o java.util.concurrent.*

Static Imports

o    Static imports allow static classes to be  imported.

import static java.lang.System.out;

public class StaticImportTest

{

public static void main(String[] args)

{

out.println(“Hello, world!”);

}

}

o    Static imports also allow the import of static methods and variables.

import static java.util.Arrays.sort; //import sort method

import static java.lang.Math.*; //import static members

public class StaticImportTest {

public static void main(String[] args) {

int[] numbers = {3, 6, 1, 4, 5, 2};

sort(numbers); //sort is method in Arrays class

double d = abs(-15); //abs is method in Math class

}

}

Annotations

o Annotations provide additional information  about the code to the compiler or runtime  environment.

o Annotations are included in the source  code prefaced by the “@” symbol.

o JDK 1.5 includes three standard  annotation types: @Override , @Deprecated , and @SuppressWarnings

o The @Deprecated  annotation indicates  that a method has been deprecated.

o Works in conjunction with the @deprecated  JavaDoc tag that adds  instruction on which method to use  instead.

o Classes that call a deprecated method will  receive a warning at compile time.

o

o @Deprecated public void MyDeprecatedMethod()

o Annotations can include a single argument  or an array of arguments like this:

o @Annotation([name=]value[, …])

o @Annotation([name=]{value[, …]})

o Arguments can include an optional  parameter name.

o The @SuppressWarnings  annotation  turns off specified compiler warnings.

o Defines a single parameter called value .

@SuppressWarnings(value=“unchecked”)

public void nonGenericMethod()

//these formats are also supported

@SuppressWarnings(“unchecked”)

@SuppressWarnings(value={“unchecked”, “fallthrough”})

@SuppressWarnings({“unchecked”, “fallthrough”})

o Custom annotations can be created using the @interface declaration like this:

 

public @interface MyAnnotation {String value(); //defines a single parameter named value

}

@MyAnnotation(“argument value”)

public void myMethod()

o At runtime, custom annotations can be retrieved using reflection (if retention policy is set to RUNTIME).

Variable Arguments

o Variable arguments, or varargs, allow a method to accept any number of arguments.

printNumberList(“Numbers”, 1, 2, 3); //method call

void printNumberList(String header, int… list) {

System.out.println(header);

for (int item : list) {

System.out.println(item);

}

}

o Only one vararg parameter is allowed per  method.

o The vararg must be the last parameter.

o The vararg parameter is implemented as  an array. Therefore, the compiler sees  these methods declarations as equivalent:

void printNumberList(String header, int[] list);

void printNumberList(String header, int… list);

o Since the compiler implements variable arguments using arrays, the vararg can be treated as an array.

void printList(String header, int… list) {

System.out.println(header);

for (int i = 0; i < list.length; i++) {

System.out.println(list[i]);

}

}

Enhanced For loop

o The enhanced for loop eliminates the need to use java.util.Iterator to iterate over a collection.

List<String> list = new ArrayList<String>();

list.add(“One”); list.add(“Two”); list.add(“Three”);

for (String item : list)

{

System.out.println(item);

}

o The enhanced for loop works with any array or collection class that implements the new java.lang.Iterable interface.

o The Iterable interface defines a single method called iterator() that returns a java.util.Iterator object.

o Unlike using Iterator, the enhanced for loop doesn’t allow you to remove items from the list during iteration.

Auto Boxing

o Conversions between primitives and their equivalent wrapper types are now automatic.

 

Integer i = new Integer(10); //without autoboxing

int j = i.intValue(); //without auto-unboxing

 

Integer i = 10; //with autoboxing

int j = i; //with auto-unboxing

i++; //automatically unboxes, increments, and boxes again

 

List list = new ArrayList();

list.add(1); //adds new Integer with a value of 1

int i = list.get(1); //converts Integer to int

 

o Autoboxing supports Boolean types as  well.

Boolean value1 = true;

Boolean value2 = false;

Boolean result = (value1 && value2); //result is false

Boolean result2 = (value1 || value2); //result2 is true

 

o Unboxing can be used in conjunction with  generic types to reduce casting.

 

//without autoboxing

List list = new ArrayList();

list.add(new Integer(42));

int i = ((Integer)list.get(0)).intValue();

 

//with autoboxing

List<Integer> list = new ArrayList<Integer>();

list.add(42);

int i = list.get(0);

Enumerated types

o The new enum  data type allows the  developer to restrict valid values to a  specified set.

o The compiler enforces valid values.

public enum CardSuit {HEARTS, DIAMONDS, CLUBS, SPADES};

public setSuit(CardSuit suit) //method that accepts enum

{ … }

setSuit(CardSuit.CLUBS); //can only be passed a valid suit

o All enum  types extend java.lang.Enum .

o enum  types are classes not integers. This  guarantees type safety.

o enum  types cannot be extended.

o enum  values are public, static, and final.

o enum  values can be compared with ==  or equals() .

o You can switch on enumerated types.

o When switching, there is no need to preface the enum values with the enum class name (in fact, the compiler does not allow it).

switch (card.getSuit()) {

case HEARTS:

System.out.println(“Hearts”);

break;

case DIAMONDS:

System.out.println(“Diamonds”);

break;

// and so on

}

o Since they are classes, you can add constructors and methods to enum types. (Grades.A.getAssessment() returns “Excellent!”)

public enum Grades {

A(1), B(2), C(2), D(3), F(3); //integer values are passed to constructor

private String assessment;

 

Grades(int value) {

switch (value) {

case 1: assessment = “Excellent!”; break;

case 2: assessment = “Not bad.”; break;

case 3: assessment = “Needs improvement!”; break;

}

}

 

public String getAssessment() {

return assessment;

}

}

Generics

o Improves type safety

– Accepts “parameterized types” (parameters that accept data types)

– Allows for compile time type checking

o Eliminates manual type-checking and type-casting

o JDK 1.5’s Java docs indicate the new generic classes.

o E is a “type parameter” for ArrayList. The name “E” is arbitrary. It simply serves as a placeholder that can be replaced with any Java class type.

o The compiler replaces every occurrence of E in the methods with the type that you specify

when the ArrayList is created.

Class ArrayList<E>

boolean add(E e)

E get(int index)

o Type arguments can be specified when an  object is declared/created.

o If an ArrayList is created using a type  argument of “String”, the compiler  enforces that the list can contain only  String objects.

List<String> colors = new ArrayList<String>();

colors.add(“Blue”);

colors.add(“Red”);

colors.add(new Integer(1)); //compile time error

o Using a type argument of “String” with ArrayList and Iterator allows iteration across an ArrayList without any type casts.

List<String> colors = new ArrayList<String>();

colors.add(“blue”);

colors.add(“red”);

for (Iterator<String> i = colors.iterator(); i.hasNext();)

{

String color = i.next(); //no type cast necessary

System.out.println(color);

}

o JDK 1.5’s Javadocs use type parameters named E, K, V, and T. These values stand for element, key, value, and type, respectively.

o The generic version of HashMap allows you to declare a type for both key and value.

Class HashMap<K,V>

boolean put(K key, V value);

V get(Object key);

o Classes that implement the Map<K,V>  interface can specify a type for both key  and value.

Map<String,Integer> map = new HashMap<String,Integer>();

map.put(“age”, new Integer(30)); //success

map.put(“name”, “Bob”); //compile time error

map.put(new Integer(1), new Integer(10)); //compile time error

o Generic types can be used in method parameters.

o The following method prints a List of Strings. If a parameterized List of any other type is passed in, a compile time error will occur.

o A non-parameterized List can be passed to this method but the compiler will issue a type safety warning. If the List contains any objects other than Strings, a class cast exception will occur.

void printList(List<String> list) {

for (Iterator<String> i = list.iterator(); i.hasNext();) {

System.out.println(i.next());

}

}

o Methods can return parameterized types.

o The following method returns a List of Strings.

o The client that calls this method can receive the return value as a List<String> or as a plain List. However, if it accepts the return type as List, the compiler will issue a type safety warning.

List<String> getList(String one, String two, String three) {

List<String> list = new ArrayList<String>();

list.add(one);

list.add(two);

list.add(three);

return list;

}

o Parameterized types can contain other parameterized types.

o The following code demonstrates using a parameterized ArrayList that contains a collection of parameterized HashMaps.

void printList(List<Map<String,String>> list) {

for (Iterator<Map<String,String>> i = list.iterator(); i.hasNext();) {

Map<String,String> map = i.next();

for (Iterator<Map.Entry<String,String>> j =map.entrySet().iterator(); j.hasNext();) {

Map.Entry entry = j.next();

System.out.println(entry.getKey() + “=” +

entry.getValue());

}

}

}

o Type parameterization is implemented through a process called “erasure”. Erasure removes all type information as the code is compiled.

o The compiler automatically adds any required type casts to the bytecode.

o Since it occurs at runtime, type parameterization does not effect code executed through reflection.

o The JDK 1.5 compiler will issue “unchecked” type safety warnings whenever a non-parameterized collection is used. To suppress warnings when parameterization is not required, method parameters can be declared using the “?” wildcard. For instance, this method accepts a list of any type.

– void printList(List<?> list)

o Generic types can be specify a range of types using the “extends” keyword. For instance, List<? extends Number> declares a List that only contains types that extend Number (or Number itself).

– void printNumberList(List<? extends Number>)