Beruflich Dokumente
Kultur Dokumente
All these features added was to make developing the java code easily
1). StringBuilder :
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;
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”
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 :
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 )
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
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 { }
In annotations with single element ,that element should named with “value” is show
below
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.
}
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)
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.
here
argument index denotes the which argument it will deals. Format specifier refer the
argument in three ways
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) 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 :
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 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
java.util.Formatter class :
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.* ; (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
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
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)
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
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
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 “.
double first=Double.parseDouble(ar[0]);
double second=Double.parseDouble(ar[1]);
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.
But here you have to explicitly specify the type of the items you are trying to insert into
that list
But while extracting the element from the collection you no need to type cast again 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
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
In this case, if you tried to insert the String buffer element into the collection itself ,it will
gives compilation time error.
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.
we can get the same functionality using below code fragment also
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 .
1) generics
2) Enhanced for loop
3) AutoBoxing and OutBoxing
4) Meta Data
5) Static imports
6) Typesafe Enums
7) Variable Arguments
NOTE: To Compile the code using jdk1.4 then use the following command