Your SlideShare is downloading. ×
0
Java 1.5 Features
Mohan Bang
Presentation Agenda
Enhanced for loop
3
Enumeration Types5
Formatted I/O
32
Static Imports
34
Introduction to JDK 1.5 and ...
Presentation Agenda
Autoboxing / Unboxing6
Complementary Features
8
Questions10
Improvement / Performance
37
Final Comment...
§1. Introduction to JDK 1.5 and
its features
 Version  Code Name  Release Date
JDK 1.0
JDK 1.1
JDK 1.1.4
JDK 1.1.5
JDK 1.1.6
JDK 1.1.7
JDK 1.1.8
J2SE 1.2
J2SE 1.2.1...
The Windows JRE download has not grown
significantly in recent memory
Java 1.4.2 Java 5 (1.5) Java 6 (1.6)
JRE 15.10 MB 16...
Java Release
Initial Release
Java Evolution
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE
6
Java SE
Oak Designed for embe...
Java Evolution
Major additions included:
• an extensive retooling of the AWT
event model
• inner classes added to the lang...
Java Evolution
JDK 1.0
JDK 1.1
J2SE 1.2
J2SE 1.3
J2SE 1.4
J2SE 5.0
Java SE
6
Java SE
Major additions included:
• strictfp ...
Java Evolution
Major additions included:
• HotSpot JVM included
• RMI was modified to support optional
compatibility with ...
Java Evolution
Major additions included:
• assert keyword
• regular expressions modeled after Perl
regular expressions
• e...
Java Evolution
Major additions included:
• Generics
• Metadata:
• Autoboxing/unboxing
• Enumerations
• Swing: New skinnabl...
Java Evolution
Major additions included:
•Support for older Win9x versions dropped.
•Scripting Language Support (JSR 223)
...
Java Evolution
Major additions included:
• JVM support for dynamic languages,
following the prototyping work currently don...
java.applet, java.awt, java.io, java.lang, java.net, java.util
java.math, java.rmi, java.security, java.sql, java.text, ja...
Java 1.5.0 (called as “Tiger”)
J2SDK 1.5 / J2SDK 5.0 version Focused on below key areas
 Ease of Development
 Scalabilit...
What’s New
 J2SE 5.0 is full of dramatic changes to the
java programming language, including new
syntax support and JVM e...
New Features in J2SE 5.0
 Language Features
(Enhanced for Loop, Static Import, Type-safe enumerations, Boxing / Unboxing,...
 Scanner and Formatter - printf() method
 Finally, simplified input and formatted output
 Enhanced for loop
 Automates...
 Metadata
 Variable length argument lists.
 Semaphores
 Many more features and enhancements
 Improved performance
Jav...
New features enhance existing API
 Static import improves utility functions
 Enum improves readability and organization ...
§2. Formatted I/O
Scanner class
 Provides basic input functionality for reading data
from system console or any data stream
 Following exa...
java.util.Scanner
 Java finally has a fairly simple way to read input
 Scanner sc = new Scanner(System.in);
 boolean b ...
Scanner
Scanner API provide a more robust mechanism for reading in data
types rather than simply parsing strings from buff...
Improved input
 The new Scanner class can parse primitive types
and strings using regular expressions
 The Scanner class...
Formatted output
 Similar to C/C++ printf and scanf:
System.out.printf("name count%n"); //newline
System.out.printf("%s %...
java.util.Formatter
 Java now has a way to produce formatted
output, based on the C printf statement
 String line;
int i...
C-style printf()method
 C-style printf()
 Uses a variable number of arguments (“varargs”).
 Formatting options for each...
printf()method example
 System.out method call to printf():
System.out.printf(“%d %.2f %.2en",
78, 1.23456, 1.23456);
 w...
printf()method -
numeric examples
Format Value Output
“%.2f” 1.23456 1.23
“%.2e” 1.23456 1.23e+00
“%,15.2f” -234567.8 -234...
printf()method -
alignment examples
Format Value(s) Output
“%10s” “ABC” ABC
“%-10s” “ABC” ABC
“%10d” 123 123
“%-10d” 123 1...
printf()method -
Date (02/23/2004) examples
Format Output
“%tD” 02/23/04
“%tF” 2004-02-23
“%1$tb %1$te %1$ty” Feb 23 04
“%...
Formatter class
 Same C-style printf()capability
 Variable number of arguments (“varargs”)
 Same formatting options as ...
Formatter class example
Formatter formatter = new Formatter();
formatter.format(
"%-10s %-2s ","Hartford","CT");
formatter...
Improved output
 The new Formatter class, modeled after C’s printf
statement, gives you much simpler formatted
output
 T...
§3. Enhanced for Loop
Iterators
 An iterator gives you every element of a collection,
one at a time
 The collection has a type iterator(); fac...
New for statement
 The syntax of the new statement is
for(type var : array) {...}
or for(type var : collection) {...}
 E...
Iterations, Part I
List policies = new ArrayList();
. . .
Iterator iter = policies.iterator();
while ( iter.hasNext() ) {
...
Iterations, Part II
List policies = new ArrayList();
. . .
for (Iterator iter =
policies.iterator();
iter.hasNext(); ) {
r...
Iterations, Part III
 How about iterating through arrays?
Policy policies[] = { … };
. . .
for ( int i = 0;
i < policies....
Enhanced for loop
 Iterations over collections are painful.
 Iterator is only used to get elements.
 Iterators can be e...
Enhanced for loop
for Collections
 For collections:
List policies = new ArrayList();
. . .
for ( Object policy : policies...
Enhanced for loop
for Arrays
 For arrays:
Policy[] policies = { … };
. . .
for ( Policy policy : policies ) {
renew( poli...
Enhanced for loop
Restrictions
 Restrictions
 Cannot be used to filter a collection.
 i.e., remove elements
 Cannot mo...
J2SE 1.4.0
for(Iterator iter = myArray.iterator(); iter.hasNext(); )
{    
MyClass myObj = (MyClass)iter.next();    
myObj...
// Returns the sum of the elements of a
int sum(int[] a)
{
int result = 0;
for (int i : a)
result += i;
return result;
}
F...
For Each Statement
 A great way to ditch annoying Iterators. Makes
code more elegant and less error prone.
 before
 aft...
Spot the Bug
Fixed Version
Using the For Each Statement
For each loop (arrays)
double[] array = {2.5, 5.2, 7.9, 4.3, 2.0};
for(double d: array)
{
System.out.println(d);
}
Iterate...
For each loop (Collections)
ArrayList<Integer> list = new
ArrayList<Integer>();
list.add(7);
list.add(15);
list.add(-67);
...
For each loop enums
for( Suit s: Suit.values()){
System.out.println(s.getColor());
}
values() returns an Iterator for enum...
§4. Static Imports
The “Constant Interface”
antipattern
 public interface Physics {
public static final double AVOGADROS_NUMBER = 6.02214199...
Static Import
 You can now import just the static members of a class or interface
 public interface Physics { // as befo...
Static Import
 Enables one to refer to static constants from
a class without needing to inherit from it
 If only used on...
Example
 import static java.awt.BorderLayout.*;
 import static java.lang.System.*;
getContentPane().add(new JPanel(),
CE...
Static Import
import static java.lang.Math.*;
…
int themax = max( 123123, 23475 );
 Reduces typing
 Alleviates need for ...
Static Import
Static imports let you avoid qualifying static members with class
names. Once the static member is imported ...
Static Import
 In order to access static members, it is necessary to
qualify references with the class they came from.
do...
Static Import
 Using constants of another class is merely an
implementation detail. Declaring that a class
implements an ...
Static Import
 members of another class are imported
import static java.lang.Math.PI;
 Once imported they can be used wi...
Example
 Before
System.out.println(“Hello”);
System.out.println(“World”);
System.err.println(“From”);
System.err.println(...
Static Vs. Normal import
 Static imports are analogous to regular imports. In
normal imports you import classes from pack...
Static import
 Ability to access static members from a class
without need to qualify them with a class
name.
interface ShapeNumbers {    
public static int CIRCLE = 0;    
public static int SQUARE = 1;    
public static int TRIANGL...
To make this cleaner, the static members are placed into a class and
then imported via a modified syntax of the import dir...
An example of importing
a Java class
 For example, to use java.lang.Math.
double radians =
Math.toRadians(30.0);
double u...
Importing Static Members
 Currently
 Importing a class or interface
 Why require a class name prefix?
 Static Import
...
With Static Import
 No need to reference Math, except in import.
import static java.lang.Math.*;
double radians = toRadia...
Importing Static Members
 Code is more readable.
 No need to reference the class or interface names.
 Code can be less ...
Static import facility
 import static org.iso.Physics.*;
class Guacamole {
public static void main(String[] args) {
doubl...
§5. Enumeration Types
Enumerations
 An enumeration, or “enum,” is simply a set of
constants to represent various values
 Here’s the old way of...
enums are classes
 An enum is actually a new type of class
 You can declare them as inner classes or outer classes
 You...
Enums really are classes
 public enum Coin {
 // enums can have instance variables
private final int value;
 // An enum...
Other features of enums
 values() returns an array of enum values
 Season[] seasonValues = Season.values();
 switch sta...
Standard Approach to Constant
Enumerations – Definition
 int enums
public class PolicyOperation {
public static final int...
Simple example of
Typesafe enum Construct
 For a deck of cards…
enum Suit { CLUBS, DIAMONDS,
HEARTS, SPADES }
enum Rank {...
A more complex
Typesafe enum Construct
public enum OperationEnum {
QUOTE(1), ISSUE(2), RENEW(4),
CANCEL(12),
ENDORSE(16), ...
Using the
Typesafe enum Construct
void process(OperationEnum oper) {
. . .
switch (oper) {
case ISSUE: . . .
case CANCEL: ...
Type Safety: All statuses above may carry some business
meaning, but in Java language context, these are just int values.
...
Type-safe enumerations
 Compiler support for Typesafe Enum pattern.
 Looks like traditional enum (C, C++, Pascal).
 Far...
An enumeration is an ordered list of items wrapped into a
single entity.
enum Season {winter, spring, summer, fall}
Usage ...
Enums
 Previously, the standard way to represent an
enumerated type was to use the int
Enum pattern:
public static final ...
Switch with Enum
Color getColor( Suit suit ) {
switch( suit ) {
case clubs:
case spades: return Color.Black;
case diamonds...
Enumerated Types
 Similar to enum types in C, Pascal etc. and
HashTable, keyset
 Enums are classes, extends java.lang.En...
Fun with Enums
 public enum DAYConstants {
MON<,UES<WED………..
 };
 Class DAYConstants
 {
 Final staic sting MONDAY = 1...
Enumerated types
 Enumerated types are a way of representing nonstandard
data, such as days of the week, with integers:
...
Enumerated types in Java 1.5
 public enum Suit {clubs, diamonds, hearts, spades}
 Notice new keyword “enum”
 Values of ...
Using an enumerated type
 public class CoinTest {
public static void main(String[] args) {
for (Coin c : Coin.VALUES)
Sys...
Advantages of enumerated types
 enum types simplify code and make it more readable
 Types are checked at compile time (h...
Disadvantages of enumerated
types
 Still more complexity in the language
 Harder for beginners, nicer for experts!
Type-safe enum
enum Day { SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY }
//used
Day today = Day.WEDNESDA...
More Complex Enum
enum Suit {
CLUBS(Color.BLACK),
DIAMONDS(Color.RED),
HEARTS(Color.RED),
SPADES(Color.BLACK);
private Col...
§6. Autoboxing / Unboxing
Autoboxing
 Java distinguishes between primitive types and Objects
 Primitive types, i.e., int, double, are compact, sup...
Auto boxing and unboxing
 Java won’t let you use a primitive value where an
object is required--you need a “wrapper”
 my...
www.themegallery.com
Autoboxing / Unboxing
Example
 Traditional “boxing” example:
List ssnList = new ArrayList();
. . .
i...
Autoboxing / Unboxing
Example #1
 “Autoboxing” example:
List ssnList = new ArrayList();
. . .
int ssn = getSocSecNum();
....
Autoboxing / Unboxing
 The need to explicitly convert between primitive
types and wrapper objects.
 Such as primitive ty...
Autoboxing / Unboxing
Example #2
 Autoboxing/Unboxing used in other ways.
double area(double height,
double width) {
retu...
Autoboxing / Unboxing
Example #3
 And others:
Double premium = new Double(123.45);
Double tax = premium * 0.05;
double fe...
Boxing / Unboxing
 Collections hold only objects, so to put
primitive data types it needs to be wrapped
into a class, lik...
J2SE 1.4.0
ArrayList arrayList = new ArrayList();    
Integer intObject = new Integer(10);
arrayList.add(intObject); // ca...
Autoboxing and Unboxing
 Autoboxing:
 Automatic converting of primitives into wrapper classes
 Integer x = 10;
 Unboxi...
§7. Improvement / Performance
Analyze Memory Heap Dump
Any problem in pure Java code throws a Java exception
or error. Java exceptions or errors will no...
StringBuilder Class
 Introduced a new class java.lang.StringBuilder.
 It is like unsunchronized StringBuffer.
 Faster t...
Performance
 Faster startup time
 Better garbage collection; low pause option
§8. Complementary Features
Complementary Features
 Generics improve enhanced for loop
 Generics and auto-boxing/unboxing allow
Enumerated types
 V...
§9. Final Comments
"The new language features all have one thing in common: they take some
common idiom and provide linguistic support for it...
If you have any queries, Please feel free to contact me
Java 1.5 features
Upcoming SlideShare
Loading in...5
×

Java 1.5 features

8,367

Published on

Introduction to JDK 1.5 and its features
Formatted I/O
Enhanced for loop
Static Imports
Enumeration Types
Autoboxing / Unboxing
StringBuilder

Published in: Technology, Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
8,367
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
233
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "Java 1.5 features"

  1. 1. Java 1.5 Features Mohan Bang
  2. 2. Presentation Agenda Enhanced for loop 3 Enumeration Types5 Formatted I/O 32 Static Imports 34 Introduction to JDK 1.5 and its features1
  3. 3. Presentation Agenda Autoboxing / Unboxing6 Complementary Features 8 Questions10 Improvement / Performance 37 Final Comments 39
  4. 4. §1. Introduction to JDK 1.5 and its features
  5. 5.  Version  Code Name  Release Date JDK 1.0 JDK 1.1 JDK 1.1.4 JDK 1.1.5 JDK 1.1.6 JDK 1.1.7 JDK 1.1.8 J2SE 1.2 J2SE 1.2.1 J2SE 1.2.2 J2SE 1.3 J2SE 1.3.1 J2SE 1.4.0 J2SE 1.4.1 J2SE 1.4.2 J2SE 5.0 (1.5.0) J2SE 6.0 (1.6.0) J2SE 7.0 (1.7.0) Oak (none) Sparkler Pumpkin Abigail Brutus Chelsea Playground (none) Cricket Kestrel Ladybird Merlin Hopper Mantis Tiger Mustang Dolphin Jan 23, 1996 Feb 19, 1997 Sept 12, 1997 Dec 3, 1997 April 24, 1998 Sept 28, 1998 April 8, 1999 Dec 8, 1998 March 30, 1999 July 8, 1999 May 8, 2000 May 17, 2001 Feb 6, 2002 Sept 16, 2002 June 26, 2003 Sept 30, 2004 Dec 11, 2006 Not Yet Released Java History The main difference between Java 5 and Java 6 is performance. In Java 6 performance is good as compare to Java 5. The Java 7 Dolphin Project began in August 2006 and is tentatively scheduled for release in late 2010. The development period is organized into ten milestones; as of April 2010, milestone 7 is in progress.
  6. 6. The Windows JRE download has not grown significantly in recent memory Java 1.4.2 Java 5 (1.5) Java 6 (1.6) JRE 15.10 MB 16.13 MB 15.42 MB SDK 49.33 MB 51.82 MB 72.90 MB
  7. 7. Java Release
  8. 8. Initial Release Java Evolution JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE Oak Designed for embedded devices
  9. 9. Java Evolution Major additions included: • an extensive retooling of the AWT event model • inner classes added to the language • JavaBeans • JDBC • RMI JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE
  10. 10. Java Evolution JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE Major additions included: • strictfp keyword • reflection which supports Introspection only, no modification at runtime possible. • the Swing graphical API was integrated into the core classes • Sun's JVM was equipped with a JIT compiler for the first time • Java Plug-in • Java IDL, an IDL implementation for CORBA interoperability • Collections framework
  11. 11. Java Evolution Major additions included: • HotSpot JVM included • RMI was modified to support optional compatibility with CORBA • JavaSound • Java Naming and Directory Interface (JNDI) included in core libraries (previously available as an extension) • Java Platform Debugger Architecture (JPDA) JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE
  12. 12. Java Evolution Major additions included: • assert keyword • regular expressions modeled after Perl regular expressions • exception chaining allows an exception to encapsulate original lower-level exception • Internet Protocol version 6 (IPv6) support • non-blocking NIO (New Input/Output) • logging API • image I/O API for reading and writing images in formats like JPEG and PNG • integrated XML parser and XSLT processor (JAXP) • integrated security and cryptography extensions (JCE, JSSE, JAAS) • Java Web Start included JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE
  13. 13. Java Evolution Major additions included: • Generics • Metadata: • Autoboxing/unboxing • Enumerations • Swing: New skinnable look and feel, called synth. • Varargs • Enhanced 'for loop' • Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory. • Automatic stub generation for RMI objects. • static imports JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE
  14. 14. Java Evolution Major additions included: •Support for older Win9x versions dropped. •Scripting Language Support (JSR 223) •Dramatic performance improvements for the core platform[15][16], and Swing. •Improved Web Service support through JAX- WS (JSR 224) •JDBC 4.0 support (JSR 221). •Java Compiler API (JSR 199) •Upgrade of JAXB to version 2.0 •Support for pluggable annotations (JSR 269). •Many GUI improvements JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE
  15. 15. Java Evolution Major additions included: • JVM support for dynamic languages, following the prototyping work currently done on the Multi Language Virtual Machine, • A new library for parallel computing on Multi- core processors[26], • Superpackages (JSR 294), which are a way to define explicitly in a library or module which classes will be visible from outside of the library[27], • Swing Application Framework, an infrastructure common to most desktop applications, making Swing applications easier to create. • Replacing the existing concurrent low-pause garbage collector JDK 1.0 JDK 1.1 J2SE 1.2 J2SE 1.3 J2SE 1.4 J2SE 5.0 Java SE 6 Java SE
  16. 16. java.applet, java.awt, java.io, java.lang, java.net, java.util java.math, java.rmi, java.security, java.sql, java.text, java.beans javax.accessibility, javax.swing, org.omg javax.naming, javax.sound, javax.transaction java.nio, javax.imageio, javax.net, javax.print, javax.security, org.w3c javax.activity, javax. management Java 1.0 8 packages 212 classes Java 1.1 23 packages 504 classes Java 1.2 59 packages 1520 classes Java 1.3 77 packages 1595 classes Java 1.4 103 packages 2175 classes Java 1.5 131 packages 2656 classes New Events Inner class Object Serialization Jar Files International Reflection JDBC RMI JFC/Swing Drag and Drop Java2D CORBA JNDI Java Sound Timer Regular Exp Logging Assertions NIO
  17. 17. Java 1.5.0 (called as “Tiger”) J2SDK 1.5 / J2SDK 5.0 version Focused on below key areas  Ease of Development  Scalability, Performance and quality  Monitoring and Manageability  Desktop Client  Miscellaneous Features
  18. 18. What’s New  J2SE 5.0 is full of dramatic changes to the java programming language, including new syntax support and JVM enhancements.  It is considered to be the most revolutionary java release since JDK1.2
  19. 19. New Features in J2SE 5.0  Language Features (Enhanced for Loop, Static Import, Type-safe enumerations, Boxing / Unboxing, Annotations (aka metadata), Variable Arguments, Generics)  Virtual Machine Features (Class Data Sharing, Server-Class Machine Detection, Garbage Collector Ergonomics, Thread Priority Changes, High-Precision Timing Support)  Performance Enhancements (Garbage collection Ergonomics, StringBuilder Class, Java 2D Technology, Image I/O)  Base Libraries (Lang and Util Packages, Networking, JAXP, Bit Manipulation Operations)  Integration Libraries (Remote Method Invocation (RMI), Java Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI))
  20. 20.  Scanner and Formatter - printf() method  Finally, simplified input and formatted output  Enhanced for loop  Automates use of Iterators to avoid errors  Static import - import static java.Math.*;  Lets you avoid qualifying static members with class names  Enumerated Types  Provides all the well-known benefits of the Typesafe Enum pattern  Autoboxing / Unboxing  Automatic wrapping and unwrapping of primitives  Generic Types  Compile-time type safety for collections without casting Java 1.5 New Features
  21. 21.  Metadata  Variable length argument lists.  Semaphores  Many more features and enhancements  Improved performance Java 1.5 New Features
  22. 22. New features enhance existing API  Static import improves utility functions  Enum improves readability and organization of constants  Auto-boxing improves readability  Generics enhance compile time type checking  Generics improve reflection  Generics allow return type overriding
  23. 23. §2. Formatted I/O
  24. 24. Scanner class  Provides basic input functionality for reading data from system console or any data stream  Following example reads a String from standard input and expects a following int value: Scanner s= new Scanner(System.in); String param= s.next(); int value=s.nextInt(); s.close();  Scanner methods next and nextInt block if no data is available  Supports regular expression based search  To process more complex input, pattern matching algorithms are available from class java.util.Formatter
  25. 25. java.util.Scanner  Java finally has a fairly simple way to read input  Scanner sc = new Scanner(System.in);  boolean b = sc.nextBoolean();  byte by = sc.nextByte();  short sh = sc.nextShort();  int i = sc.nextInt();  long l = sc.nextLong();  float f = sc.nextFloat();  double d = sc.nextDouble();  String s = sc.nextLine();  By default, whitespace acts as a delimiter, but you can define other delimiters with regular expressions
  26. 26. Scanner Scanner API provide a more robust mechanism for reading in data types rather than simply parsing strings from buffered System.in calls. Prior to Scanner feature was introduced, to read from standard input it would be necessary to write exception handling code and wrap an InputStreamReader and a BufferedReader around System.in. Scanner class throws an unchecked exception InputMismatchException, which you could optionally catch. Scanner API simplifies your code as follows: Scanner keyboard = new Scanner(System.in); //no more wrapping with InputStreamReader and //BufferedReader around System.in System.out.println("Enter your first number?"); int i1 = keyboard.nextInt(); //no more parsing strings e.g. new Integer("5").intValue(); System.out.println("Enter your second number?"); int i2 = keyboard.nextInt(); //no more parsing strings e.g. new Integer(str).intValue();
  27. 27. Improved input  The new Scanner class can parse primitive types and strings using regular expressions  The Scanner class can also read in input from a String (not just an I/O stream)
  28. 28. Formatted output  Similar to C/C++ printf and scanf: System.out.printf("name count%n"); //newline System.out.printf("%s %5d%n", user,total);  Supports formats for dates, etc: System.out.format("Local time: %tT", Calendar.getInstance()); // -> "Local time: 13:34:18"  Like C's sprintf(3), Strings may be formatted using String.format: import java.util.Calendar; import java.util.GregorianCalendar; import static java.util.Calendar.*; Calendar c = new GregorianCalendar(1995, MAY, 23); String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); // -> s == "Duke's Birthday: May 23, 1995"
  29. 29. java.util.Formatter  Java now has a way to produce formatted output, based on the C printf statement  String line; int i = 1; while ((line = reader.readLine()) != null) { System.out.printf("Line %d: %s%n", i++, line); }  There are about 45 different format specifiers (such as %d and %s), most of them for dates and times
  30. 30. C-style printf()method  C-style printf()  Uses a variable number of arguments (“varargs”).  Formatting options for each argument.  Common formats for numeric, string, and date/time.  Layout justification and alignment.  Locale-specific output  Normally used with System PrintStream  System.out  System.err
  31. 31. printf()method example  System.out method call to printf(): System.out.printf(“%d %.2f %.2en", 78, 1.23456, 1.23456);  will print: 78 1.23 1.23e+00
  32. 32. printf()method - numeric examples Format Value Output “%.2f” 1.23456 1.23 “%.2e” 1.23456 1.23e+00 “%,15.2f” -234567.8 -234,567.80 “%(,15.2f” -34567. (34,567.00) “%x” 252 fc “%4d” 5 5 “%04d” 78 0078
  33. 33. printf()method - alignment examples Format Value(s) Output “%10s” “ABC” ABC “%-10s” “ABC” ABC “%10d” 123 123 “%-10d” 123 123 “%-10s %-2s %05d-%04d” “Hartford”, “CT”, 6115, 11 Hartford CT 06115-0011
  34. 34. printf()method - Date (02/23/2004) examples Format Output “%tD” 02/23/04 “%tF” 2004-02-23 “%1$tb %1$te %1$ty” Feb 23 04 “%1$tA %1$tB %1$te, %1$tY” Monday February 23, 2004 “%1$tF %1$tr” 2004-02-23 10:45:00 AM
  35. 35. Formatter class  Same C-style printf()capability  Variable number of arguments (“varargs”)  Same formatting options as printf().  Used with:  String  File  Code similar to output streams.  Not everyone sends output to:  System.out and System.err  e.g., servlet output to web pages.
  36. 36. Formatter class example Formatter formatter = new Formatter(); formatter.format( "%-10s %-2s ","Hartford","CT"); formatter.format( "%05d-%04d",6115,11); String s = formatter.toString(); formatter.close(); s now contains: Hartford CT 06115-0011
  37. 37. Improved output  The new Formatter class, modeled after C’s printf statement, gives you much simpler formatted output  This class provides support for:  Layout justification and alignment  Common formats for numeric, string, and date/time data  Locale-specific output  Common Java types such as byte, BigDecimal, and Calendar  Limited formatting customization for arbitrary user types is provided through the Formattable interface
  38. 38. §3. Enhanced for Loop
  39. 39. Iterators  An iterator gives you every element of a collection, one at a time  The collection has a type iterator(); factory method to return a new iterator to return objects of the given type  The method boolean hasNext() tells you if there are more objects  The method type next() returns the next object  The method void remove() deletes the last object gotten  Example:  Iterator iter = integerStack.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); }
  40. 40. New for statement  The syntax of the new statement is for(type var : array) {...} or for(type var : collection) {...}  Example: for(float x : myRealArray) { myRealSum += x; }  For a collection class that has an Iterator, instead of for (Iterator iter = c.iterator(); iter.hasNext(); ) ((TimerTask) iter.next()).cancel(); you can now say for (TimerTask task : c) task.cancel();
  41. 41. Iterations, Part I List policies = new ArrayList(); . . . Iterator iter = policies.iterator(); while ( iter.hasNext() ) { renew( (Policy)iter.next() ); }  A common Java “idiom” for iteration.  Is this the best way to iterate through a collection?
  42. 42. Iterations, Part II List policies = new ArrayList(); . . . for (Iterator iter = policies.iterator(); iter.hasNext(); ) { renew( (Policy)iter.next() ); }  Another common Java “idiom” for iteration.  Is this any better?
  43. 43. Iterations, Part III  How about iterating through arrays? Policy policies[] = { … }; . . . for ( int i = 0; i < policies.length; ++i ) { renew( policies[i] ); }  Is looping through an array any better?
  44. 44. Enhanced for loop  Iterations over collections are painful.  Iterator is only used to get elements.  Iterators can be error-prone.  Iterator variable used in for loop three times – two opportunities to get it wrong.  Common cut and paste errors.  A “foreach” style loop construct would be better.  Wouldn’t it be nice if the compiler would iterate for you?
  45. 45. Enhanced for loop for Collections  For collections: List policies = new ArrayList(); . . . for ( Object policy : policies ) { renew( (Policy)policy ); }  Using the enhanced for loop is much clearer.  But, note the cast to Policy.
  46. 46. Enhanced for loop for Arrays  For arrays: Policy[] policies = { … }; . . . for ( Policy policy : policies ) { renew( policy ); }  Again, using the enhanced for loop is clearer.  And, no cast is needed to Policy.
  47. 47. Enhanced for loop Restrictions  Restrictions  Cannot be used to filter a collection.  i.e., remove elements  Cannot modify the current slot in an array or list.  e.g., replace the entire element  Provides for most common for loop “idiom”.  Provides simple iteration over a collection or an array.  More complicated processing addressed by the traditional for or while loops.
  48. 48. J2SE 1.4.0 for(Iterator iter = myArray.iterator(); iter.hasNext(); ) {     MyClass myObj = (MyClass)iter.next();     myObj.someOperation(); } J2SE 5.0 for(MyClass myObj : myArray) {     myObj.someOperation(); }
  49. 49. // Returns the sum of the elements of a int sum(int[] a) { int result = 0; for (int i : a) result += i; return result; } For Arrays ● Eliminates array index rather than iterator ● Similar advantages
  50. 50. For Each Statement  A great way to ditch annoying Iterators. Makes code more elegant and less error prone.  before  after
  51. 51. Spot the Bug Fixed Version Using the For Each Statement
  52. 52. For each loop (arrays) double[] array = {2.5, 5.2, 7.9, 4.3, 2.0}; for(double d: array) { System.out.println(d); } Iterate (forward) through the array without paying attention to indices.
  53. 53. For each loop (Collections) ArrayList<Integer> list = new ArrayList<Integer>(); list.add(7); list.add(15); list.add(-67); for(Integer number: list) { System.out.println(number); }
  54. 54. For each loop enums for( Suit s: Suit.values()){ System.out.println(s.getColor()); } values() returns an Iterator for enum types
  55. 55. §4. Static Imports
  56. 56. The “Constant Interface” antipattern  public interface Physics { public static final double AVOGADROS_NUMBER = 6.02214199e23; public static final double BOLTZMANN_CONSTANT = 1.3806503e-23; public static final double ELECTRON_MASS = 9.10938188e-31; } public class Guacamole implements Physics { public static void main(String[] args) { double moles = ...; double molecules = AVOGADROS_NUMBER * moles; ... } }  This is considered to be very poor style by smart programmers who have thought about it a lot more than I have
  57. 57. Static Import  You can now import just the static members of a class or interface  public interface Physics { // as before public static final double AVOGADROS_NUMBER = 6.02214199e23; public static final double BOLTZMANN_CONSTANT = 1.3806503e- 23; public static final double ELECTRON_MASS = 9.10938188e-31; }  import static org.iso.Physics.*; class Guacamole { public static void main(String[] args) { double moles = ...; double molecules = AVOGADROS_NUMBER * moles; ... } }
  58. 58. Static Import  Enables one to refer to static constants from a class without needing to inherit from it  If only used on occasion this technique is not very useful, but in complex cases this technique help simplify coding
  59. 59. Example  import static java.awt.BorderLayout.*;  import static java.lang.System.*; getContentPane().add(new JPanel(), CENTER); Out.println(“hello world”);
  60. 60. Static Import import static java.lang.Math.*; … int themax = max( 123123, 23475 );  Reduces typing  Alleviates need for implementing a Constant Interface  Compiler error if names clash
  61. 61. Static Import Static imports let you avoid qualifying static members with class names. Once the static member is imported then you can use it in your code without the class name prefix. //static import import static sample.SampleStaticValues.NUM_ZERO; … //need not do SampleConstants.NUM_ZERO due to static import feature if(num % 2 == NUM_ZERO){ System.out.println("The num " + num + " is: " + OddEven.even); } package sample; public class SampleStaticValues { public static int NUM_ZERO = 0; public static int NUM_ONE = 0; }
  62. 62. Static Import  In order to access static members, it is necessary to qualify references with the class they came from. double r = Math.cos(Math.PI * theta);  As a workaround people often put static members as part of an interface and inherit from that interface.  This is known as the “Constant Interface Antipattern”
  63. 63. Static Import  Using constants of another class is merely an implementation detail. Declaring that a class implements an interface is an API issue. Implementation details should not leak into APIs.  The static import construct allows you to access static members of another class without inheriting from the type containing them.
  64. 64. Static Import  members of another class are imported import static java.lang.Math.PI;  Once imported they can be used without qualification double r = cos(PI * theta);
  65. 65. Example  Before System.out.println(“Hello”); System.out.println(“World”); System.err.println(“From”); System.err.println(“Me”);  After import static java.lang.System.*; out.println(“Hello”); out.println(“World”); err.println(“From”); err.println(“Me”);
  66. 66. Static Vs. Normal import  Static imports are analogous to regular imports. In normal imports you import classes from packages, and in static imports you import static class members out of classes.  Use with care: only when frequent access is required. It is suppose to improve readability, and overuse may have an opposite effect.
  67. 67. Static import  Ability to access static members from a class without need to qualify them with a class name.
  68. 68. interface ShapeNumbers {     public static int CIRCLE = 0;     public static int SQUARE = 1;     public static int TRIANGLE = 2; } Implementing this interface creates an unnecessary dependence on the ShapeNumbers interface. It becomes awkward to maintain as the class evolves, especially if other classes need access to these constants also and implement this interface
  69. 69. To make this cleaner, the static members are placed into a class and then imported via a modified syntax of the import directive. package MyConstants;     class ShapeNumbers {     public static int CIRCLE = 0;     public static int SQUARE = 1;     public static int TRIANGLE = 2; } To import the static members in your class, specify the following in the import section of your Java source file. import static MyConstants.ShapeNumbers.*; // imports all static data You can also import constants individually by using the following syntax: import static MyConstants.ShapeNumbers.CIRCLE; import static MyConstants.ShapeNumbers.SQUARE;
  70. 70. An example of importing a Java class  For example, to use java.lang.Math. double radians = Math.toRadians(30.0); double unity = Math.pow(Math.sin(radians),2.0) + Math.pow(Math.cos(radians),2.0); double areaCircle = Math.PI * Math.pow(10.0,2.0);
  71. 71. Importing Static Members  Currently  Importing a class or interface  Why require a class name prefix?  Static Import  A variant of the import statement.  Import static methods and fields.  Similar to the import of classes and interfaces from a package.  Import individual members, or collectively.
  72. 72. With Static Import  No need to reference Math, except in import. import static java.lang.Math.*; double radians = toRadians(30.0); double unity = pow(sin(radians),2.0) + pow(cos(radians),2.0); double areaCircle = PI * pow(10.0,2.0);
  73. 73. Importing Static Members  Code is more readable.  No need to reference the class or interface names.  Code can be less understandable.  No reference to class or interfaces names.  Implementation detail added.  Commitment to the implementation.
  74. 74. Static import facility  import static org.iso.Physics.*; class Guacamole { public static void main(String[] args) { double molecules = AVOGADROS_NUMBER * moles; ... } }  You no longer have to say Physics.AVOGADROS_NUMBER  Are you tired of typing System.out.println(something); ?  Do this instead:  import static java.lang.System.out;  out.println(something);
  75. 75. §5. Enumeration Types
  76. 76. Enumerations  An enumeration, or “enum,” is simply a set of constants to represent various values  Here’s the old way of doing it: public final int SPRING = 0; public final int SUMMER = 1; public final int FALL = 2; public final int WINTER = 3;  This is a nuisance, and is error prone as well  Here’s the new way of doing it: enum Season { winter, spring, summer, fall }
  77. 77. enums are classes  An enum is actually a new type of class  You can declare them as inner classes or outer classes  You can declare variables of an enum type and get type safety and compile time checking  Each declared value is an instance of the enum class  Enums are implicitly public, static, and final  You can compare enums with either equals or ==  enums extend java.lang.Enum and implement java.lang.Comparable  Hence, enums can be sorted  Enums override toString() and provide valueOf()  Example:  Season season = Season.WINTER;  System.out.println(season ); // prints WINTER  season = Season.valueOf("SPRING"); // sets season to Season.SPRING
  78. 78. Enums really are classes  public enum Coin {  // enums can have instance variables private final int value;  // An enum can have a constructor, but it isn’t public Coin(int value) { this.value = value; }  // Each enum value you list really calls a constructor PENNY(1), NICKEL(5), DIME(10), QUARTER(25);  // And, of course, classes can have methods public int value() { return value; } }
  79. 79. Other features of enums  values() returns an array of enum values  Season[] seasonValues = Season.values();  switch statements can now work with enums  switch (thisSeason) { case SUMMER: ...; default: ...}  You must say case SUMMER:, not case Season.SUMMER:  It’s still a very good idea to include a default case  It is possible to define value-specific class bodies, so that each value has its own methods  The syntax for this is weird, and I don’t yet understand it well enough myself to lecture on it
  80. 80. Standard Approach to Constant Enumerations – Definition  int enums public class PolicyOperation { public static final int QUOTE = 1; public static final int ISSUE = 2; public static final int RENEW = 4; public static final int CANCEL = 12; public static final int ENDORSE = 16; public static final int CHANGE = 64; public static final int REINSTATE = 192; . . .
  81. 81. Simple example of Typesafe enum Construct  For a deck of cards… enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } enum Rank { DUECE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } List<Card> deck = new ArrayList<Card>(); for ( Suit s: Suit.values() ) for ( Rank r: Rank.values() ) deck.add(new Card(s,r));
  82. 82. A more complex Typesafe enum Construct public enum OperationEnum { QUOTE(1), ISSUE(2), RENEW(4), CANCEL(12), ENDORSE(16), CHANGE(64), REINSTATE(192); private int operation = 0; private OperationEnum(int op) { this.operation = op; } public boolean isNewOperation() { return (this.operation==2) || (this.operation==4) || (this.operation==192); } }
  83. 83. Using the Typesafe enum Construct void process(OperationEnum oper) { . . . switch (oper) { case ISSUE: . . . case CANCEL: . . . } // Prints “ISSUE”, not “1” System.out.println(oper); }
  84. 84. Type Safety: All statuses above may carry some business meaning, but in Java language context, these are just int values. This means any int value is a status for this Java program. So the program using these statuses can break with any int value not defined in this group.
  85. 85. Type-safe enumerations  Compiler support for Typesafe Enum pattern.  Looks like traditional enum (C, C++, Pascal).  Far more powerful.  Can be used in switch/case statements.  Can be used in for loops.
  86. 86. An enumeration is an ordered list of items wrapped into a single entity. enum Season {winter, spring, summer, fall} Usage Example for (Season s : Season.VALUES){ // } An enumeration (abbreviated enum in Java) is a special type of class. All enumerations implicitly subclass a new class in Java, java.lang.Enum. This class cannot be subclassed manually.
  87. 87. Enums  Previously, the standard way to represent an enumerated type was to use the int Enum pattern: public static final int WINTER = 0; public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3;
  88. 88. Switch with Enum Color getColor( Suit suit ) { switch( suit ) { case clubs: case spades: return Color.Black; case diamonds: case hearts: return Color.Red; default: throw new AssertionError( suit + “ not valid value” ); } }
  89. 89. Enumerated Types  Similar to enum types in C, Pascal etc. and HashTable, keyset  Enums are classes, extends java.lang.Enum  Class declaration: Class Enum<E extends Enum<E>>  Enums are final, can’t be subclassed.  Only one Constructor and is are protected.  Implement java.lang.Comparable: compareTo()  Implement Serializable
  90. 90. Fun with Enums  public enum DAYConstants { MON<,UES<WED………..  };  Class DAYConstants  {  Final staic sting MONDAY = 1;  TUESDAY = 2;  doStuff(52);  }  Pubilc int doStuff(DAYConstants day) {  }
  91. 91. Enumerated types  Enumerated types are a way of representing nonstandard data, such as days of the week, with integers:  static final int SUNDAY = 1; static final int MONDAY = 2; …  Or months of the year:  static final int JANUARY = 0; static final int FEBRUARY = 1; …  The problem with this approach is that there are so many ways to make errors:  static final int DECEMBER = 12;  int date = year + month + dayOfWeek;  Over the past few years there have been many attempts to define an idiom for making type-safe enumerations
  92. 92. Enumerated types in Java 1.5  public enum Suit {clubs, diamonds, hearts, spades}  Notice new keyword “enum”  Values of enum constants are assigned automatically public enum Coin{ penny(1), nickel(5), dime(10), quarter(25); // values Coin(int value) { this.value = value; } // constructor private final int value; // instance variable public int value() { return value; } // method }  This is very like a class declaration  Printing results in the named constant: dime, not 10  Named constants can be read in
  93. 93. Using an enumerated type  public class CoinTest { public static void main(String[] args) { for (Coin c : Coin.VALUES) System.out.println(c + ": t" + c.value() +"¢ t" + color(c)); } private enum CoinColor { copper, nickel, silver } private static CoinColor color(Coin c) { switch(c) { case Coin.penny: return CoinColor.copper; case Coin.nickel: return CoinColor.nickel; case Coin.dime: // deliberate fall through to next case case Coin.quarter: return CoinColor.silver; default: throw new AssertionError("Unknown coin: " + c); } } }
  94. 94. Advantages of enumerated types  enum types simplify code and make it more readable  Types are checked at compile time (hence, very type safe)  Performance is comparable to int constants  Each enum type has its own name space (you don't have to say Coin.dime)  You can add, reorder or even remove constants without the need to recompile other classes that use these constants  I’ve seen one source that says you do need to recompile  Printed values are informative  enum constants can be used in collections (for example, as HashMap keys)  You can add arbitrary fields and methods to an enum class  An enum type can be made to implement arbitrary interfaces  enum types can be used in switch statements  enum types are serializable
  95. 95. Disadvantages of enumerated types  Still more complexity in the language  Harder for beginners, nicer for experts!
  96. 96. Type-safe enum enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } //used Day today = Day.WEDNESDAY; switch(today){ case SUNDAY: break; //… }
  97. 97. More Complex Enum enum Suit { CLUBS(Color.BLACK), DIAMONDS(Color.RED), HEARTS(Color.RED), SPADES(Color.BLACK); private Color color; Suit(Color color) { this.color = color; } public Color getColor() { return color; } }
  98. 98. §6. Autoboxing / Unboxing
  99. 99. Autoboxing  Java distinguishes between primitive types and Objects  Primitive types, i.e., int, double, are compact, support arithmetic operators  Object classes (Integer, Double) have more methods: Integer.toString()  You need a “wrapper” to use Object methods: Integer ii = new Integer( i ); ii.hashCode()  Similarly, you need to “unwrap” an Object to use primitive operation int j = ii.intValue() * 7;  Java 1.5 makes this automatic:  Before: ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, new Integer(42)); int total = (list.get(0)).intValue();  After: ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, 42); int total = list.get(0);
  100. 100. Auto boxing and unboxing  Java won’t let you use a primitive value where an object is required--you need a “wrapper”  myVector.add(new Integer(5));  Similarly, you can’t use an object where a primitive is required--you need to “unwrap” it  int n = ((Integer)myVector.lastElement()).intValue();  Java 1.5 makes this automatic:  Vector<Integer> myVector = new Vector<Integer>(); myVector.add(5); int n = myVector.lastElement();  Other extensions make this as transparent as possible  For example, control statements that previously required a boolean (if, while, do-while) can now take a Boolean  There are some subtle issues with equality tests, though
  101. 101. www.themegallery.com Autoboxing / Unboxing Example  Traditional “boxing” example: List ssnList = new ArrayList(); . . . int ssn = getSocSecNum(); . . . Integer ssnInteger = new Integer(ssn); ssnList.add(ssnInteger);  Why do I have to convert from int to Integer?
  102. 102. Autoboxing / Unboxing Example #1  “Autoboxing” example: List ssnList = new ArrayList(); . . . int ssn = getSocSecNum(); . . . ssnList.add(ssn);  No need for an explicit conversion to Integer.
  103. 103. Autoboxing / Unboxing  The need to explicitly convert between primitive types and wrapper objects.  Such as primitive type int, and wrapper object Integer.  Can’t put primitives into Collections.  Autoboxing and Unboxing  Automatic conversion by the compiler  Eliminates casts  Automatically part of method invocation, assignment conversion, numeric promotion.  Wouldn’t it be nice if the compiler would perform these conversions for you?
  104. 104. Autoboxing / Unboxing Example #2  Autoboxing/Unboxing used in other ways. double area(double height, double width) { return height * width; } . . . Double h = new Double(…); double w = …; double a = area(h,w); Double A = area(h,w);
  105. 105. Autoboxing / Unboxing Example #3  And others: Double premium = new Double(123.45); Double tax = premium * 0.05; double fee = 5.95; Double totalPremium = premium + tax + fee;  This is an example.  Mixing primitives and objects.  (Note: Don’t multiply two floating point values and expect to get an accurate result!)
  106. 106. Boxing / Unboxing  Collections hold only objects, so to put primitive data types it needs to be wrapped into a class, like int to Integer.  It is a pain to wrap and unwrap.  Wouldn’t it be nice if the compiler took care of it for you?
  107. 107. J2SE 1.4.0 ArrayList arrayList = new ArrayList();     Integer intObject = new Integer(10); arrayList.add(intObject); // cannot add 10 directly J2SE 5.0 ArrayList arrayList = new ArrayList();     arrayList.add(10); // int 10 is automatically wrapped into Integer
  108. 108. Autoboxing and Unboxing  Autoboxing:  Automatic converting of primitives into wrapper classes  Integer x = 10;  Unboxing  Automatic converting of wrapper classes into primitives  double PI = new Double(3.14);
  109. 109. §7. Improvement / Performance
  110. 110. Analyze Memory Heap Dump Any problem in pure Java code throws a Java exception or error. Java exceptions or errors will not cause a core dump (on LINUX systems) or a Dr.Watson error (on WIN32systems). Any serious Java problem will result in an OutOfMemoryError thrown by the JVM with the stack trace and consequently JVM will exit. These Java stack traces are very useful for identifying the cause for an abnormal exit of the JVM. So is there a way to know that OutOfMemoryError is about to occur? The Java JDK 1.5 has a package called java.lang.management which has useful JMX beans that we can use to manage the JVM. One of these beans is the MemoryMXBean.
  111. 111. StringBuilder Class  Introduced a new class java.lang.StringBuilder.  It is like unsunchronized StringBuffer.  Faster than StringBuffer.  An improvement upon StringBuffer  Allows quicker concatenation of strings.  Why use it?  Creating new Strings in a loop can be inefficient because of the number new objects that are created and discarded.  StringBuilder.append(<type> <value>)  StringBuilder.insert(<type> <value>)  No synchronization! Not safe for use by multiple threads
  112. 112. Performance  Faster startup time  Better garbage collection; low pause option
  113. 113. §8. Complementary Features
  114. 114. Complementary Features  Generics improve enhanced for loop  Generics and auto-boxing/unboxing allow Enumerated types  Variable args improve API usability  Variable args allow formatted I/O
  115. 115. §9. Final Comments
  116. 116. "The new language features all have one thing in common: they take some common idiom and provide linguistic support for it. In other words, they shift the responsibility for writing the boilerplate code from the programmer to the compiler." Final Comments  Better expressiveness  Current Java “idioms”  Java “boilerplate” code  New language features  Shift boilerplate code from programmer to compiler.  Easier to write. Reduces the chances for bugs.  Easier to read. Less code to accomplish the same result.  Increased type safety  Catch bugs at compile time, not run time.
  117. 117. If you have any queries, Please feel free to contact me
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×