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

Java 5 New Features: Generics Enhanced Loop Autoboxing/unboxing Typesafe Enums Other

This document summarizes several new features introduced in Java 5, including generics, enhanced for loops, autoboxing/unboxing, and typesafe enums. Generics allow type-safe collections and APIs. Enhanced for loops provide a simpler syntax for iterating over arrays and collections. Autoboxing automatically converts between primitives and object wrappers. Typesafe enums provide a safer alternative to constant integers for enumerated values. Other new features include varargs, static imports, metadata, and virtual machine enhancements.

Uploaded by

renuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Java 5 New Features: Generics Enhanced Loop Autoboxing/unboxing Typesafe Enums Other

This document summarizes several new features introduced in Java 5, including generics, enhanced for loops, autoboxing/unboxing, and typesafe enums. Generics allow type-safe collections and APIs. Enhanced for loops provide a simpler syntax for iterating over arrays and collections. Autoboxing automatically converts between primitives and object wrappers. Typesafe enums provide a safer alternative to constant integers for enumerated values. Other new features include varargs, static imports, metadata, and virtual machine enhancements.

Uploaded by

renuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Java 5 New Features

ÿ Generics
ÿ Enhanced for loop
ÿ Autoboxing/unboxing
ÿ Typesafe enums
ÿ Other
Varargs
Static Import
Metadata
New classes and methods
VM Enhancements

CompSci 100E 40.1


Generics
ÿ Allows classes to store objects whose type is irrelevant to
storing class, while allowing type-safe retrieval
ÿ E.g., Collection
ÿ Syntax
ArrayList<String> list = new ArrayList<String>();
list.put(“hello”); // put() takes a String
Iterator<String> iter = list.iterator();
String s = iter.next(); // next() returns a String
ÿ Compare with earlier Java
ArrayList list = new ArrayList();
list.put(“hello”); // put() takes an Object
Iterator iter = list.iterator();
String s = (String)iter.next();
// next() returns an Object which must be cast to String

CompSci 100E 40.2


Generics in API Docs
ÿ In API documentation, generics are given a type alias, e.g.,
“E”:
Alias is arbitrary, but stands for the same type throughout class
definition
Can be on more than one type using different aliases
ÿ Examples
Class ArrayList<E>
o add(E o)
o E get(int index)
Interface Map<K,V>
o V put(K key, V value)
o V get(Object key)
o Collection<V> values()

CompSci 100E 40.3


Enhanced for Loop
ÿ Replaced iterators, indexing

ÿ Iterators and indexing are prone to bounds errors


// throws ArrayIndexOutOfBoundsException
for (int i = 0; i <= arr.length; i++)
{ System.out.println(arr[i]); }

// what does this do?


Iterator iter = list.iterator();
while (iter.hasNext()) {
if (!“stop”.equals(iter.next())) {
System.out.println(iter.next());
}
}

CompSci 100E 40.4


Looping in Java 5
ÿ Java 5 introduces new language syntax for looping over arrays
and collections using for (aka “For-Each” loop)
ÿ Syntax:
for (type var: collection) {
// do something with var
}
ÿ Examples:
void processArray(String[] arr) {
for (String s: arr)
System.out.println(s.toUpperCase());
}

// generics work with new for loop to simplify syntax!


void processList(List<String> list) {
for (String s: list)
System.out.println(s);
}

CompSci 100E 40.5


Autoboxing/Unboxing
ÿ Java primitive types provided for performance, but mix poorly
with objects:
// compilation error!
ArrayList list = new ArrayList();
list.add(42);
int x = (int) list.get(0);

// Kludgey fix provided by original Java: ugh!


list.add(new Integer(42));
int x = ((Integer)list.get(0)).intValue()

ÿ Java 5 automatically “boxes” primitive types in Object types as


neeeded:
Integer objInt;
objInt = 42; // equivalent to objInt = new Integer(42);

CompSci 100E 40.6


Autoboxing with Generics and For-Each
ÿ Note again how the new Java 5 features work together:

// old syntax
Integer sumInteger(List list) {
int sum = 0;
Iterator iter = list.iterator();
while (iter.hasNext()) {
Integer iobj = (Integer) iter.next();
sum += iobj.intValue();
}
}
return new Integer(sum);

// new syntax
Integer sumIntegers(List<Integer> list) {
int sum = 0;
for (int x: list) sum+= x; // auto-unboxing
elements
return sum; // autobox return value
}
CompSci 100E 40.7
New Features: Limitations
ÿ Generics are not everywhere, yet
consider list.toArray() returning Object[]

ÿ Enhanced for loop on non-parameterized collections is still


annoying (obviously using generics helps, but what if you are
forced to use legacy code?)
for (Object o: list) { String s = (String)o; ... }

ÿ For loop doesn't give you a good way to loop over multiple
collections in parallel:
still must do:
int[] arr1, arr2;
for (int i; i < arr1.length; i++) {
int x = arr1[i] + arr2[i];
}

CompSci 100E 40.8


New Features: Limitations (con't)
ÿ Autoboxing doesn't carry over to arrays, or to converting arrays
to lists and vice versa:
can't do the following:
int[] arr = new int[100];
Integer[] arrInts = arr;

List<Integer> list = new ArrayList<Integer>();


list.addAll(arr);

CompSci 100E 40.9


Typesafe Enums
ÿ Enums are a safer alternative to constants
Old way:
public static final int GO = 0;
public static final int STOP = 1;
public static final int YIELD = 2;
....

Consider code taking these values as a parameter:


void process(int status) {
if (status == GO) ...
if (status == STOP) ...
if (status == YIELD) ...
else ... // what does status == 10 mean?

CompSci 100E 40.10


The Enum Alternative
ÿ Enums define a type, just like a class or primitive type
ÿ Enums are not interchangeable with ints, impossible to get
undefined values
ÿ Enums can be enumerated using for
ÿ String representations of enums actually mean something
ÿ Examples:
public enum TrafficLight { GO, STOP, YIELD }
public TrafficLight myLight = STOP;
for (TrafficLight t: TrafficLight.values()) {
System.out.print(t);
System.out.print(“ “);
}
// output: GO STOP YIELD

CompSci 100E 40.11


Other New Features
ÿ Java 5 has many other new features, including:
Varargs – variable-size argument lists for methods
Static Import – import constants, e.g. Math.PI
Metadata – attach extra information about code
New classes and methods – Queue, Scanner, printf, etc.
VM Enhancements

CompSci 100E 40.12

You might also like