+ All Categories
Home > Documents > 23 Java5 Features

23 Java5 Features

Date post: 05-Apr-2018
Category:
Upload: vinayakam-arumugam
View: 220 times
Download: 0 times
Share this document with a friend

of 13

Transcript
  • 7/31/2019 23 Java5 Features

    1/13

    2009 Marty Hall

    A Quick Summary

    Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1. x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.2

    2009 Marty Hall

    For live Java training, please see training courses athtt ://courses.coreservlets.com/. Servlets JSP StrutsClassic, Struts 2, JSF 1. x , JSF 2.0, Ajax (with jQuery,

    Dojo, Prototype, Ext, etc.), GWT, Java 5, Java 6, Spring,, .

    Taught by the author of Core Servlets and JSP , More

    Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1. x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    , .venues, or customized versions can be held on-site at your

    organization. Contact [email protected] for details.

  • 7/31/2019 23 Java5 Features

    2/13

    Agenda

    The for/each loop Scanner and command-line input Generics Autoboxing Varargs Printf Reading command-line input

    4

    For/Each Loops Idea

    Instead of looping with a numeric index, set a localvariable to each item of a collection or array in order

    Basic syntax for T e item: collectionOrArra OfT es

    doSomethingWith(item);}

    Applies to , , , , Arrays

    5

  • 7/31/2019 23 Java5 Features

    3/13

    For/Each Loops: Example

    public static void listEntries(String[] entries) {

    System.out.println(entry);}

    }

    ResultString[] test = {"This", "is", "a", "test"};listEntries(test);

    Thisisatest

    6

    Reading Simple Input:

    Basic Syntax ac a canner o ys em. n Call nextLine, nextInt, nextDouble, etc

    Exam lesScanner inputScanner =

    new Scanner(System.in);

    String s = inputScanner.nextLine();int i = inputScanner.nextInt();double d = inputScanner.nextDouble();

    Notes Scanner for System.in is useful only for simple testing

    Use a GUI in a real application , ,

    Process, and more

    7

  • 7/31/2019 23 Java5 Features

    4/13

    Example: Printing Random

    import java.util.*;

    public class RandomNums {

    public static void main(String[] args) {System.out.print("How many random nums? ");canner npu canner = new canner ys em. n ;

    int n = inputScanner.nextInt();for(int i=0; i

  • 7/31/2019 23 Java5 Features

    5/13

  • 7/31/2019 23 Java5 Features

    6/13

    Autoboxing

    You cannot insert primitives into tables, lists, orany ng e se expec ng an ec

    Java provides wrapper types for this purpose (int Integer, etc.) In Java 5, s stem converts automaticall Performance Warning

    Every insert converts to wrapper type (Integer above) Ever retrieval converts to rimitive t e int above Use arrays for performance-critical access

    Old NewList nums = new ArrayList(); List nums =int i = someCalculation();nums.add(new Integer(i));...

    new ArrayList();nums.add(someCalculation());...

    Integer val =(Integer)nums.get(someIndex);

    int num = val.intVal() + 1;

    int num =nums.get(someIndex);

    nums.add(num + 1);12

    Example: Finding State Abbreviations

    public class StateMap extends HashMap { public StateMap() {

    stateMap = new HashMap();for(String[] state: stateArray) {

    stateMap.put(state[0], state[1]);

    } public HashMap getStateMap() {

    return(stateMap);

    private HashMap stateMap;

    public String[][] getStateArray() {

    } private String[][] stateArray =

    { { "Alabama", "AL" },as a , ,

    { "Arizona", "AZ" }, .}

    13

  • 7/31/2019 23 Java5 Features

    7/13

    Example: Continued

    public class MapTest {

    StateMap states = new StateMap();HashMap stateAbbreviationTable =

    s a es.ge a e ap ;Scanner inputScanner = new Scanner(System.in);System.out.println("Enter state names. " +

    "Hit RETURN to quit.");String stateName;String abbreviation;

    14

    Example: Continuedwhile(true) {

    " ". .stateName = inputScanner.nextLine();if (stateName.equals("")) {

    ys em.ou .pr n n ome aga n soon. ; break;

    }a rev a on =

    stateAbbreviationTable.get(stateName);if (abbreviation == null) {

    abbreviation = "Unknown";}System.out.println(abbreviation);

    }}

    }15

  • 7/31/2019 23 Java5 Features

    8/13

  • 7/31/2019 23 Java5 Features

    9/13

    Simple Example: printf vs. println

    General idea

    argument list. %n means newline.

    Exampleublic static void rintSomeStrin s

    String firstName = "John";String lastName = "Doe";int numPets = 7;String petType = "chickens";System.out.printf("%s %s has %s %s.%n",

    firstName, lastName, numPets, petType);" ". .

    " has " + numPets + " " + petType + ".");

    } Result:John Doe has 7 chickens.John Doe has 7 chickens.18

    Controlling Formatting Different flags

    s or s r ngs, or oa ng po n num ers, ordates, etc.

    Various extra entries can be inserted To control width, number of digits, commas, justification,

    type of date format, and more

    printf uses mini-language; complete coverage would take

    an entire lecture , For complete coverage, see

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax

    Using + instead of , between arguments (printf uses varargs) Forgetting to add %n at the end if you want a newline (not automatic)

    19

  • 7/31/2019 23 Java5 Features

    10/13

    Printf Formatting Options

    Stands For Options Example%s String. Can output any data

    type. If arg is Object, toStringis called.

    %width sGives min num of chars.Spaces added to left if

    needed.

    printf("%8s", "Hi")outputs

    " Hi"

    %d Decimal.Outputs wholenumber in base 10. Also %xand %o for hex and octal.

    %width d %,width dGives min width; inserts

    commas.

    printf("%,9d", 1234)outputs

    " 1,234"

    %f Floating point.Lets you lineup decimal point and controlprecision.

    %width .precision f%,width .precision f

    width includes comma and

    printf("%6.2f", Math.PI)outputs

    " 3.14"decimal point.

    %t x Time (or date). %tA for day,%tB for month, %tY for year,

    Date now = new Date();printf("%tA, %tB ,%tY", now, now, now)

    . outputs"Thursday, November 17, 2005"

    %n Outputs a newline and a %, respectively. No automatic newline as with println.20

    Printf Example: Controlling Width

    public static void printSomeSalaries() {

    { new CEO("Steve Jobs", 3.1234),new CEO("Scott McNealy", 45.5678),new e ezos , . ,new CEO("Larry Ellison", 6789.0),new CEO("Bill Gates", 78901234567890.12)};

    " ". .for(CEO ceo: softwareCEOs) {

    System.out.printf("%15s: $%,8.2f%n" ,. , .

    }}SALARIES:

    Steve Jobs: 3.12Scott McNealy: $ 45.57

    Jeff Bezos: $ 567.98Larry Ellison: $6,789.00

    21

  • 7/31/2019 23 Java5 Features

    11/13

    Printf Example: Controlling Width

    public class CEO {

    private double salary; // In billions

    public CEO(String name, double salary) {this.name = name;this.salary = salary;

    }

    public String getName() { return(name); }

    }

    22

    Variable-Length Arguments The printf method takes any number of

    arguments You can use overloading to define a few versions of

    ,number of arguments

    To do this yourself, use " type ... variable " variable becomes an array of given type Only legal for final argument of method

    public void printf(String format, Object ... arguments) public int max(int ... numbers)

    Can call max(1, 2, 3, 4, 5, 6) or max(someArrayOfInts)

    Use sparingly

    You usuall know how man ar uments are ossible23

  • 7/31/2019 23 Java5 Features

    12/13

    Varargs: Example

    public class MathUtils {

    int minimum = Integer.MAX_VALUE;

    for(int number: numbers ) {if (number < minimum) {

    minimum = number;}

    }return(minimum);

    }

    System.out.printf("Min of 2 nums: %d.%n",

    min(2,1));" " min(2,4,6,8,1,2,3));

    }}24

    Summary For/Each loops are simple

    an an e a s ua ons, u very easy n e cases nwhich they do apply

    Scanner simplifies basic parsing Easier than String.split and Integer.parseInt

    Generics simplify code . .

    Autoboxing is convenient But can hide performance costs

    Java finally has printf No more clumsy println's with string concatenation

    For formatting, math, and other special-purposes methods

    25

  • 7/31/2019 23 Java5 Features

    13/13

    2009 Marty Hall

    Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1. x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.26


Recommended