pixel
pixel
header

    September 30, 2002    

In this Issue

imageJava Programming Language Basics
imageJava Bits
imageMaking Sense of the Java Class Libraries
imageProgram Challenge
imageNew to the New to Java Programming Center
imageFor More Information

Pixel

Java Programming Language Basics

How to Use Object Serialization

The standard libraries of the Java 2 Standard Edition (J2SE) version 1.4 provide many ways acheive persistence of information between multiple runs of the same program. For simple strings and primitive data types like int and float, you can use the java.util.Properties object or the Preferences API, found in the java.util.prefs package. For JavaBean components, use the java.beans.XMLEncoder and java.beans.XMLDecoder classes for saving and restoring the state of a bean via an XML file. For the general-purpose object, you save its state through a mechanism called object serialization.

The state of an object consists of the current settings for all the instance variables for a specific instance of that object. If that state information is another object, the current settings for that object are also saved, and so on until everything is a primitive data type.

Methods and static variable state are not saved. Methods consist of behavior and not state, so they are not saved. Static variable state is state information about the class, not the instance, so it isn't saved either.

Multiple references to the same object are saved only once and in such a way that restoration returns the multiple references to the single object.

Once an object state has been saved (or serialized), the process of restoring the state is called deserialization. This process involves identifying the class to be restored, finding the appropriate .class file for that class, and then restoring the state for an instance of that class.

If the .class file can't be located, or its format is not compatible with the saved state, the object cannot be restored. For instance, incompatibilities may arise when fields are added.

The actual process of serialization is straightforward.

The ObjectOutputStream class offers a writeObject method for saving the state of an object. Assuming the class is serializable, you just pass the instance variable for that object to the writeObject method, and the stream class does all its work.

Object o = ...;
ObjectOutputStream oos = ...;
oos.writeObject(o);

How do you know if an object is serializable? If a class implements the java.io.Serializable interface, it is indeed serializable. There are no methods to the interface, so it just serves as a marker interface. However, just implementing the interface isn't sufficient. All the instance variables of that class must also be serializable; otherwise, when you try to serialize the state, an exception would be thrown.

Deserializing the state of an object is just as simple as saving it. This time, though, use the class ObjectInputStream and the method readObject:

ObjectInputStream ois = ...;
Object o = ois.readObject();

For both reading and writing objects, you must wrap the operations in a try-catch block, as a java.io.IOException may be encountered. In addition, restoration can result in a java.lang.ClassNotFoundException when the class file isn't available.

The following program demonstrates how to serialize your own class by creating an instance, saving its state to an in-memory buffer, and getting the state back again.

import java.io.*;
import java.awt.Point;

public class Cereal implements Serializable {
String name;
int servings;
Point point;

public static void main(String args[]) {
Cereal c = new Cereal();
c.name = "Froot Loops";
c.servings = 12;
c.point = new Point(20, 30);
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
try {
ObjectOutputStream oos =
new ObjectOutputStream(baos);
oos.writeObject(c);
oos.close();
} catch (IOException e) {
System.err.println(
"Problems saving state");
}
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
try {
ObjectInputStream ois =
new ObjectInputStream(bais);
Cereal c2 = (Cereal)ois.readObject();
System.out.println("Name: "
+ c2.name);
System.out.println("Servings: "
+ c2.servings);
System.out.println("Point: "
+ c2.point);
} catch (ClassNotFoundException e) {
System.err.println(
"Cannot find class to restore");
} catch (IOException e) {
System.err.println(
"Problems restoring state");
}
}
}

This application produces the following:

Name:     Froot Loops
Servings: 12
Point: java.awt.Point[x=20,y=30]

Now you can test your knowledge about serializing objects with this online quiz.

Pixel
Pixel

Java Bits

The transient Keyword

When serializing objects, there are times when you don't want a data member to get written to the stream. To prevent the writeObject method from writing a field to a stream, declare a data member as transient. When an object is read from a stream, transient data fields are set to their default values, such as 0 for integers, and null for strings. The programmer can restore transient data to to non-default values by implementing a readObject method. Transient fields are skipped when objects are serialized.

Pixel
Pixel

Making Sense of the Java Class Libraries

Drawing with Class Graphics and Class Polygon

The java.awt.Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components. Methods provide all basic drawing operations on a component's area, including the painting of image data. A Graphics object is called a graphics context because it also holds information about the drawing area, such as clipping region, color, and text fonts.

The Graphics class serves two major purposes:

  • Sets and gets graphical parameters
  • Performs graphical operations

Whenever a component's update or paint method is called, AWT provides the component with a new Graphics object for drawing in the display area, and resets attributes.

Methods of the Graphics class operate in a coordinate system (x,y). The top left of the graphics context is point x progressing across the display, and point y progressing downward. The point at the bottom right corner within the drawing area uses the coordinates (width-1, height-1), giving you a drawing area that is width pixels wide and height pixels high.

fig 1

Some common methods are:

  • public abstract void drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
  • public void drawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle. The left and right edges of the rectangle are at x and x + width. The top left and bottom edges are at y and y + height. The rectangle is drawn using the graphics context's current color.
  • public abstract void drawOval(int x, int y, int width, int height) Draws the outline of an oval. The result is a circle or ellipse that fits within the rectangle specified by the x, y, width, and height arguments.
  • public abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y) coordinates defines a point.

For example, here is one way to create a rectangle:

public void paint(Graphics g)
{
g.drawRect(2,2,4,4);
}

Since the lines are drawn beneath and to the right of the coordinates along the path, the rectangle above is 5 pixels tall, not 4.

Another way to draw a shape is by creating a Polygon object. The Polygon class represents an ordered collection of points treated as the definition of a polygon.

You create a Polygon object with the default constructor by calling the addPoint method, or by providing point coordinates within the constructor:

Polygon(): Creates an empty Polygon.

Polygon(int[] xpoints, int[] ypoints, int npoints): Constructs and initializes a Polygon from the specified parameters.

addPoint(int x, int y): Appends the specified coordinates to this Polygon.

For example:

Polygon p = new Polygon();
p.addPoint(10, 10);
p.addPoint(10, 30);
p.addPoint(20, 20);
g.drawPolygon(p);

See the example application ShapesPolygonDrawing.java, which shows how to create shapes as described above. This application creates shapes as shown below:

fig 2
Pixel
Pixel

Program Challenge

Create the Draw Application

Create a drawing program that tracks mouse clicks. Each time the mouse is clicked, add the position to a polygon. The program draws the current polygon, based on the set of points added.

  • Create three buttons for the program: Load, Save, and Clear.
  • The Save button saves the current set of points in the polygon into an external file.
  • The Load button loads the saved set of points from the file.
  • The Clear button clears the current set of points, without touching the file.

Your application should look something like the following screen shot:

fig 3

See a possible solution to Challenge

Pixel
Pixel

New to the Java Programming Center

The first page of the lesson, "The Java Technology Phenomenon," establishes some basic facts about the Java platform. Take this quiz to test your basic knowledge.

Pixel
Pixel

For More Information

Object Serialization

Reading and Writing Data Code Samples

Object Serialization

Serialization Forum

Class Graphics

Class Polygon

Pixel
Pixel

Program Challenge Solution

See one possible solution to the September Program Challenge.

Pixel
Pixel

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.

Pixel
Pixel

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.

Pixel
Pixel
Pixel

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 2002 Sun Microsystems, Inc. All rights reserved. 901 San Antonio Road, Palo Alto, California 94303 USA.

Sun, Sun Microsystems, Java, J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Sun Microsystems, Inc.
image
image