Sun Java Solaris Communities My SDN Account Join SDN
 
Java Technology Fundamentals Newsletter Index

New-to-Java Programming Center Supplement

 

New-to-Java Programming Center
Programming Center Supplement

Welcome to the Java Developer ConnectionSM New to Java Programming Center Supplement!

This monthly supplement provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to JavaTM Programming Center.

CONTENTS

1. Java Programming Language Basics

    Classes, Objects, and Constructors: What's the Difference?

2. Making Sense of the Java Class Libraries

    The ArrayList Class

3. Program Challenges

    ItemsListing application

4. Java Bits

    Why Command-Line Arguments are not 100% Pure Java Technology

5. New to Java Technology Forum Latest

    Stored Calculations on Date

6. New to the New to Java Programming Center

    Word Games for Java technology Terminology

7. For More Information

    Links to articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

8. Program Challenge Solution and Explanation

    Possible solution to the Scores application.

9. Downloading the Java 2 Platform

    To follow examples and write the Program Challange, you need to download the Java 2 Platform.

Java Programming Language Basics

Classes, Objects, and Constructors: What's the Difference?

Distinguishing between classes, objects, and constructors can be confusing. Understanding differences between these terms is important so you know when you're designing an object versus using an object, and how your objects are constructed.

Classes and objects are the foundation of Java programming. All objects are based on classes. A class is a recipe or plan for an object. Classes specify the following:

  1. The data (through fields, attributes, or variables)

  2. How to manipulate the data (through methods)

  3. How to construct, or instantiate, the object (optional)

A class is a template that defines an object in the same way a recipe defines your favorite food. A recipe's focus is on food, and the class' focus is on data. A class is not an object any more than a recipe for apple pie is a pie.

Suppose you write a class called BankAccount that specifies data:

double account = 0;
String name = "";

You define methods that operate on that data. To use this class, instantiate an instance of the class by calling the constructor. The constructor is a special method that creates the object of the class from which it is called.

For instance:
BankAccount ba = new BankAccount()

creates a BankAccount object.

Constructors may include parameters, so when the object is instantiated, it is initialized with the arguments that are supplied.

In the previous example BankAccount is initialized without any parameters. But the class can specify that the constructor take parameters:

BankAccount(double account, String name) { 
  account = account;
  customername = name; }

When BankAccount is instantiated with BankAccount ba1 = new BankAccount(900, "Jane Doe"); this BankAccount object ba1 has an account amount and a name to go with the account.

Create as many constructors as you need. If you don't write a constructor, a default constructor is provided for you like the first constructor shown above in BankAccount(){}. The default constructor instantiates an object without parameters.

The J2SE documentation details how to instantiate objects for the predefined classes in the library by calling the constructor or constructors.

For instance, consider the following paragraph from the J2SE documentation:

FileInputStream(File file) // constructor

creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

If you want to use this FileInputStream, instantiate the class by calling its constructor:

FileInputStream fin = new FileInputStream("bankaccount.dat");

* Note: FileInputStream is a class in the IO package. Remember to import java.io.*

Providing constructors ensures that objects are built exactly as desired, with the data specified in the parameters.

Making Sense of the Java Class Libraries

The ArrayList class explained:

Applications frequently need to store a group of data within a single object. Arrays serve this purpose well, but sometimes you need to dynamically increase or decrease the number of elements in the array, or have it hold different types of data.

This is common among applications like online stores. A customer adds merchandise to a shopping basket, and behind the scene, the items are stored or removed automatically.

For this kind of growing and shrinking of a data group, you can use the Vector, or the newer ArrayList class from the java.util package.

An ArrayList holds as many objects as you need it to.

ArrayList has several constructors, depending on how you need the ArrayList built. The following two constructors will get you started:

ArrayList() constructs an ArrayList with zero capacity by default, but will grow as you add to it: ArrayList al = new ArrayList();
ArrayList(int initialCapacity) constructs an empty ArrayList with a specified initial capacity:
ArrayList al2 = new ArrayList(5);

An ArrayList object holds only references to objects. To store primitives such as double, long, or float, use a wrapper class, as demonstrated below. To add the objects to the ArrayList, call its methods with the dot operator:


al.add("Java Technology Book"); //adds a String
al.add(new Double(40.00)); //adds a double in a class wrapper
                           //More about class wrappers in a future issue

System.out.println(al.size()); //prints the size of 
                               //the ArrayList

If you need to cycle through the ArrayList elements, use the Iterator class and its methods hasNext and next:


Iterator alIt = al.iterator();

while (alIt.hasNext()) {
  System.out.println(alIt.next() + " ");
  }

ArrayList is one of many classes in the Collection Framework, which provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection.

See For More Information for links to tutorials and articles on this topic.

Program Challenge

You've learned about classes, objects, constructors, and the ArrayList class. Put these concepts together to create the following application:

  1. Create a class called ItemsListing.

  2. Create a constructor for ItemsListing that takes a parameter: item.

  3. In class ItemsListing, use the following method to convert the variable data to a String:


  4. 
    
       public String toString() {
       	String s = "Item: " + item;
       	return s;
       	}     
    



  5. Create a public class called ArrayListItems that contains the main method.

  6. In main, instantiate three objects of ItemsListing, providing the data for the constructor.

  7. Create an ArrayList.

  8. Populate the ArrayList with the three objects, using the add method.

  9. Pass the ArrayList to an Iterator.

  10. Use a while loop and the hasNext method to print the contents of the ArrayList.

  11. Save the file as ArrayListItems.java and compile, then run.

The results should look similar to the following:


Item: Snorkel
Item: Diving Mask
Item: 6.5 mm Wet Suit

Java Bits

Why Command-Line Arguments are not 100% Pure Java Technology

Applications that require command-line arguments are not 100% Pure Java because not all systems have a command line available.

If you have a command line on your system, using command-line arguments during application development is useful for testing code logic, or reading in files. Otherwise, consider using properties so that your applications are portable. See properties in a future issue of the New to Java Programming Center supplement.

New to Java Technology Forum Latest

Compile the file:
I need to generate a weekly report. How can I calculate sysdate minus seven days and store it in a String?

See: the Forums to respond to this question.

New to the Java Programming Center

Test your knowledge of Java technology terminology with this new crossword puzzle online game. Look for new Java related puzzles in the future.

For More Information

The Java Tutorial Trail: Lesson: Object Basics and Simple Data Object

Ess entials of the Java Programming Language, Part 2 Lesson 8: Object-Oriented Programming

Class ArrayList

Fundamentals of the Collection Framework:

Essentials of the Java Programming Language, Part 2 Lesson 5: Collection

Tech Tips August 09, 1999

POSIX Conventions for Command Line Arguments

Java 2 SDK, Standard Edition, version 1.3: Summary of New Features and Enhancements

Program Challenge Solution

This is one possible solution to the Program Challenge:


//ArrayList class is in the 
//java.util package
import java.util.*;

class ItemsListing {
  
  
   
   private String item;
   
   
    // Constructor with parameters. When each object
   // is instantiated, or created, arguments must be
   // provided so the object contains the required 
   // data.
   public ItemsListing (String item) {
                                    
         // The keyword this is necessary to prevent confusion
         // over which object you are referring to when
         // you instantiate multiple objects.
         
         this.item = item;
         
         }
         
    
      // Method to convert the objects to Strings. 
         
         public String toString() {
         
         String s = "Item: " + item;
   	  return s;
   	}	  
         
 }
 
 public class ArrayListItems {

   public static void main(String []args) {
   
          
       // Creates an ArrayList to store each object, and 
       // adds each object with the add method and dot operator
       // as well as with the arguments for each object.
       
         
       ArrayList items = new ArrayList();
       
       items.add(new ItemsListing("Snorkel"));
       items.add(new ItemsListing("Diving Mask"));
       items.add(new ItemsListing("6.5 mm Wet Suit"));
       
      // The ArrayList is then passed to an Iterator
      
       Iterator iterateItems = items.iterator();
       
      // while loops through each element of the ArrayList
      // and prints the results 
      
       while (iterateItems.hasNext()) {
       
          System.out.println(iterateItems.next());
         
          }
        
       }
 } 
 

Results:


Snorkel
Diving Mask
Item: 6.5 mm Wet Suit

Downloading the Java 2 Platform

Have a question about programming? Use Java Online Support.

- Note -

Sun respects your online time and privacy. The Java Developer Connection mailing lists are used for internal Sun Microsystems purposes only. You have received this email because you elected to subscribe.

- Unsubscribe -

To unsubscribe to this newsletter, go to the subscriptions page uncheck the "JDC New-to-Java Supplement" checkbox, and click "Update".

- Subscribe -

To subscribe to other JDC mailings, go to the subscriptions page choose the newsletters you want to subscribe, and click "Update".

- Feedback -

Comments? Send your feedback on the JDC Newsletter to: jdc-webmaster

- Copyright -

Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA

This document is protected by copyright.

JDC New-to-Java Programming Center Supplement
August 2001

1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.