Comparison of different java versions and features (1.5, 1.6 & 1.7)
Features of Java 1.5
Some of the features of Java 1.5 are listed
below:
1)
Generics:
Generics provide a way to create and use typesafe
data structures. This means that no longer do you have to create a List of the basic Objects then
typecast every time you pull stuff out! You can declare your list to
automatically typecast the stuff inside:
List things =
createListOfBorkObjects();
for(Iterator i = things.iterator() ;
i.hasNext() ; ) {
Bork item = (Bork)i.next();
//do something useful
}
Simply becomes...
List<Bork> things =
createListOfBorkObjects();
for(Iterator<String> i =
things.iterator() ; i.hasNext() ; ) {
Bork item = i.next();
//do something useful
}
2)
for-each loop:
For
each loop provides a efficient way to iterate through the elements of a collection.
for(Iterator lineup = list.iterator() ; lineup.hasNext() ; )
{
Object thatThing =
lineup.next();
myMonster.eat(thatThing);
}
In a
shortened:
for(Object thatThing : list) {
myMonster.eat(thatThing);}
This
works with the arrays also
int[] nums = { 1, 2, 3, 4, 5, 6 };
for(int n : nums) {
System.out.println(n);
}
3)
Autoboxing/Unboxing:
Integer i = new Integer(4);
int j = i.intValue();
Number n = new Float(3.14159);
Boolean stuff = new Boolean(false);
// stuff before ? must be a boolean (lower case)
System.out.println(
stuff.booleanValue() ? "Yep" : "Nope" );
Sick of this? Me too. Do this
instead:
Integer i = 4;
int j = i;
Number n = 3.14159f;
Boolean stuff = false;
System.out.println( stuff ?
"Yep" : "Nope" );
4)
Typesafe Enums
public
enum JettStaff {
ADRIAN("Adrian German"),
ARIJIT("Arijit Sengupta"),
BETH("Beth Plale"),
ERIC("Eric Wernert"),
KATIE("Katie A. Siek"),
KATY("Katy Borner"),
RAJA("Raja Sooriamurthi"),
RICH("Rich Kick"),
SUZANNE("Suzanne Menzel");
private String name;
public JettStaff(String n) { this.name = n; }
public String toString() { return this.name;
}
}
JettStaff
x = JettStaff.SUZANNE;
System.out.println(x);
But wait, it gets cooler! Now you can also give each enumerated value a
custom body. Since they're each instances, you could design a toString() method
for each:
public
enum JettStaff {
ADRIAN("Adrian German") {
public String toString() {
return name + "
(dgerman@indiana.edu)";
}
},
ARJIT("Arjit Sengupta") {
public String toString() {
return name + "
(asengupt@indiana.edu)";
}
},
// and on for the rest...
private String name;
public JettStaff(String n) { this.name = n; }
}
JettStaff
x = JettStaff.SUZANNE;
System.out.println(x);
Last but not least, enums can extend each other.
5)
Var args:
public
class VarArgs {
public static void main(String[] args) {
String[] newArgs = {"a",
"b", "c"};
vaMethod(newArgs);
}
public void vaMethod(String[] args) {
System.out.println("You gave me "
+ args.length + " args!
Yay.");
}
}
You can declare it more easily, and not have to
construct the array ahead of time:
public
class VarArgs {
public static void main(String[] args) {
vaMethod("a", "b",
"c");
}
public void vaMethod(String... args) {
System.out.println("You gave me "
+ args.length + " args!
Yay.");
}
}
6)
Annotations (Metadata)
public class MyClass extends Object {
@Override
public String toString()
{
return "My
overridden method!";
}
}
In the above example, we declare that we will
override the immediately following toString()
method. So the compiler looks in our superclass (Object) for
the same metho and makes sure it exists. If for some reason we had overloaded toString() by
declaring it with different parameters and maybe return type, then the compiler
would throw an error saying we didn't override correctly. This is really useful
if you want to make sure you override a method as opposed to simply overloading it.
Of course you can define your own annotations.
They're basically like interfaces, but they can contain values. An example
annotation looks like:
public @interface Conference {
String what();
String when();
String location();
}
7)
printf comes to java:
Till now printf can be used in c programming but
now it came to java. But why did they introduce it?
This feature was introduced to format the output.
System.out.printf("%d and %s are ok ", 6,”str”);
This
API can be used for internationalization as shown below:
System.out.printf(new Locale("en_us"),"%d and %s are ok ", 6,str);
8)
Java Concurrency:
Utility classes commonly useful in concurrent
programming. This package includes a few small standardized extensible
frameworks, as well as some classes that provide useful functionality and are
otherwise tedious or difficult to implement. Here are brief descriptions of the
main components. Locks and atomic classes were introduced in this version of
java.
a. Executors
Interfaces. Executor is a
simple standardized interface for defining custom thread-like subsystems, including
thread pools, asynchronous IO, and lightweight task frameworks. Depending on
which concrete Executor class is being used, tasks may execute in a newly
created thread, an existing task-execution thread, or the thread calling execute(), and may execute sequentially or concurrently. ExecutorService
provides a more complete asynchronous task execution framework. An
ExecutorService manages queuing and scheduling of tasks, and allows controlled
shutdown. The ScheduledExecutorService subinterface adds support
for delayed and periodic task execution. ExecutorServices provide methods
arranging asynchronous execution of any function expressed as Callable, the
result-bearing analog of Runnable. A Future returns the results of a function, allows
determination of whether execution has completed, and provides a means to
cancel execution.
Implementations.
Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor
provide tunable, flexible thread pools. The Executors class
provides factory methods for the most common kinds and configurations of
Executors, as well as a few utility methods for using them. Other utilities
based on Executors include the concrete class FutureTask
providing a common extensible implementation of Futures, and ExecutorCompletionService, that
assists in coordinating the processing of groups of asynchronous tasks.
b. Queues
The
java.util.concurrent ConcurrentLinkedQueue class supplies an
efficient scalable thread-safe non-blocking FIFO queue. Five implementations in
java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put
and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue. The
different classes cover the most common usage contexts for producer-consumer,
messaging, parallel tasking, and related concurrent designs.
c. Concurrent Collections
Besides
Queues, this package supplies a few Collection implementations designed for use
in multithreaded contexts: ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteArraySet.
Features of Java 1.6
1) Collections Framework Enhancements
New collection interfaces includes Deque, NavigableSet, NavigableMap.
Deque: A linear collection that supports element insertion and removal at
both ends. The name deque is short for "double ended queue".This
interface defines methods to access the elements at both ends of the deque.
Methods are provided to insert, remove, and examine the element.
2) java.io Enhancements:
New
class” Console” is added and it
contains methods to access a character-based console device. The readPassword()methods disable echoing thus they are suitable
for retrieval of sensitive data such as passwords. The method System.console ()returns the unique console associated with the
Java Virtual Machine.
3) Security Features and Enhancements:
·
Native platform Security (GSS/Kerberos)
integration.
·
Java Authentication and Authorization Service
(JAAS) login module that employs LDAP authentication
·
New Smart Card I/O API
4) GUI
·
JFC and Swing integration with desktop by using
Windows API.
·
Java 2D integration with desktop such as using
desktop anti-aliasing font settings
·
Splash screen direct support and can be shown
before JVM started
o System
tray support with ability to add icons, tool tips, and pop-up menus to the
Windows or any other system tray (such as Gnome).
5)
JavaTM API for XML Processing (JAXP):
The
Java API for XML Processing (JAXP) enables applications to parse, transform,
validate and query XML documents using an API that is independent of a
particular XML processor implementation. JAXP provides a pluggability layer to
enable vendors to provide their own implementations without introducing
dependencies in application code. Using this software, application and tool
developers can build fully-functional XML-enabled Java applications for
e-commerce, application integration, and web publishing.
The Java Platform, Standard Edition version 6.0 includes JAXP 1.4.
JAXP 1.4 is a maintenance release of JAXP 1.3 with support for the Streaming
API for XML (StAX).
6) Java
Compiler API
String fileToCompile = "test" + java.io.File.separator +"MyClass.java";
|
|||||||
|
JavaCompiler compiler =
ToolProvider.getSystemJavaCompiler();
|
|
|||||
|
int compilationResult
= compiler.run(null, null, null, fileToCompile);
|
||||||
|
if(compilationResult
== 0){
|
|
|||||
|
System.out.println("Compilation
is successful");
|
|
|||||
|
}else{
|
|
|||||
|
System.out.println("Compilation
Failed");
|
|
|||||
|
}
|
|
|||||
7)
JDBC
4.0 API
·
Auto load of JDBC driver.
·
ROWID
data type which is supported by
databases such as Oracle and DB2.
RowId
Value
|
Description
|
ROWID_UNSUPPORTED
|
Doesn't
support ROWID data type.
|
ROWID_VALID_OTHER
|
Lifetime of
the RowID is
dependent on database vendor implementation.
|
ROWID_VALID_TRANSACTION
|
Lifetime of
the RowID is
within the current transaction as long as the row in the database table is
not deleted.
|
ROWID_VALID_SESSION
|
Lifetime of
the RowID is
the duration of the current session as long as the row in the database table
is not deleted.
|
ROWID_VALID_FOREVER
|
Lifetime of
the RowID is
unlimited as long as the row in the database table is not deleted.
|
8)
Integrated web services
Merged JAX-RS and JAX-WS into java.
9) Support for
Javascript
Introduced javascripting engine in the package javax.script.*; Java 6 has inbuilt javascript
engine through which we can execute javascript.
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
engine.eval("print('Hello, World')");
Features of Java 1.7
1)
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;
}
2)
Diamond
syntax:
This:
List<Employee> employees = new
ArrayList<Employee>();
Became:
List<Employee> employees = new ArrayList<>();
3)
Binary
literals
int binary = 0b1001_1001;
4)
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;
}
5)
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
}
6) NIO
·
Support for
filesystem provider for zip/jar archives.
·
IPv6 defaulted support.
·
Implemented SDP (Sockets Direct Protocol).
7) Graphics:
·
XRender
pipeline for Java 2D
·
Create new
platform APIs for graphics features
Comments
Post a Comment