.
.
Java Technology Fundamentals Newsletter header
    July 30, 2003    

In this Issue

imageJava Programming Language Basics: Recursion Basics
imageJava Bits: Language Essentials Short Course
imageMaking Sense of the Java Class: GregorianCalendar and Calendar
imageProgram Challenge: Finally
imageJava Workbook: Error Handling Exercise
imageSun Developer Network and Barnes & Noble.com: Joined forces with Barnes & Noble
imageFor More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

.

Java Programming Language Basics

Recursion Basics

Recursion is a programming technique that isn't specific to the Java programming language. The technique involves solving problems through method calling. Before going into the details of how to program recursively, let us look more at how recursive thinking works.

First, you need to learn to think recursively: solving a problem by repeatedly solving smaller versions of the same problem. For example, in mathematics, there is the concept of N! (Pronounced N factorial). N! is defined for all positive integers as the product of all integers from 1 to N, inclusive. Thus, 4! would be 4*3*2*1 or 24.

Thinking recursively doesn't just involve creating a for-loop and multiplying all the numbers together though. Instead, thinking recursively provides a two part definition:

1! = 1
and
N! = N*(N-1)!

The 1! is what is known as a base case. Since N! is only defined for positive integers, this makes sure that the recursion isn't infinite, eventually producing a condition that isn't itself recursive. Eventually, the base condition will be hit. For any positive number N greater than 1, N! is defined to be N times (N-1)!. So, 4! would be defined to be 4*3!. But, what is 3!? That is 3*2!. And, 2! is 2*1!, where 1! is the base case of 1.

Put to code, this would look as follows:

public class Fact {
   public static int factorial(int n) {
     int returnValue;
     if (n < 1) {
       throw new IllegalArgumentException("Illegal value: " + n);
     } else if (n == 1) {
       returnValue = n;
     } else {
       returnValue = n * factorial(n-1);
     }
     return returnValue;
   }

   public static void main(String args[]) {
     for (int i=1; i<10; i++) {
       System.out.println(factorial(i));
     }
   }
}

The example code also includes test code to show the values for 1! through 9!.

Notice that each call to the factorial method decrements the parameter passed.

For some problems, recursion isn't always the best solution. In the N! case, this could just have easily been done with a simple for-loop as follows:

int factorial = 1;
for (int i=2; i<10; i++) {
   factorial *= i;
}
System.out.println("9! is " + factorial);

Either solution for N! works, but the developer may have reasons to choose one solution over the other.

In another example, there is the mathematical concept of Fibonacci numbers, where each number in a series is the sum of the prior two numbers.

The sequence of Fibonacci number starts as follows:

1 1 2 3 5 8 13 21 34 55 89 ...

The base cases (first two digits) here are both fixed to be 1.

Thinking recursively, you can write a recursive method to calculate the Fibonacci values as follows:

int fibonacci(int n) {
   int returnValue;
   if (n < 2) {
     returnValue = 1;
   } else {
     returnValue = fibonacci(n-1) + fibonacci(n-2);
   }
   return returnValue;
}

While definitely simple to write the method as such, the calculations necessary to determine any Fibonacci numbers can be considered a bit wasteful. For every fibonacci(n-1) calculated, you have to calculate fibonacci(n-2). But, the result is thrown away before fibonacci(n-2) is then recalculated. Adding in some memory still lets this problem be solved recursively, but the simple technique of just calling the method recursively is not the best solution.

With a little bit of upfront thought you can determine when recursion is good for the programming problem.

.
.

Java Bits

Language Essentials - Short Course

The Java programming language is a modern, evolutionary computing language that combines an elegant language design with powerful features that were previously available primarily in specialty languages. In addition to the core language components, Java platform software distributions include many powerful, supporting software libraries for tasks such as database, network, and graphical user interface (GUI) programming. This course introduces the core Java programming language features.

The Java programming language is a true object-oriented (OO) programming language. The main implication of this statement is that in order to write programs, you must work within its object-oriented structure.

Object-oriented languages provide a framework for designing programs that represent real-world entities such as cars, employees, insurance policies, and so on. Representing real-world entities with non-object-oriented languages is difficult because it's necessary to describe entities such as a truck with rather primitive language constructs such as Pascal's record, C's struct, and others that represent data only.

Also, in non-object-oriented languages, the behavior of an entity must be handled separately with language constructs such as procedures and/or functions, hence, the term procedural programming languages. In procedural programming, the programmer must manually associate a data structure with the appropriate procedures that operate on, that is, manipulate, the data.

In contrast, object-oriented languages provide a more powerful class construct for representing user-defined entities. The class construct supports the creation of user-defined data types, such as Employee, that represent both the data that describes a particular employee and the manipulation or use of that data.

Java programs employ user-defined data types liberally. Designing nontrivial Java classes requires, of course, a good working knowledge of Java syntax. The following sections illustrate Java syntax and program design in the context of several Java class definitions.

Read the full short course

.
.

Making Sense of the Java Class

Classes GregorianCalendar and Calendar

Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision. See Date for information about the Date class.)

Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The platform provides one concrete subclass of Calendar: GregorianCalendar. Future subclasses could represent the various types of lunar calendars in use in many parts of the world.

Because Calendar is an abstract class, a Calendar object is never instantiated. The static methods defined in the Calendar class are accessed using the Calendar class name with the dot operator and the attribute:

Calendar.DAY_OF_WEEK

The GregorianCalendar class is a concrete subclass of Calendar, and provides the standard calendar. GregorianCalendar implements Gregorian and Julian calendars. Dates are computed by extrapolating the current rules indefinitely far backward and forward in time.

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. Week 1 for a year is the earliest seven day period starting on getFirstDayOfWeek that contains at least getMinimalDaysInFirstWeek days from that year. Therefore, it depends on the values of getMinimalDaysInFirstWeek, getFirstDayOfWeek, and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (as needed).

Values calculated for the WEEK_OF_MONTH field range from 0 to 6. Week 1 of a month (the days with WEEK_OF_MONTH = 1) is the earliest set of at least getMinimalDaysInFirstWeek() contiguous days in that month, ending on the day before getFirstDayOfWeek(). Unlike week 1 of a year, week 1 of a month may be shorter than 7 days, need not start on getFirstDayOfWeek(), and will not include days of the previous month. Days of a month before week 1 have a WEEK_OF_MONTH of 0.

For example, the following application creates a Gregorian calendar, and prints it to the console, marking today's date with an *:

import java.util.*;

public class CalendarExample
 {
 
  public static void main(String []args)
   {
   //Construct new calendar
   
   GregorianCalendar d = new GregorianCalendar();
   
   int today = d.get(Calendar.DAY_OF_MONTH);
   int month = d.get(Calendar.MONTH);
   
   d.set(Calendar.DAY_OF_MONTH, 1);
   
   int weekday = d.get(Calendar.DAY_OF_WEEK);
   
   System.out.println("Sun Mon Tue Wed Thu Fri Sat");
   
   for (int i = Calendar.SUNDAY; i < weekday; i++)
       System.out.print("    ");
       
   do
   {
     int day = d.get(Calendar.DAY_OF_MONTH);
     
     if (day < 10) System.out.print(" ");
     System.out.print(day);
     
     if(day == today)
       System.out.print("* ");
     else 
       System.out.print("  ");
       
     if (weekday == Calendar.SATURDAY)
       System.out.println();
           
     d.add(Calendar.DAY_OF_MONTH, 1);
     weekday = d.get(Calendar.DAY_OF_WEEK);
     
     }
     
     while (d.get(Calendar.MONTH) == month);
     
     if (weekday != Calendar.SUNDAY)
       System.out.println();
       
   }
}

The results look something like:

.
.

Program Challenge

Write a program to determine if a given word is a palindrome, a word that reads the same backwards as forwards.

See a possible solution to the Challenge

.
.

Take an Online Quiz

Java Workbook Error Handling Exercise

.
.

Sun Developer Network and Barnes & Noble.com have joined forces to offer developers discounts on the latest Java books, bestsellers, DVDs and Music through the Sun Developer Network online bookstore. Developers save 10% off the list price of all non-discounted titles. Free shipping is also offered (see site for details) and the discount is applied automatically at checkout.

Start saving by going to: http://sun.com/developers

.
.

For More Information

Class Calendar

Class GregorianCalendar

The finally Block

Handling Errors with Exceptions

.
.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com

Go to the subscriptions page to subscribe or unsubscribe to this newsletter.

ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/


Copyright 2003 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Sun 
Microsystems, Inc.
image
image