0% found this document useful (0 votes)
71 views

J2SE 5 0 - Technical Session

J2SE 5.0 - technical Session

Uploaded by

toba_sayed
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

J2SE 5 0 - Technical Session

J2SE 5.0 - technical Session

Uploaded by

toba_sayed
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
You are on page 1/ 39

Harf E-Learning Technical

Session

Programming with the New Language


Features in J2SE 5.0

Ibrahim Sayed Ibrahim


[email protected]

All rights reserved to


[email protected]
Welcome and Introduction

All rights reserved to


[email protected]
A Brief History of the
Java™
Programming Language
 1995 (1.0)—First public release
 Hit a sweet spot!
 1997 (1.1)—Nested classes added
 Support for function objects
 2001 (1.4)—Assertions added
 Verify programmers understanding of
code
 2004 (1.5) All rights reserved to
[email protected]
Vocabulary

 The codename for the J2SE 5.0


release is "Tiger"
 A major theme—ease of
development

All rights reserved to


[email protected]
Overview

 Tiger has introduced several


enhancements as well as new
language features that ease the
development of Java applications
 Why this training is important to
the staff members.
 How Tiger can help you to improve
your Java programs
All rights reserved to
[email protected]
Overview

 Topics to be covered.
I. Generics
II. Enhanced for Loop
III. Autoboxing/unboxing
IV. Typesafe Enumerations
V. Static Imports
VI. Metadata
VII. Variable Arguments (Enhancement)
VIII. Enhanced Input
 Others
All rights reserved to
[email protected]
I- Generics
 Generics, which are also known as
parameterized types
 When you get an element from a
collection, you have to cast
 Casting is a pain
 Casting is unsafe—casts may fail at
runtime
 Wouldn’t it be nice if you could tell the
compiler what type a collection holds?
 Compiler could put in the casts for you
 They’d be guaranteed* to succeed
All rights reserved to
[email protected]
Generics
 Filtering a Collection—Today
// Removes 4-letter words from c; elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if(((String) i.next()).length() == 4)
i.remove();
}
// Alternative form - a bit prettier?
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
String s = (String) i.next();
if(s.length() == 4)
i.remove();
}
}
All rights reserved to
[email protected]
Generics

 Filtering a Collection With Generics


// Removes 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}
 Clearer and Safer
 No cast, extra parentheses,
temporary variables
 Provides compile-time type checking
All rights reserved to
[email protected]
Generics
 Example 2
import java.util.*;
public class Ex2 {
private void testCollection() {
List<String> list = new ArrayList<String>();
list.add(new String("Hello world!"));
list.add(new String("Good bye!"));
list.add(new Integer(95)); //a compile-time error will be produced,
// informing you that you cannot add an
//Integer to a collection of Strings.
printCollection(list);
}
private void printCollection(Collection c) {
Iterator<String> i = c.iterator();
while(i.hasNext()) {
String item = i.next();
System.out.println("Item: "+item);
}
}
public static void main(String argv[]) {
Ex2 e = new Ex2(); e.testCollection();
} All rights reserved to
} [email protected]
Generics

 Java Generics vs. C++ Templates ?


Generics simply provide compile-time type safety and eliminate the
need for casts.
The main difference is encapsulation: errors are flagged where they
occur and not later at some use site, and source code is not
exposed to clients
A C++ template on the other hand is just a fancy macro processor;
whenever a template class is instantiated with a new class, the
entire code for the class is reproduced and recompiled for the new
class.

All rights reserved to


[email protected]
II- Enhanced for Loop
(“foreach”)
 Iterating over collections is a pain
 Often, iterator unused except to get
elements
 Iterators are error-prone
 Iterator variable occurs three times per
loop
 Gives you two opportunities to get it wrong
 Common cut-and-paste error
 Wouldn’t it be nice if the compiler took
care of the iterator for you?
All rights reserved to
[email protected]
Enhanced for Loop
(“foreach”)
 The new form of the for statement has the following
syntax:
for (FormalParameter : Expression) Statement

 Note that Expression must be an array or an instance


of a new interface called java.lang.Iterable,
java.util.Collection now extends the Iterable
package java.lang;
public interface Iterable<E> {
/**
* Returns an iterator over the elements in this collection.
* There are no guarantees concerning the order in which the elements
* are returned (unless this collection is an instance of some class
*that provides such a guarantee).
*
*@return an iterator over the elements in this collection
*/
Iterator<E> iterator();
} All rights reserved to
[email protected]
Enhanced for Loop
(“foreach”)
 As an example, consider the following method that
uses the conventional for statement to iterate over a
collection:
// Assume we have an instance of StringBuffer "sb"
public void oldFor(Collection c) {
for(Iterator i = c.iterator(); i.hasNtext(); ) {
String str = (String) i.next();
sb.append(str);
}
}
 With the addition of generics, the above segment of
code can be rewritten using the enhanced for
statement as follows:
// Assume we have an instance of StringBuffer "sb"
public void newFor(Collection<String> c) {
for(String str : c) {
sb.append(str);
} All rights reserved to
} [email protected]
Enhanced for Loop
(“foreach”)
 The enhanced for statement can be used to iterate
over an array. Consider the following segment of code
for a method that calculates the sum of the elements
in an array:
public int sumArray(int array[]) {
int sum = 0;
for(int i=0;i<array.length;i++) {
sum += array[i];
}
return sum;
}
 Using the enhanced for statement, this can be
rewritten as:
public int sumArray(int array[]) {
int sum = 0;
for(int i : array) {
sum += i;
} All rights reserved to
[email protected]
return sum;
}
Enhanced for Loop
(“foreach”)

 Why they didn't add the ”foreach” and


”in” so that we can write:
foreach (element in collection)

 The fact of the matter is that adding new


keywords to a language such as Java is quite
costly. In addition, it wouldn't be compatible
with existing source code that uses the in
keyword, for example, as in System.in. So the
whole idea is just to keep things upwardly-
compatible. All rights reserved to
[email protected]
III- Autoboxing/unboxing

 You can’t put an int into a


collection
 Must use Integer instead
 It’s a pain to convert back and
forth
 Wouldn’t it be nice if compiler did
it for you?
All rights reserved to
[email protected]
Autoboxing/unboxing
 As an example, consider an int being stored and then
retrieved from an ArrayList:
list.add(0, new Integer(59));
int n = ((Integer)(list.get(0))).intValue();

 The new autoboxing/unboxing feature eliminates this


manual conversion. The above segment of code can
be written as:
list.add(0, 59);
int total = list.get(0);

 However, note that the wrapper class, Integer for


example, must be used as a generic type:
List<Integer> list = new ArrayList<Integer>();

All rights reserved to


[email protected]
Autoboxing/unboxing

 What is the main purpose of the


autoboxing / unboxing feature?

 Simply to ease the


interoperability between primitive
types and references without any
radical changes
All rights reserved to
[email protected]
IV- Typesafe Enumerations
 Enumerated types in Java commonly define
a class of constants as follows:
public class MainMenu {
public static final int MENU_FILE = 0;
public static final int MENU_EDIT = 1;
public static final int MENU_FORMAT = 2;
public static final int MENU_VIEW = 3;
}

 This pattern has several drawbacks


including:
 It is not type safe
 Constants are compiled into clients and therefore
adding more constants require recompilation of
the clients
 It has no namespace and therefore must prefix
constants
 Provides no easy wayreserved
All rights to translate
to the constants
into informative printable
[email protected]
Typesafe Enumerations
 A type safe enum pattern that avoids all of the
above problems . The idea is to define an enum as a
class that represents a single element of the
enumerated type; such a class must not provide public
constructors. Here is an example
public class MainMenu {
private final String name;
private MainMenu(String name) { this.name = name; }
public static final MainMenu FILE = new MainMenu("file");
public static final MainMenu EDIT = new MainMenu("edit");
public static final MainMenu FORMAT=new MainMenu("format");
public static final MainMenu VIEW = new MainMenu("view");
public String toString() { return name; }
}
All rights reserved to
[email protected]
Typesafe Enumerations

 This is a compile-time typesafe enumerated


type:
it is guaranteed that if you declare a method
with a parameter of type MainMenu, then any
non-null object reference passed in
represents one of the four valid menu items.
Any attempt to pass an incorrectly-typed
object results in a compile-time error.
In addition, this is a truly object-oriented
class as it contains both state and behavior.
All rights reserved to
[email protected]
Typesafe Enumerations
!!!!!!!
 In J2SE 5.0, however, you do not need to worry about
inventing your 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};

 This syntax looks much like enums in other languages such


as C/C++, but in C/C++ enums are simply glorified integers
where in Java a full-fledged class is generated for each enum
type. This approach has many advantages including:
 It provides strong compile-time type safety
 It provides a separate namespace for each enum type and thus
eliminates the need to include a prefix in each constant name
 Constants are not compiled into clients so you can freely add,
remove, or reorder them without recompiling the clients
 Printed values are informative instead of just numbers
 Enum constants can be used wherever objects can be used
All rights reserved to
[email protected]
Typesafe Enumerations
 Here is a complete example that declares an enumeration and
then prints the values:
public class Example {
public enum MainMenu {FILE, EDIT, FORMAT, VIEW}
public static void main(String[] argv) {
for (MainMenu menu : MainMenu.values())
System.out.println(menu);
}
}

 And the following segment of code shows another example using


the switch statement:
for(MainMenu menu : MainMenu.values()) {
switch(menu) {
case FILE: System.out.println("FILE Menu"); break;
case EDIT: System.out.println("EDIT Menu"); break;
case FORMAT: System.out.println("FORMAT Menu"); break;
case VIEW: System.out.println("VIEW Menu"); break;
}
} All rights reserved to
[email protected]
Typesafe Enumerations

 What are the advantages of the new


typesafe enums over the standard
approach, int enum pattern?
 They provide compile-time type safety--int enums don't provide any type
safety at all.
 They provide a proper name space for the enumerated type--with int
enums you have to prefix the constants to get any semblance of a name
space.
 They're robust--int enums are compiled into clients, and you have to
recompile clients if you add, remove, or reorder constants.
 Printed values are informative--if you print an int enum you just see a
number. All rights reserved to
[email protected]
 Because they're objects, you can put them in collections.
 Because they're essentially classes, you can add arbitrary fields and
V- Static Imports

 Static import feature enables you


to import static members from a
class or an interface and thus use
them without a qualifying name

All rights reserved to


[email protected]
Static Imports
 As an example, consider the following interface that
contains two constant values:
package com.name;
interface XYZ {
public static final double Constant1 = someValue;
public static final double Constant2 = anotherValue;
}

 Now, the constants in the XYZ interface can be used as


follows:
public class MyClass implements XYZ {
....
double value = 2 * Constant1;
...
}

 As you can see, a class must implement the interface


in order to have access to the constants defined in the
All rights reserved to
interface. [email protected]
Static Imports
 In J2SE 5.0, static import solves this problem as shown
in the following example:
import static com.name.XYZ.*;
public class MyClass {
...
double value = 2 * Constant1;
...
}
 Static Import Interacts Well With Enums
import static MainMenu.*;
class MyClass {
public static void main(String[] args) {
System.out.println(“FILE name =” +FILE);
...
}
}

All rights reserved to


[email protected]
Static Imports

How can use sin(x) instead of


Math.sin(x), and out.println("Hello
there"); instead of
System.out.println("Hello
there");??
 By the following static imports:
import static java.lang.Math.*;
import static java.lang.System.*;

All rights reserved to


[email protected]
VI- Metadata
 Many APIs require a fair amount of boilerplate
 Example: JAX-RPC web service requires paired
interface and implementation
 Wouldn’t it be nice if language let you
annotate code so that tool could generate
boilerplate?
 Many APIs require “side files” to be
maintained
 Example: bean has BeanInfo class
 Wouldn’t it be nice if language let you
annotate code so that tools could generate
side files? All rights reserved to
[email protected]
Metadata
 JAX-RPC Web Service—Today
public interface CoffeeOrderIF extends java.rmi.Remote {
public Coffee [] getPriceList()throws
java.rmi.RemoteException;
public String orderCoffee(String name, int quantity) throws
java.rmi.RemoteException;
}
public class CoffeeOrderImpl implements CoffeeOrderIF {
public Coffee [] getPriceList() {
...
}
public String orderCoffee(String name, int quantity) {
...
}
}

All rights reserved to


[email protected]
Metadata

 JAX-RPC Web Service With


Metadata
import javax.xml.rpc.*;
public class CoffeeOrder {
@Remote public Coffee [] getPriceList() {
...
}
@Remote public String orderCoffee(String name, int
quantity) {
...
}
} All rights reserved to
[email protected]
VII- Variable Arguments
(Enhancement)
 To write a method that takes an
arbitrary number of parameters, you
must use an array
 Creating and initializing arrays is a
pain
 Array literals are not pretty
 Wouldn’t it be nice if the compiler did it
for you?
 Essential for a usable printf facility
All rights
System.out.printf("%s %3d", reserved
name, to
age);
[email protected]
Variable Arguments
(Enhancement)
 The variable arguments new
functionality in J2SE 5.0 allows multiple
arguments to be passed as parameters
to methods as in:
void someMethod(Object ... args) {
// do something
}
// invoke the method
someMethod("arg1", "arg2", "arg3");

The notation ... is required. The printf


statement, is an example
All rights reserved to of using
variable arguments. [email protected]
Variable Arguments
(Enhancement)
 Using MessageFormat
 Today
Object[] arguments = {new Integer(7),new Date(),
"a disturbance in the Force"};
String result = MessageFormat.format("At {1,time} on
{1,date}, there was {2} on planet "+
"{0,number,integer}.", arguments);
 With Varargs
String result = MessageFormat.format("At {1,time} on
{1,date}, there was {2} on planet "+
"{0,number,integer}.",7, new Date(), "a disturbance in
the Force");
All rights reserved to
[email protected]
VIII- Enhanced Input
 Prior to J2SE 5.0, in order to read an integer value
from the keyboard, it has to be read as a String
and then parsed as follows :
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int n = Integer.parseInt(str);
 In J2SE 5.0, the java.util.Scanner class can be used
to accomplish the same thing but with less code
as follows:
Scanner reader = new Scanner(System.in);

int n = reader.nextInt();
All rights reserved to
[email protected]
Others

 Queues and Delayed Processing.


 Getting to Know Synth .
 Changes in Working With
ContentPane
 Class Formatter and Class
StringBuilder

All rights reserved to


[email protected]
Summary

 New features were designed to


interact well
 Language will be more
expressive
 Programs will be clearer, shorter,
safer
 Further ease the development of
Java applications
 improve theAllreadability
rights reserved to
[email protected]
of your
programs
More information

 http://java.sun.com/developer/techni

 http://java.sun.com/developer/comm

 http://java.sun.com/features/2003/05

All rights reserved to


[email protected]

You might also like