Wednesday 25 November 2015

Code examples for new features in Java 1.7



Automatic Resource Management

this:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {
   br.close();
}
becomes:
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();
}
You can declare more than one resource to close:
try (
   InputStream in = new FileInputStream(src);
   OutputStream out = new FileOutputStream(dest))
{
 // code
}

Underscores in numeric literals

int one_million = 1_000_000;

Strings in switch

String s = ...
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through
case "foo":
  case "bar":
    processFooOrBar(s);
    break;
case "baz":
     processBaz(s);
    // fall-through
default:
    processDefault(s);
    break;
}

Binary literals

int binary = 0b1001_1001;

Improved Type Inference for Generic Instance Creation

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
become:
Map<String, List<String>> anagrams = new HashMap<>();

Better exception handling

this:
} catch (FirstException ex) {
     logger.error(ex);
     throw ex;
} catch (SecondException ex) {
     logger.error(ex);
     throw ex;
}
become:
} catch (FirstException | SecondException ex) {
     logger.error(ex);
    throw ex;
}

String pooling vs intern



Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.
Since interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String()
Using your example:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh");
String s5 = new String("Rakesh").intern();

if ( s1 == s2 ){
    System.out.println("s1 and s2 are same");  // 1.
}

if ( s1 == s3 ){
    System.out.println("s1 and s3 are same" );  // 2.
}

if ( s1 == s4 ){
    System.out.println("s1 and s4 are same" );  // 3.
}

if ( s1 == s5 ){
    System.out.println("s1 and s5 are same" );  // 4.
}
will return:
s1 and s2 are same
s1 and s3 are same
s1 and s5 are same

Heap vs Stack memory



Heap: is a single area where JVM allocates memory for -Objects, including method code , static variables & instance variables.

Stack: Stack is created for each individual thread, JVM allocates memory for - local variables & arguments (values passed to method variables)

@ interface - all values in interface are constants i.e final static, so it's stored on Heap only.

Hibernate LAZY LOADING



<hibernate-mapping package="com.one2one" default-lazy="true">
      <class name="Certificate" table="CERTIFICATE" lazy="true">
            <id name="id" column="id" type="int">
                  <generator class="native"></generator>
            </id>
            <property name="name" column="NAME"></property>
      </class>
</hibernate-mapping>