Java
5 Features
Release date:
The
release on September 30, 2004 was originally numbered 1.5
Features:
-
Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion) (specified by JSR 14)
-
Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities (specified by JSR 175)
-
Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer) (specified by JSR 201)
-
Enumerations: the enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.); previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern) (specified by JSR 201)
-
Varargs: the last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)); in the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type
-
Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes (specified by JSR 201)
-
Improved semantics of execution for multi-threaded Java programs; the new Java memory model addresses issues of complexity, effectiveness, and performance of previous specifications
-
Static imports
-
Scanner class for parsing data from various input streams and buffer
-
The concurrency utilities in package java.util.concurrent
There
were also the following improvements to the standard libraries:
-
Automatic stub generation for RMI objects
-
Swing: New skinnable look and feel, called synth
-
The concurrency utilities in package java.util.concurrent
-
Monitoring and Management -
-
Monitoring and management API for the Java virtual machine
-
The new java.lang.management package provides the interface for monitoring and managing the Java virtual machine.
-
Monitoring and management API for the logging facility
-
JMX instrumentation of the Java virtual machine
-
The Java virtual machine (JVM) has built-in instrumentation that enables you to monitor and manage it using JMX. You can easily start a JMX agent for monitoring and managing remote or local Java VMs instrumentation or of any application with JMX instrumentation.
-
Other Features:
Virtual
Machine
- Class Data Sharing
- Garbage Collector Ergonomics
- Server-Class Machine Detection
- Thread Priority Changes
- Fatal Error Handling
- High-Precision Timing Support
Base
Libraries
- Lang and Util Packages
- Networking
- Security
- Internationalization
- Improved Support for Environment Variables
- ProcessBuilder
- Formatter
- Scanner
- Reflection
- JavaBeansTM Component Architecture
- Collections Framework
- Java API for XML Processing (JAXP)
- Bit Manipulation Operations
- Math
- Instrumentation
- Serialization
- Concurrency Utilities
- Threads
- Monitoring and Management
Integration
Libraries
- Remote Method Invocation (RMI)
- Java Database Connectivity (JDBC)
- CORBA, Java IDL, and Java RMI-IIOP
- Java Naming and Directory InterfaceTM (JNDI)
User
Interface
- Internationalization
- Java Sound Technology
- Java 2DTM Technology
- Image I/O
- AWT
- Swing
Deployment
- General Deployment
- Java Web Start
Tools
and Tool Architecture
- Java Virtual Machine Tool Interface (JVMTI)
- Java Platform Debugger Architecture (JPDA)
- Java Compiler (javac)
- Javadoc Tool
- Annotation Processing Tool (apt)
- Java TM 2 Platform, Standard Edition 5.0
- Trouble-Shooting and Diagnostic Guide
OS
& Hardware Platforms
- Supported System Configurations
- 64-Bit AMD Opteron Processors
Generics
Detailed Explanation
-
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:
Example:
package
com.sachin4java.java5.generics;
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
public
class
GenericTest
{
private
static
List
nonGenericlist
=
new
ArrayList();
private
static
List<String>
genericlist
=
new
ArrayList<String>();
public
static
void
main(String[]
args)
{
//nonGenericlist
items add
nonGenericlist.add("sachin");
nonGenericlist.add("rane");
//nonGenericlist.add(123);
//list accept integer also which should not be allowed if we want
type only Strings
Iterator
nonGenericIterator
=
nonGenericlist.iterator();
while
(nonGenericIterator.hasNext())
{
String
value
=
(String) nonGenericIterator.next();
//needs
to do casting otherwise comiple
error
System.out.println(value);
}
System.out.println("******************************");
//Genericlist
items
add
genericlist.add("sachin");
genericlist.add("rane");
//genericlist.add(123);
//if we uncomment this, it will give compile error
Iterator<String>
genericIterator
=
nonGenericlist.iterator();
while
(genericIterator.hasNext())
{
String
value
=
genericIterator.next();
//No
Need to typecast
System.out.println(value);
}
}
}
OUTPUT:
sachin
rane
******************************
sachin
rane
-
annotations
It
can be seen in class declaration, method declaration, field
declaration etc
We
can also declare custom annotation and use it.
-
Annotation methods can’t have parameters.
-
Annotation methods return types are limited to primitives, String, Enums, Annotation or array of these.
-
Java Annotation methods can have default values.
-
Annotations can have meta annotations attached to them. Meta annotations are used to provide information about the annotation.
For
ex. Java In built @Override annotation in subclasses to make
sure you are overriding superclass method otherwise it will give
compile error if wrong method overridden.
package
com.sachin4java.annotation;
import
java.lang.annotation.Documented;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Inherited;
import
java.lang.annotation.Retention;
import
java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public
@interface
MyCustomAnnotation{
String
name() default
"sachin";
String
city();
int
age()
default
30;
}
package
com.sachin4java.annotation;
import
java.lang.annotation.Annotation;
import
java.lang.reflect.Method;
public
class
AnnotationUse
{
//Use
of custom annotation
@MyCustomAnnotation(name="Sachin1",
city="Pune",
age=30)
public
void
m1()
{
System.out.println("m1()");
}
//Use
of custom annotation
@MyCustomAnnotation(name="Sachin2",
city="Pune")
public
void
m2()
{
System.out.println("m2()");
}
public
static
void
main(String[]
args)
throws
SecurityException,
ClassNotFoundException {
parseAnnotations();//analyze
annotations using reflection
}
private
static
void
parseAnnotations()
throws
SecurityException,
ClassNotFoundException {
//get
all methods of AnnotationUse class
Method[]
methods
=
AnnotationUse.class.getClassLoader()
.loadClass(("com.sachin4java.annotation.AnnotationUse")).getMethods();
//Iterate
methods
for
(Method
method
:
methods)
{
//check
if annotation available on method
if(method.isAnnotationPresent(MyCustomAnnotation.class))
{
//traverse
through all annotations on method
for(Annotation
annotation
:
method.getDeclaredAnnotations())
{
MyCustomAnnotation
myCustomAnnotation
=
method.getAnnotation(MyCustomAnnotation.class);
System.out.println("Method
Name="+method.getName()
+"
>>Name ="+myCustomAnnotation.name()+"
City ="+myCustomAnnotation.city()+"
Age ="+myCustomAnnotation.age());
}
}
}
}
}
OUTPUT:
Method
Name=m2 >>Name =Sachin2 City =Pune Age =30
Method
Name=m1 >>Name =Sachin1 City =Pune Age =30
-
Autoboxing/unboxing
This
facility eliminates the drudgery of manual conversion between
primitive types (such as int) and wrapper types (such as Integer)
package
com.sachin4java.autoboxing;
import
java.util.ArrayList;
import
java.util.List;
public
class
AutoBoxingTest
{
public
static
void
main(String[]
args)
{
List<Integer>
li
=
new
ArrayList<>();
for
(int
i
=
1; i
<
5; i++)
li.add(i);//converting
i primitive to wrapper automatically(AutoBoxing)
for
(Integer
integer
:
li)
{
int
i
=
integer;//conerting
wrapper
to primituive(Unboxing)
System.out.print(i+"
");
}
}
}
OUTPUT:
1
2 3 4
-
Enumerations
the
enum keyword creates a typesafe, ordered list of values (such as
Day.MONDAY, Day.TUESDAY, etc.); previously this could only be
achieved by non-typesafe constant integers or manually constructed
classes (typesafe enum pattern) (specified by JSR 201)
For
ex. We are passing enum week days and only week days will be allowed
in method, other values will not be possible in method as parameter
package
com.sachin4java.enumerations;
public
enum
MyWeekDaysEnum
{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSADAY,
FRIDAY,
SATURDAY,
SUNDAY
}
package
com.sachin4java.enumerations;
public
class
EnumerationTest
{
public
static
void
main(String[]
args)
{
testEnum(MyWeekDaysEnum.MONDAY);
}
//Here
we can not pass other value than enum
values.
So we can avoid garbage params
private
static
void
testEnum(MyWeekDaysEnum
weekDaysEnum)
{
switch
(weekDaysEnum)
{
case
MONDAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
case
TUESDAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
case
WEDNESDAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
case
THURSADAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
case
FRIDAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
case
SATURDAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
case
SUNDAY:{
System.out.println("It
is "+weekDaysEnum.toString());
break;
}
default:
break;
}
}
}
OUTPUT:
It
is MONDAY
-
Varargs
the
last parameter of a method can now be declared using a type name
followed by three dots (e.g. void drawtext(String... lines)); in the
calling code any number of parameters of that type can be used and
they are then placed in an array to be passed to the method, or
alternatively the calling code can pass an array of that type.
Varargs
will be last param in the method.
package
com.sachin4java.varargs;
public
class
VarargsTest
{
public
static
void
main(String[]
args)
{
varArgsMethod(10,"sachin",
"rane");
//first
param
int
and
//rest
will be assumed as varargs
varArgsMethod(10,"sachin",
"rane","aaaa","bbbb");//added
more params
but
//no
extra overloaded method
}
private
static
void
varArgsMethod(int
val,
String...varArgsParam)
{
System.out.println("\n**Iterating
varargs");
System.out.print(val
+
"
");
for
(String
string
:
varArgsParam)
{
System.out.print(string+
"
");
}
}
}
OUTPUT:
**Iterating
varargs
10
sachin rane
**Iterating
varargs
10
sachin rane aaaa bbbb
-
Enhanced for each loop:
Syntax
is extended with special syntax for iterating over each member of
either an array or any Iterable, such as the standard Collection
classes (specified by JSR 201)
When
we use LIST SET MAP traversal using for each loop, it uses ietrator
internally. If any other thread modify the collection or changes
underlying structure, ConcurrentModificationException will be thrown.
package
com.sachin4java.java5.foreach;
import
java.util.Arrays;
import
java.util.List;
public
class
ForEachTest
{
public
static
void
main(String[]
args)
{
List<String>
list
=
Arrays.asList("sachin",
"rane",
"pune");
System.out.println("***Using
old for loop ***");
for
(int
i
=
0; i
<
list.size();
i++)
{
System.out.print(list.get(i)+
"
");
}
System.out.println("\n
***Using old for loop***");
for
(String
str
:
list)
{
System.out.print(str+
"
");
}
}
}
OUTPUT:
***Using
old for loop
sachin
rane pune
***Using
old for loop
sachin
rane pune
-
Static imports
This
facility lets you avoid qualifying static members with class names
without the shortcomings of the "Constant Interface
antipattern." Refer to JSR 201.
package
com.sachin4java.java5.staticimport;
public
class
StaticImport
{
public
static
final
int
STATIC_IMPORT_VAL
=
10;
public
static
int
staticImportSum(int
a
,
int
b)
{
return
a+b;
}
}
package
com.sachin4java.java5.staticimport;
//adding
below STATIC IMPORT, So we can use StaticImport class members
//
that of this class
import
static
com.sachin4java.java5.staticimport.StaticImport.*;
public
class
StaticImportTest
{
public
static
void
main(String[]
args)
{
System.out.println(STATIC_IMPORT_VAL);//direct
use of STATIC_IMPORT_VAL
System.out.println(staticImportSum(10,
20));//direct
use of staticImportSum method
}
}
OUTPUT:
10
30
-
Scanner class
The
java.util.Scanner class can be used to convert text into primitives
or Strings. Since it is based on the java.util.regex package, it also
offers a way to conduct regular expression based searches on streams,
file data, strings, or implementors of the Readable interface.
Lets
see use of Scanner class to read text files as lines and using
delimeter
package
com.sachin4java.java5.scanner;
import
java.io.FileNotFoundException;
import
java.util.Scanner;
public
class
ScannerTest
{
public
static
void
main(String[]
args)
throws
FileNotFoundException
{
//
Initialize Scanner object
Scanner
scanner
=
new
Scanner(ScannerTest.class.getResourceAsStream("./scanner.txt"));
while(scanner.hasNext()){
//
initialize the string delimiter
Scanner
scan
=
new
Scanner(scanner.nextLine());
scan.useDelimiter("-");
System.out.println("***Printing
line***");
while
(scan.hasNext())
{
//
Printing the tokenized
Strings
System.out.println(scan.next());
}
scan.close();
}
//
closing the scanner stream
scanner.close();
}
}
OUTPUT:
***Printing
line***
sachin
rane
pune
***Printing
line***
aaa
bbb
ccc
-
The concurrency utilities
The
java.util.concurrent, java.util.concurrent.atomic, and
java.util.concurrent.locks packages provide a powerful, extensible
framework of high-performance, scalable, thread-safe building blocks
for developing concurrent classes and applications, including thread
pools, thread-safe collections, semaphores, a task scheduling
framework, task synchronization utilities, atomic variables, and
locks. The addition of these packages to the core class library frees
the programmer from the need to craft these utilities by hand, in
much the same manner that the Collections Framework did for data
structures. Additionally, these packages provide low-level primitives
for advanced concurrent programming which take advantage of
concurrency support provided by the processor, enabling programmers
to implement high-performance, highly scalable concurrent algorithms
in the Java language to a degree not previously possible without
resorting to native code.
Let's
take example of AtomicInteger.
package
com.sachin4java.java5.concurrency;
import
java.util.concurrent.atomic.AtomicInteger;
public
class
AtomicIntegerTest
{
public
static
void
main(String[]
args)
throws
InterruptedException
{
MyThread
runnable
=
new
MyThread();
Thread
t1
=
new
Thread(runnable);
Thread
t2
=
new
Thread(runnable);
t1.start();
t2.start();
System.out.println("nonAtomic
val="+runnable.getNonAtomic());
//the
above output will be varying between 5 to 10,
//
to get expected output
//we
will need to synchronize the nonAtomic++ operation
System.out.println("Atomic
val="+runnable.getAomic());
//The
above output always be as expected.
//No
need to synchronize increment operation
t1.join();
t2.join();
}
}
class
MyThread
implements
Runnable{
int
nonAtomic
=0;
AtomicInteger
atomicInteger=new
AtomicInteger(0);
@Override
public
void
run()
{
for
(int
i
=
0; i
<
5; i++)
{
nonAtomic++;
}
for
(int
i
=
0; i
<
5; i++)
{
atomicInteger.incrementAndGet();
}
}
public
int
getNonAtomic()
{
return
nonAtomic;
}
public
AtomicInteger
getAomic() {
return
atomicInteger;
}
}
OUTPUT:
nonAtomic
val=5
Atomic
val=10
-
Monitoring and Management
-
Monitoring and management API for the Java virtual machine
-
The new java.lang.management package provides the interface for monitoring and managing the Java virtual machine.
-
Monitoring and management API for the logging facility
-
JMX instrumentation of the Java virtual machine
-
The Java virtual machine (JVM) has built-in instrumentation that enables you to monitor and manage it using JMX. You can easily start a JMX agent for monitoring and managing remote or local Java VMs instrumentation or of any application with JMX instrumentation.
Let's
take example of management
package
Usage:
package
com.sachin4java.java5.monitoringmanagement;
import
java.lang.management.ManagementFactory;
import
java.lang.management.RuntimeMXBean;
import
java.lang.management.ThreadMXBean;
public
class
Monitoring
{
public
static
void
main(String[]
args)
{
//
Get the managed bean for the thread system of the Java
//
virtual machine.
ThreadMXBean
bean
=
ManagementFactory.getThreadMXBean();
//
Get the peak live thread count since the Java virtual
//
machine started or peak was reset.
int
peakThreadCount
=
bean.getPeakThreadCount();
System.out.println("Peak
Thread Count = "
+
peakThreadCount);
//
Get the current number of live threads including both
//
daemon and non-daemon threads.
int
threadCount
=
bean.getThreadCount();
System.out.println("Thread
Count = "
+
threadCount);
//GetClassPath
RuntimeMXBean
runtimeMXBean
=
ManagementFactory.getRuntimeMXBean();
String
classPath
=
runtimeMXBean.getClassPath();
System.out.println("ClassPath
= "
+
classPath);
}
}
OUTPUT:
Peak
Thread Count = 4
Thread
Count = 4
ClassPath
=
/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jfxrt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/localedata.jar:/home/sachin/eclipse-workspace/JavaFeatures/bin
No comments:
Post a Comment