# Java 5 Overview

- Java 1.5
- Tiger
- Released end of September 2004

# Some Additions

- Generics - Like C++ templates
- Enhanced for loop
- Varargs - Variable length parameter list
- Formatted IO
- Auto-boxing/unboxing
- Enumerated types
- StringBuilder
- ProcessBuilder
- Metadata (Annotations)
- static import
- And many others...

# Generics

- Like C++ templates
- Used extensively in Collections
  - ArrayList<String> words;
- Advantages
  - Safety: Prevents adding wrong type.
  - Clarity: Reader can see intention more clearly.
  - Downcasting not explicitly required.
- However
  - Everything is still stored as Object internally.
  - No speed advantage.
- Type parameters are typically simple, but can be complicated.
  - Can specify that types that extend something.
  - Are a class that implements an interface.
  - etc.

# Generics - Parmeterizing a class

Example from madbean.com (modified)

    public class Pair<X, Y> {
        private final X a;
        private final Y b;

        public Pair(X a, Y b) {
            this.a = a;
            this.b = b;
        }

        public X getFirst() {
            return a;
        }

        public Y getSecond() {
            return b;
        }
    }

# Generics Poem

Joshua Bloch:

> To the most despised cast
> We'll bid a fond farewell at last
> With generics' burning spear
> The need for cast will disappear

# Enhanced for Loop

- Going over each element of a structure is common.
- New for loop allows this.

          for (type variable : collection-or-array) {
              ... body of loop
          }

- Works for arrays and anything that implements Iterable.

# Enhanced for Loop Example

- Pre Java 1.5 (non-generic, uses Iterator)

      void disableAll(List buttons) {
          for (Iterator it = buttons.iterator(); it.hasNext(); ) {
              JButton btn = (JButton) it.next();
              btn.setEnabled(false);
          }
      }

- Java 1.5 (generic, new for loop)

      void disableAll(List<JButton> buttons) {
          for (JButton btn : buttons) {
              btn.setEnabled(false);
          }
      }

# Enhanced for Loop Poem

Joshua Bloch:

> While Iterators have their uses
> They sometimes strangle us like nooses
> With enhanced-for's deadly ray
> Iterator's kept at bay

# Variable Parameter Lists

- Last formal parameter may be marked with "..."
- All arguments from that point must be that type.
- They will be put into an array of that type.
- Example

      public static int sum(int ... nums) {
          int sum = 0;
          for (int x : nums) {
              sum += x;
          }
          return sum;
      }

# Enums

    public enum GameState (WIN, LOSS, DRAW, CONTINUING);

- New `enum` keyword.
- Defines a new class (`GameState`).
- Defines static method `values()` which returns array of values.
- Defines static method `valueOf(String)` which converts string to value.
- Defines `equals(...)`, `toString()`, and `compareTo(...)`

# Enum Example

    public enum GameState (WIN, LOSS, DRAW, CONTINUING);
    . . .
       for (GameState st : GameState.values()) {
           System.out.println(st);
       }
       . . .
       GameState state;
       . . .
       switch (state) {
           case WIN: ..
                   break;
           case LOSS: ...
                   break;
           default: ...
       }

# Static import

- Can import constants without having to qualify by class name.

-     import static javax.swing.JFrame.*;
      ...
         window.setDefaultCloseOperation(EXIT_ON_CLOSE);

# Formatted Output - printf

- Similar to C printf

-     System.out.printf("%s %6d\n", name, age);

# Formatted Input - printf

- For reading and converting values from a charcter input stream.

-     Scanner input = new Scanner(System.in);
          String name = input.next();
          int age     = input.nextInt();
          input.close();

# ProcessBuilder

- Allows starting an operating system process.
- Takes program name and parameters.
- Create a process. Call start() to run it.
- Example from ?

      Process p = new ProcessBuilder("notepad", "\\autoexec.bat").start();

# StringBuilder

- Drop-in replacement for StringBuffer.
- Unsynchronized
- Therefore slightly faster.
- Prefer StringBuilder to StringBuffer for single thread programs.

# Auto-boxing/unboxing

- Collections require elements to be objects.
- Java now will do automatic conversion between primitive types and their wrapper types: eg, int to/from Integer.
- Example - 1.4

      ArrayList nums = new ArrayList();
      . . .
      nums.add(new Integer(25));
      . . .
      int x = ((Integer)nums.get(0)).intValue();

- Example - Generic

      ArrayList<Integer> nums = new ArrayList<Integer>();
      . . .
      nums.add(new Integer(25));
      . . .
      int x = nums.get(0).intValue();

- Example - Generics and Autoboxing

      ArrayList<Integer> nums = new ArrayList<Integer>();
      . . .
      nums.add(25);
      . . .
      int x = nums.get(0);

# MetaData (Annotations)

- Allows defining arbitrary tags to mark classes, methods, etc.
- Intent is that tags will be used by IDEs / preprocessors.
- Tags can be either compile-time or run-time.
- Use @.
- This is a very powerful facility, with unknown consequences.

# End