Your First Cup: An Introduction to the Java EE Platform

ProcedureImplement the getText Method

Add code to DukesAgeResource.getText that calculates Duke's age at the time of the request. To do this, use the java.util.Calendar and java.util.GregorianCalendar classes to create an object representing the date May 23, 1995, Duke's birthday. Then create another Calendar object representing today's date, and subtract today's year from Duke's birth year. If today's date falls before May 23, subtract a year from this result. Then return the result as a String representation.

  1. Highlight the current code in getText and replace it with the following code:

    // Create a new Calendar for Duke's birthday
    Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);
    // Create a new Calendar for today
    Calendar now = GregorialCalendar.getInstance();
    // Subtract today's year from Duke's birth year, 1995
    int dukesAge = now.get(Calendar.YEAR) - dukesBirthday.get(Calendar.YEAR);
    dukesBirthday.add(Calendar.YEAR, dukesAge);
    // If today's date is before May 23, subtract a year from Duke's age
    if (now.before(dukesBirthday)) {
    // Return a String representation of Duke's age
    return new String("" + dukesAge);
  2. Right-click in the editor window and select Format.

  3. Right-click in the Editor and select Fix Imports.

  4. Select File -> Save from the menu to save the file.