Your First Cup: An Introduction to the Java EE Platform


Add a java.util.Logger instance and a business method that calculates the difference in age in years between Duke and the user, and creates a new FirstcupUser entity.

  1. Directly after the class declaration, paste in the following code:

    private static Logger logger = 

    This code creates a logger for the session bean.

  2. Right-click in the editor window and select Insert Code, then Add Business Method.

  3. Set the name to getAgeDifference and the return type to int.

  4. Under Parameters click Add, set the Name to date and the Type to java.util.Date, then click OK.

  5. Replace the body of the getAgeDifference method with the following code:

    	int ageDifference;
    	Calendar theirBirthday = new GregorianCalendar();
    	Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);
    	// Set the Calendar object to the passed in Date
    	// Subtract the user's age from Duke's age
    	ageDifference = dukesBirthday.get(Calendar.YEAR) - 
    	theirBirthday.get(Calendar.YEAR);"Raw ageDifference is: " + ageDifference);
    	// Check to see if Duke's birthday occurs before the user's. If so, 
    	// subtract one from the age difference
    	if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {
    	// create and store the user's birthday in the database
    	FirstcupUser user = new FirstcupUser(date, ageDifference);
"Final ageDifference is: " + ageDifference);
    	return ageDifference;

    This method creates the Calendar objects used to calculate the difference in age between the user and Duke and performs the actual calculation of the difference in age.

    Similar to the DukesAgeResource.getText code, getAgeDifference subtracts Duke's birthday year from the user's birthday year to get a raw age difference. If Duke's birthday falls before the users, and the raw difference is more than 0, subtract one year from the age difference.

    A new FirstcupUser entity is created with the user's birthday and age difference, then stored in the JavaDBTM database by calling the EntityManager's persist method.

    The final age difference is returned as an int.

  6. Right-click in the editor window and select Format.

  7. Right-click in the editor window and select Fix Imports.

  8. Choose the java.util.logging.Logger fully-qualified name for the Logger class.

  9. Click OK.

  10. Select File -> Save.