Notes eMeroo(Some TechTips);

December 22, 2008

What did J2SE 1.5 add? Part II

Filed under: Java — Amira @ 3:48 pm

This Post From My Old Blog
The last topic, I introduced the first four features J2SE 1.5 has added. They were Enhanced for Statement, Variable Arguments, static Import and Enumeration.Now, I’ll continue listing these features.
The Fifth Feature: Autoboxing and Auto-Unboxing

What should you do to insert a primitive value in a data structure that stores only Objects??Look to this code snippet, I want to add the integer value 5 to an ArrayList but I can't do that directly. You should convert the primitive value (here is int) to the corresponding type-wrapper class (here is Integer), and hence you can add 5 to the array. To retrieve this element, you should cast the return of the ArrayList's get method to Integer then assign it to Integer variable

ArrayList arrayList=new ArrayList();
Integer i=new Integer(5);
arrayList.add(i);

Integer y=(Integer) arrayList.get(0);
int z=y.intValue(); //get the int value of Integer
System.out.print(z);

J2SE 1.5 supports autoboxing and auto-unboxing conversions; they made writing such a snip of code easier.

Autoboxing conversion: automatically converts a value of a primitive type to an object of the corresponding type-wrapper class.

Auto-unboxing conversion: converts an object of a type-wrapper class to a value of the corresponding primitive type.

So, there is no need to create a type wrapper-class of the primitive type variable just you can assign directly an object of a type-wrapper class to a variable of the corresponding primitive type or a value of primitive type to a variable of the corresponding type-wrapper class.

You can write the last code snippet as following, the boxing and unboxing conversions have done automatically.

ArrayList arrayList = new ArrayList();
arrayList.add(1);
int x=(Integer) arrayList.get(0);
System.out.print(x);

Hint: (Integer) arrayList.get(0) the explicit cast here to Integer is a must because get method returns an Object and you can't assign a reference to superclass object(here Object) to a subclass variable(here Integer) without the explicit casting. But of course, you can assign a reference to a subclass to superclass variable without casting, implicit cast has already done by the compiler. 

The Sixth Feature: Generics

Generics is a new features supported by J2SE 1.5 that helps you in developing a class that work on any type, that specific type is specified only after declaring an instance of the class.

For example I've a problem; I want to extract unique elements from an array, these elements can be integers, double, character or any object. Generics will help in solving this problem easily without developing a class for each type. All you need is only one class that will operate on all types.

These two classes solve this problem; the first one is a generic class that is implemented to operate on any object.


import java.util.Arrays;
import java.util.ArrayList;

public class Extract
{

private ArrayList array=new ArrayList();

/** Returns an array list of a specific type after extracting the passed array */

public ArrayList doExtract(E[] data)
{
Arrays.sort(data);
array.add(data[0]);
for(int index=0 ; index
{
int current=index;
if(!data[++index].equals(data[current]))
array.add(data[index]);
}
return array;
}
/** prints the array before extracting it */
public String print(E[] data)
{
StringBuffer string=
new StringBuffer();
int size=data.length;

for(int index=0; index  index++)
string.append(data[index]+",");

string.append(data[size-1]);

return string.toString();
}

}

Now in the second class it's the time for declaring an instance of the class and specifying the type the program will operate on. Here three types(Integer,Character and String).


import java.util.ArrayList;
public class TestExtract
{


private static Integer[] i={1,3,5,2,1,2,1,3,4};
private static Character[] c={'a','s','d','a','a','d'};
private static String[] s={"Mohamed","Ali","Ahmed","Ahmed"};

private static ArrayList intArray=new ArrayList();

private static Extract intElements=new Extract();
private static Extract charElements=new Extract();
private static Extract stringElements=new Extract();

public static void main(String[] args)
{
System.out.printf("The integer array is [%s]\n",intElements.print(i));

intArray= intElements.doExtract(i);
System.out.printf("The integer array after extraction is %s\n\n",intArray);

System.out.printf("The character array is [%s]\n",charElements.print(c));
System.out.printf("The character array after extraction is %s\n\n",charElements.doExtract(c));

System.out.printf("The string array is [%s]\n",stringElements.print(s));

System.out.printf("The string array after extraction is %s\n\n",stringElements.doExtract(s));
}

}

Finally, that is a method that uses var-args, enhanced for statement and generics. It takes its parameter as type parameter using generics and use var-args to take any number of inputs and find the maximum number between them.


public class
Maximum
{


public static <T extends Comparable <T> > T  max (T... inputs){

T max =inputs[0];

for(T member:inputs)
if(member.compareTo(max)>0)
max=member;

return max;

}

public static void main(String[] args) {

System.out.printf("%d \n", max(1,2,3)) ;

System.out.printf("%.1f \n", max(2.8,7.5)) ;
System.out.printf("%s \n",max('a','b','c','d','f','g','j','y','u')) ;


}


}

The type parameter section specifies that T extends Comparable< T > so that only objects of classes that implement interface Comparable< T > can be used with this method.The restriction of using Comparable< T > objects is important because not all objects can be compared.
the arguments to a generic method must be of a reference type. So the compiler autoboxes the three int values as Integer objects and specifies that the three Integer objects will be passed to max.and that's allowed because class Integer, Double and Character (package java.lang) implements the Comparable< Double >,Comparable< Integer > and Comparable< Character > interface respectively.

The last feature is used in the overriding

when you override a method of a superclass in a subclass, it must have the same change return type and the argument
but in java 5 you can change the return type as long as the new return type is a subclass of the previous return type.
For example:


class A

{
A doSomething(int x)
{
return new A();
}
}


class B extends A
{
B doSomething(int x)      //legal override in java 1.5
{
return new B();
}

}

So this line B doSomething(int x) will not make any troubles because B is a subclass for the superclass A, so you can override the A's doSomething method in class B and use B as a return type instead of A.

Good Luck,

Amira

What did J2SE 1.5 add? part I

Filed under: Java — Amira @ 3:41 pm

This Post From My Old Blog
New features have already added to J2SE 5.0, these new features make the programming and developing the code using Java
programming language is easier, cleaner and faster. Using these features saves time and saves tens of lines of java code.
I’ll list the most of these features for you and explain them in brief, the rest I’ll mention them later on.

The First Feature: Enhanced for Statement

It iterates through the elements of an array or a collection without using counter, and you can use it when you aren’t in need to use the index of the array or the counter.
The syntax of an enhanced for statement is:

for ( parameter : arrayName )
statement;

This parameter passes all array values and executes the statement of each parameter/array value.

For example if you have an array of integers and want to multiply each element of the array by 2 then print the product. Let’s implement a piece of code do that using the enhanced for statement

int arr []={1,2,3,4,5,6};
for (int element : arr)
System.out.printf(“%d * 2 = %d \n “,element,element*2);

Without using the enhanced for statement the implementation will be:

int arr []={1,2,3,4,5,6};
for (int x=0 ; x< x++ ;>
System.out.printf(“%d * 2 = %d \n “,arr[x],arr[x]*2);

The Second Feature: Variable Arguments

It enables you to create methods that receive an unspecified number of arguments and its syntax is:

Return_type methodSignature (parameter_type… parameterName)

{
//to do code here
}

For example if you want to implement a method that return the summation of 2 integers it will be as following:

int sum (int x, int y)
{
return x+y;
}

But what will you do if you want to add up 3, 4 ,5 or any number of integers, before adding this new feature to J2SE 5.0 you have to re-implement the method with 3,4 or the count of integers you want to sum them.
Using the
Variable Arguments you can save all these implementation Just you will implement this method as following:

int sum( int… inputs)
{
int total=0;
for( int element : inputs)
total+=element;
return total;
}

Take care although the arrangement of the parameters in the method declaration doesn’t have an effect as long as the arguments of the invoked method match the parameters. But here it’s different, the var-args must be the last parameter in the parameter list of your method, if you want to implement a method that take two different parameter one of them double and the other is a var-args parameter so it must be ( double x, int… y) and it can’t be (int… y, double x).

The Third Feature: static Import

If you want to use the static members of a class you should import the class in the import statement then in every time you want to use this member you must write the member and preceding it by its class and the dot operator. In J2SE 1.5, you shouldn’t Just import the static member you need but attach the keyword static directly after import and before the package name.

To import the static members in your class or package, use this syntax (at the top and after the package declaration if found):

import static packageName.ClassName.staticMemberName;

for example if you want to find the square root of a 900, it can be solved by using the Math's sqrt and you haven't to write Math.sqrt(900). Using the static import you can write sqrt(900) but first you must use this import statement

import static java.lang.Math.sqrt;

Note:
-You can’t use static import with members defined in a class in the default package, you must name your package.
-If you have two classes with different names are declared in different packages but both have the same static member name, So after statically importing the two members and when you call that member, it leads to a compiler error. But you can overcome this problem by using the member’s class and the dot operator before the used member.

The Fourth Feature: Enumerations

An enumeration is an ordered list of items wrapped into a single entity. All enumerations types are reference types. Enum supports iterating over its items list, and comparing one item to another. Declaring enum is like declaring class, and as following you can declare an enum for listing employees and use for loop to print their name address and position. Without enum you will need to some of lookup tables or data structure to return the employee details, but look how it is easy with the enum.

enum Employee
{
Mohamed("Cairo","manager"),
Ahmed("Giza"," senior "),
Ali("Alex"," junior ");

public String address;
public String Position;

Employee(String empAddress, String empposition)
{
address=empAddress;
Position=empposition;
}
}//end enum Employee

public class EnumTest
{
public static void main(String[] args)
{
for(Employee emp : Employee.values())
System.out.printf("Employee name is: %s, His address is:%s, His possition is:%s \n", emp,emp.address,
emp.Position);

}
}//end class EnumTest

Note:
- Enum types are implicitly final, because they declare constants that should not be modified.
- Enum constants are implicitly static.
-For every enum, the compiler generates a static method called values that returns an array of the enum's constants in the order in which they were declared.

These were the first four features,
Good luck!
Amira

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.