Pages

Wednesday, November 27, 2013

Java 7 Tutorial - For beginners

In Java 7, few minor language changes are introduced. It is not a major change like Java 5.

You can use underscores in numeric literals. For example the below is allowed in Java 7

private long reallyLongNumber = 1_000_000_000_000l;
private float entryFee = 10.5_5f;

There are certain rules on where you can use the underscore. 

Also to make the code more compact some un ncessary overheads has been removed. For example one of the overhead with generics is that if you want to define a hash table with Long value as key and ArrayList of Long as value you need to declare like this.

//Normally you have to declare like this
Hashtable<Long, ArrayList<Long>> employeeListByBank = new Hashtable<Long, ArrayList<Long>>();

The new Hashtable part also you need to repeat the samething which makes it bit difficult. In SE 7 you dont have to do that. You can just declare like this.

HashMap<String, ArrayList<String>> employeeListByBankInSE7 = new HashMap<>();

Which makes the program little less complex. I agree this is not a major improvement but reduces bit of coding.

Full example code below.

package com.ravi.java7learning;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;

public class Java7Improvements {

/**
* 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
*/
private long reallyLongNumber = 1_000_000_000_000l;
private float entryFee = 10.5_5f;
//private float wrongEntryFee = 10._55f; - This will give compilation error because adjacent to dot (.)

public static void main(String a[])
{
Java7Improvements instance = new Java7Improvements();
System.out.println("Long number with underscore allowed :"+instance.reallyLongNumber);
System.out.println("Float value with underscore :"+instance.entryFee);
}

private void lessVerboseForTypeArgumentsExample()
{
//Normally you have to declare like this
Hashtable<Long, ArrayList<Long>> employeeListByBank = new Hashtable<Long, ArrayList<Long>>();

//In SE 7 you can avoid this and declare like this
HashMap<String, ArrayList<String>> employeeListByBankInSE7 = new HashMap<>();

//This make the declaration less verbose. Note that you still need to provide the <> to make it
//generic.

HashMap<String, ArrayList<String>> withoutGenerics = new HashMap();

//Otherwise compiler will throw warning that, we are using raw type of hashmap.
}

}

No comments:

Post a Comment

 
Blogger Templates