Java Ver 1.5 or simply Java 5 came with some new features. These new features were added to facilitate a programmer not for the enhancement in JVM performance anymore.
Below i will describe few of them with some pretty examples. Hope you will find them helpful.
Autoboxing : - Just think automatically wrapping primitives into corresponding objects (i.e Integer,Boolean etc)
Check the example given below.
package testnewfeatures;
public class TestAutoBoxing {
public static void main(String[] args) {
int a = 10;
// old method of wrapping Primitive to Corresponding type Obj
Integer intObj1 = new Integer(a);
//new method of AutoBoxing - just created for programmer's ease NOT for a better performance
Integer intObj2 = a;
boolean bol = true;
System.out.println("\t Value of intObj1 = " + intObj1 );
System.out.println("\t Value of intObj2 = " + intObj2 );
if (bol) {
System.out.println("\t This is the Old way of Conditional-Cheack = " + bol );
}
Boolean bolObj = new Boolean(true);
// If requires ONLY Boolean Primitive but here we have given a Boolean Object
// Actually Java 5 automatically 'unbox' this for you.
if (bolObj) {
System.out.println("\t This is the NEW way of Conditional-Cheack = " + bolObj );
}
}
}
Scanners
Scanner are introduced to make new java programmers happy when they like to get some inputs from the system. Before this you were supposed to create a stream object and wrap it around another stream object & then you will have a chance to get a single input!.
Check the example given below.
package testnewfeatures;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
String name = null;
int age = 0;
java.util.Scanner keyboard = new java.util.Scanner(System.in);
System.out.println("Please enter your Name ");
name = keyboard.nextLine();
System.out.println("Now enter you Age");
age = keyboard.nextInt();
System.out.println("Your Name is = " + name + "\nYour Age is = " + age);
System.out.println("Now reading a File from a drive \n" );
try {
String fileText = "";
java.util.Scanner readFile = new java.util.Scanner(new java.io.File("D:\\NetBeansProjetcs\\TestNewFeatures\\src\\testnewfeatures\\InputFile.txt"));
while (readFile.hasNextLine()) {
fileText += readFile.nextLine() + "\n";
}
System.out.println (fileText);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
Static Import
If you want to use some properties or fields more then once then use Static Import one time and use only the created shortcuts on the remaining places.
Check the example given below.
package testnewfeatures;
import static java.lang.System.out;
public class TestStaticImport {
public static void main(String[] args) {
System.out.println("This is normal way to print something" );
out.println("This is the new way to print something" );
out.println("Here we have only 'Statically imported System.out' ");
out.println("so from now on we need no more ' System.out ' association.");
}
}