You are on page 1of 12

Features of JAVA5.

All these features added was to make developing the java code easily
1). StringBuilder :

It works just like Unsynchronized StringBuffer class. It is faster than the


StringBuffer . Generally it is preferable to use this whenever you want to access the
string using single thread only.

It has two methods “append” and “insert” .These two methods are
overloaded you can use any datum ,first it will convert those datum to string after that
it will append to StringBulder object. Append method appends the strings or
characters at the end of StringBuilder object and insert inserts strings or characters in
particular place.

Java.lang.StringBuilder;

2).Auto Boxing and Un Boxing :

For example if you want to create wrapper for any primitive type you should follow
like this
float p_float=0.6f;
Float o_float=new Float(p_float);
But in J2SE5.0 you no need to do all this stuff ,you can directly write as follows
Float o_float = p_float; (or) Float p_float = 0.4f;
Here the total wrapping was done automatically ,this is called “Auto Boxing”. This
Auto Boxing is available for all primitive types.The reverse process is also simple as
above, called “Un Boxing”

Float o_float = 0.6f;


float p_float = o_float;
Ex .1)
public void loop( ) {
int MAX = 100;
Integer sum = 0;
Integer counter = 0;
While(true) {
sum += counter;
if(counter == MAX) break;
counter ++;
}
}

In this code snippet there is lot of hidden AutoBoxing and UnBoxing was taken palce.
In loop sum ,counter was auto boxed to Integer type , after that in while loop they
UnBoxed to do some arithmetical operations .

If, while ,do-while expects only boolean before java5.0 now they will accept
Boolean also . at the same time Switch statement expects only byte ,int ,char before ,now
it will accept Byte ,Char , Integer also.

NOTE :

Here is small confusion about the method overloading here. Ex;

long method1( long arg1) {………}


long method1( Integer arg1) {………}

if you call the method with int argument ,before java5.0 that int argument will
promoted to long and first method get called. But here it is reasonable to call the second
method by converting the primitive int argument with Integer object version
(I don’t know exact answer for this )

3). Annotation [METADATA frame work ]:

Java platform has various ad hoc (specific) annotation mechanisms .For example
transient modifier is ad hoc annotation indicating that a field should be ignored by
serialization and @deprecated ad hoc annotation indicates ,that method was deprecated.
Java5.0 release has introduced a general purpose annotation facility called MetaData .
Using this facility you can declare your own annotation using apt(annotation processing
tool ).
Annotation can be read from source files ,class files and even at run time also.
Annotation type declarations are similar to normal interface declaration . An at @ sign
precedes the interface keyword. Each method declaration defines an element of
annotation type. Method declaration must not have parameters or throws clause .Return
types are restricted to Element types (like String ,enum, class , annotations and arrays of
preceding types ). Method can have default values .See the following example

public @interface testing {

int id();
String synopsis() ;
String engineer() default “[unassigned]”;
String date() default “[unassigned]”;
}

Once the annotation is declared ,you can use that annotation to annotate the declarations.
Annotation is special kind of modifier ,can be used anywhere ,the other modifiers (public
static, final ) can be used with preceding of @ sign.
See the following example
@testing {
id = 10880,
synopsis = “ enable”, //these values must be compile time constants
engineer = “siva”,
date = “27/06/05”
}
An annotation with no elements is called marker annotation. Ex
public @interface testing { }

It is possible to omit the brackets in the marker annotations .


Ex
public @testing class Jclass() { ………}

In annotations with single element ,that element should named with “value” is show
below

public @interface copyright{


String value();
}

It is possible to omit the element name and equal sign in case of single element
annotation .
@copyright(“jdk1.5 new features”)
public class Aclass { ……….}

An annotation is new JAVA5.0 element that starts with ‘@’. Some annotations
are processed by JAVAC and some require new annotation tool “apt”. At present only
three annotations are there (and metadata frame work is also available).

a) @override :
This override annotation represents the method was overriding from the
super class . some annotations may have member methods and member variables and
parameters also. But Override is Marker annotation.

Ex: class sup{


long method1(long s) { ………}

}
class sub extends sup {

@override
long method1(long d) { . ………….}
}
here method1( long ) was overridden , if the parameters were different in super and
sub classes then it just simply treat it as overloading .

Note: If super class doesn’t have the method1( long) but if you try to use the
@override annotation in subclass then compiler will gives the following error
message

Parent.java 7: method doesn’t override the method from its super class
@override error

b)
c)

4) Formatted Input Output and var args:

java.text.Format subclasses provides very limited formatting facilities


compared to C language printf satetement.JAVA5.0 comes with new class
java.util.formatter which can both format the numerical output to string and send the
string to file or some other destination.

Java 5.0 has added printf() method to PrintStream class so that you can use
System.out.printf() statement to format the output .It will internally call the
java.util.formatter class to do the functionality.

System.out.printf( “ format string”, variable arguments);

Here format string original form is

“%[argument index$][flags][width][.precession] conversion “

here

width denotes the minimum no of character you want to show


precession indicates the no character after the decimal point

argument index denotes the which argument it will deals. Format specifier refer the
argument in three ways

1)Explicit Indexing : Argument index is integer indicating the position of the


argument in the argument list. First argument is referenced by %1$ and second by %2$
like this
Ex : System.out.printf(“%3$s %2$s %1$s”,”a”,”b”,”c”);
Output as follows
c ba
2) Relative Indexing : relative indexing is used when the specifier contains “ <”,which
caused argument for the previous format specifier should be reused.
Ex: System.out.printf(“%s %s %<s %<s” ,”a”,”b”,”c”,”d”);
Or
Formatter.format(“%s %s %<s %<s” ,”a”,”b”,”c”,”d”); (for all remain ex also)
Output is as follows
a b b b (here c, d ignored because they didn’t referenced)

3) Ordinary Indexing : is used when the format specifier contains neither argument
index nor “<” flag. Ordinary index is assigned a sequential implicit index into the
argument list.
Ex: System.out.printf(“%s %s %s %s” ,”a”,”b”,”c”,”d”);
Output is as follows
a b c d

flag : indicates whether you want display sign if it is ‘+’, or to pad zeros ‘0’

a) ‘ – ‘ : The result will be left justified


b) ‘ # ‘ : The result should use the conversion dependent alternate form
c) ‘ + ‘ : The result always includes sign
d) ‘ ‘ : The result will include the leading spaces for positive values
e) ‘0’ : The result will be zero padded
f) ‘ ( ‘ : The result will enclose the negative values in parenthesis
g) ‘ , ‘ : The result will include the local specific grouping characters

Conversion : conversions are divided into following categories

1) general : applied to any argument

a) b ‘B’ : if the argument is null then the result is null ,if the argument is
boolean ( Boolean) then the value is equal to the String.ValueOf() ,otherwise false

b) h ‘H’: if the argument is null ,then the result is null ,otherwise result is
Integer.toHexString(arg.hasCode());

c)s ‘S’ : if the argument is null ,then the result is null .If the argument
implements Formattable then arg.FormatTo() is invoked otherwise the result is
invoked by arg.toString();

2) character :

applied to any basic type that represent Unicode character(byte, char , short
(object versions) and for int (Integer) when Character.isValidCodepoint(int) is true.
a) c ‘C’: The result is Unicode character

3) Numeric :

a) Integral : byte , short ,int ,long (Object versions) and BigInteger.

1) d : The result is formatted as decimal integer


2) o : The result is formatted as Octal Integer
3) x ‘X’ : The result is formatted as Hexadecimal Integer

b)Floating : float, double,(Object versions) and BigDecimal

1) e ‘E’ : The result is formatted as decimal number in scientific notation


2) f : The result is formatted as floating point decimal number
3) g ‘G’ : The result is formatted as scientific or decimal format based on
the precession and value after rounding.
4) a ‘A’ : The result is formatted as hexadecimal float point

4) Date/time : capable of handling the java date and time (long,Calendar,Date)

a) t ‘T’ : prefix for the date and time conventions

5) Line Separator : produce the platform specific line separator

NOTE: Conversions denoted by uppercase letters is same as the lower case letter except
the result are converted to uppercase according to rules of the locale.

There is possibility to throws the following exceptions


1) UnknownFormatConversionException
2) UnknownFormatFlagsConversionException
3) IllegalFormatWidthException
4) IllegalFormatPrecessionException
5) FormatFlagsConversionMismatchException

There is another specifier that doesn’t deal with any argument .It is “%n” ,new line
specifier , you can also use “\n” but it is better to use “%n” ,because it is portable across
the platforms

Ex : 1) double pi = Math.PI;
System.out.printf(“pi = %5.3f %n”,pi);
Output for this is
pi = 3.142

Ex :2) System.out.printf(“%3$2s %2$2s %1$2s “, “a”,”b”,”c”);


Output is as follows
c ba

Ex:3) System.out.printf(“Local Time:%tT” , Calendar.getInstance());


Output is as follows
Local Time :13:23:45

Ex:4) Calendar c=new GregorianCalendar(1982, march, 10);


System.out.printf(“my birth date is: %1$tm %1$te %1$tY”,c);
Output is as follows
My birth date is: march 10 1982

java.util.Formatter class :

Formatter class is not necessarily safe from the multi threading .

StringBuilder sb=new StringBuilder();


Formatter f =new Formatter(sb,Locale.US);
f.format

5).Static Import :

Up to now to access any static fields or methods in class you should specify the
complete package name like as follows

double pi = Math.PI;

But JAVA5.0 has introduced the static imports ,usage is like this

import static java.lang.Math.PI;

then in the program you can directly use PI.

import static java.lang.Math.* ; (Wild characters also work in the static import)

NOTE : before implementing the static imports , we kept all those constants in single
interface and implement that interface wherever you need them .
6).Enumeration in Java5.0 :

In j2SE 5.0 however ,you do not need to worry about inventing you own enumeration
patterns since it provides a typesafe enumerated type facility .The J2SE 5.0 enum
declaration looks as follows

public enum MainMenu { FILE, EDIT,FORMAT ,VIEW);

here the syntax is just like C/C++ ,but C/C++ enums are simply integers where in java
enums are full fledged class, here it allows you to add arbitrary methods , fields to enum
to implement arbitrary interfaces.

You can also add data and behavior to an enum .see the following example

public enum Planet {

Mercury (109, 10),


Venus (110,20),
Earth (111,30),
Mars (112,40),
Jupiter (113,50),
Saturn (114,60),

public final double mass; //first parameter


public final double radius; //second parameter

Planet(double mass ,double radius) { //constructor


this.mass=mass;
this.radius=radius;
}
public double mass(){ return mass;}
public double radius(){ return radius;}

public static double surfaceGarvity(){


return mass*radius;
}
public static double surfaceWeight(double othermass){
return othermass*surfaceGravity;
}

The enum type Planet has the constructor ,and each enum constant is declared with
parameters to be passed to constructor when it is created.
There small method that takes weight of you on the earth and it will produces the weights
on different planets(sorry I have given wrong logic)

public void static main(String ar[]) {


double earthweight=Double.parseDouble(ar[0]);
double mass=earthweight/Earth.surfaceGravity();

for(Planet p:Planet.values())
System.out.printf( “Your Weight on %s is %f %n “,
p ,p.surfaceWeight(mass));
}

The idea of adding the behavior to enum can be taken one step forward. You can give the
each enum constant with different behavior using switch and eval method. See the
following example

public enum Operation {

Plus, Minus, Multiply, Divide ;

double eval(double x , double y) {


switch(this) {

case Plus: return x+y ;


case Minus: return x-y;
case Multiply: return x*y;
case Divide : return x/y;
}
throw new AssertionError(“assertion error “+this);
}
}

NOTE: this will work fine ,but without throw statement it won’t work , and for every new
constant you have to add another case statement otherwise eval method will execute the
throw method.

There is another ,you can give the different behavior to constant. See the below example

public enum Operation {

PLUS { double eval(double x, double y) { return x+y ; } }


MINUS { double eval(double x, double y) { return x-y; } }
MULTIPLY{ double eval(double x, double y) { retrun x*y; }}
DIVIDE { double eval(double x, double y) { return x/y; } }
abstract double eval(double x, double y);
}

here we have declared one abstract method in enum type and override with concrete
method in each constant .Such methods are known as “constant specific methods “.

public static void main(String ar[]){

double first=Double.parseDouble(ar[0]);
double second=Double.parseDouble(ar[1]);

for(Operation p=Operation.values()) // to traverse through all constants


System.out.printf(“%f %s %f =%f%n”,x ,p , y, p.eval(x,y) );
}

NOTE: Two class has been added java.util package ,EnumSet ,EnumMap. EnumSet is
high performance set implementations for enum.Enum sets allow the iteration over
ranges of the enum types.

7).Casting in java collections(Generics):

Examine the following example

List words=new ArrayList( ); // it is correct in jdk1.4

But here you have to explicitly specify the type of the items you are trying to insert into
that list

List<String> words=new ArrayList<String>( );

But while extracting the element from the collection you no need to type cast again in
jdk1.5

String word1=(String) ( words.get(i) ).toUppercase( ); //you have do like in jdk1.4

String word1=words.get(i).toUppercase( ); // this is enough in jdk1.5

Because of this feature in jdk1.5 ,if you try to insert the element that is other than the
String ,at the compilation time itself it will gives the error .

Example:
1) remove the four letter words from the collection ,code fragment is as follows

public void method(Collection words){


for(Iterator i=words.iterator() ; i.hasNext();){
String s=(String)i.next( ); //causes run time error if it is String Buffer
if(s.length() == 4)
i.remove();
}
}

But in the above code if the collection contains String Buffer instead of the String
element causes the run time error .Generics avoided this type of the problems ,see the
code fragment below

Public void method(Collection<String> words){

for(Iterator i=words.iterator();i.hasNext( );){


if(i.next().length()== 4)
i.remove();
}
}

In this case, if you tried to insert the String buffer element into the collection itself ,it will
gives compilation time error.

8).Enhanced For loop:

In most of the cases we are using the Iterator to traverse through the collection only .
JDK.15 has introduced the new enhanced for loop ,using this you can traverse through
the whole collection without using the iterator.

Ex: public void cancelAll( Collection c) { //this code is in jdk1.4


for(Iterator i=c.iterator() ;i.hasNext();) {
TimerTask tt=(TimerTask)i.next();
tt.cancel( );
}
}

we can get the same functionality using below code fragment also

public void cancelAll(Collection c) {


for(Object o : c)
( (TimerTask)o).cancel( );
}

we can also combine the generics and enhanced for loop as show below
public void cancelAll(Collection<TimerTask> c) {
for(TimerTask o : c)
o.cancel( );
}

8).Variable Arguments:

In the past releases if the method requires arbitrary arguments ,you have to create an
array and put all the values into that array prior to invoking that method. But the variable
argument feature hides this total process.

The three periods after the final parameter type indicates the final argument may be array
or sequence of arguments. VarArgs can be used only in final position .

Ex: public static method( type1 arg1,type2 arg2, type3 … arg3’s) ;

The following are six areas where jdk1.5 was concentrated:

1) generics
2) Enhanced for loop
3) AutoBoxing and OutBoxing
4) Meta Data
5) Static imports
6) Typesafe Enums
7) Variable Arguments

New Keyword introduced in java5.o release is “enum”

NOTE: To Compile the code using jdk1.4 then use the following command

javac –source 1.4 xxx.java

You might also like