Object Serialization And De-Serialization In Java To Filesystem

Object Serialization:
In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward.

This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

Advantages Of Object Serialization:
Serialization has a number of advantages. It provides:

  • A method of persisting objects which is more convenient than writing their properties to a text file on disk, and re-assembling them by reading this back in.
  • A method of issuing remote procedure calls, e.g., as in SOAP
  • A method for distributing objects, especially in software componentry such as COM, CORBA, etc.
  • A method for detecting changes in time-varying data.

Serialization In Java:
Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as “okay to serialize,” and Java then handles serialization internally. There are no serialization methods defined on the Serializable interface, but a serializable class can optionally define methods with certain special names and signatures that if defined, will be called as part of the serialization/deserialization process. The language also allows the developer to override the serialization process more thoroughly by implementing another interface, the Externalizable interface, which includes two special methods that are used to save and restore the object’s state.

There are three primary reasons why objects are not serializable by default and must implement the Serializable interface to access Java’s serialization mechanism.

  • Not all objects capture useful semantics in a serialized state. For example, a Thread object is tied to the state of the current JVM. There is no context in which a deserialized Thread object would maintain useful semantics.
  • The serialized state of an object forms part of its class’s compatibility contract. Maintaining compatibility between versions of serializable classes requires additional effort and consideration. Therefore, making a class serializable needs to be a deliberate design decision and not a default condition.
  • Serialization allows access to non-transient private members of a class that are not otherwise accessible. Classes containing sensitive information (for example, a password) should not be serializable or externalizable.


The standard encoding method uses a simple translation of the fields into a byte stream. Primitives as well as non-transient, non-static referenced objects are encoded into the stream. Each object that is referenced by the serialized object and not marked as transient must also be serialized; and if any object in the complete graph of non-transient object references is not serializable, then serialization will fail. The developer can influence this behavior by marking objects as transient, or by redefining the serialization for an object so that some portion of the reference graph is truncated and not serialized.

It is possible to serialize Java objects through JDBC and store them into a database.

While Swing components do implement the Serializable interface, they are not portable between different versions of the Java Virtual Machine. As such, a Swing component, or any component which inherits it, may be serialized to an array of bytes, but it is not guaranteed that this storage will be readable on another machine. [Source of this text Wikipedia]

The following program demonstrates how any object can be serialized. The first class is a simple object which has to be serialized/deserialized. The second class serializes and saves the object to the file, and then reads the object back from the file.

The Object to Serialize

package com.kushal.serialization;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 */
import java.io.Serializable;

public class MyObjectToSerialize implements Serializable {

	private String firstName;

	private String lastName;

	private int age;

	public MyObjectToSerialize(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public String toString() {
		return firstName + " " + lastName + ", " + age;
	}

}

That Class that does the serialization/deserialization job.

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 *
 * A class that saves and loads a serialized object.
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSerialization {

	/**
	 * Saves an object to the file
	 */
	private static void saveObject(Serializable object, String filename)
			throws IOException {
		ObjectOutputStream objstream = new ObjectOutputStream(
				new FileOutputStream(filename));
		objstream.writeObject(object);
		objstream.close();
	}

	/**
	 * Loads an object from the file
	 */
	private static Object loadObject(String filename)
			throws ClassNotFoundException, IOException {
		ObjectInputStream objstream = new ObjectInputStream(
				new FileInputStream(filename));
		Object object = objstream.readObject();
		objstream.close();
		return object;
	}

	public static void main(String[] args) {
		MyObjectToSerialize original = new MyObjectToSerialize("Christopher","Walken", 64);
		System.out.println("Original Object:t" + original);
		try {
			saveObject(original, "C:/object.ser");
			MyObjectToSerialize loaded = (MyObjectToSerialize) loadObject("C:/object.ser");
			System.out.println("Loaded Object:tt" + loaded);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



Java serialization and version control:
The Java serialization mechanism provides an approach for version control. At the heart of Java serialization is the ObjectOutputStream class. It implements the computeSerialVersionUID() method to compute the suid during object serialization. This computed suid is then written to the serialized stream as a part of the serialized object. This suid in the stream serves as a marker to denote the version of the serializable class with which it is compatible. See Figure 2 for a sample of metadata stored in a serialized object. [Source of this text: JavaWorld]

Finding Java Image Pixels Information – ARGB (Alpha, Red, Green Blue)

In digital imaging, a pixel(or picture element) is the smallest item of information in an image. Pixels are normally arranged in a 2-dimensional grid, and are often represented using dots or squares. Each pixel is a sample of an original image, where more samples typically provide more-accurate representations of the original. The intensity of each pixel is variable; in color systems, each pixel has typically three or four components such as red, green, and blue, or cyan, magenta, yellow, and black.

The word pixel is based on a contraction of pix (“pictures”) and el (for “element”); similar formations with el for “element” include the words: voxel and texel. [Wikipedia]

In java 2D images, pixels are arranged in 2 dimensional array. If you take an image of dimension 200×300, there will be a total of 60,000 pixels. Each pixel is represented by a 32 bit integer. 32bit (4Bytes) represent 4 different color information. These color information, called ARGB, stand for Alpha, Red, Green and Blue. Each byte out of 4 Bytes of every pixel represents one of these color information.

In the following tutorial, you will learn

  • How to read image from filesystem
  • How to calculate the image height and width
  • How to loop through each pixel and get pixel info
  • Get alpha (transparency) value from the pixel
  • Get Color info (red, green and blue) from the pixel
  • How to do bit manipulation on an integer

package com.kushal.graphics;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 2009-10-21
 *
 * PrintImageARGBPixels.java
 * Reads an image and prints out it's color and alpha
 * information of individual pixels [Alpha, Red, Green Blue]
 */
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class PrintImageARGBPixels {

	public static void main(String args[]) {
		/**
		 * Read a sample image from the filesystem
		 */
		BufferedImage image = readImage("c:/temp/generalImage.jpg");

		/**
		 * Call the method that prints out ARGB color Information.
		 * ARGB = Alpha, Red, Green and Blue
		 */
		printAllARGBDetails(image);
	}

	public static void printAllARGBDetails(BufferedImage image) {
		int width = image.getWidth();
		int height = image.getHeight();
		System.out.println("Image Dimension: Height-" + height + ", Width-"
				+ width);
		System.out.println("Total Pixels: " + (height * width));
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {

				int pixel = image.getRGB(i, j);
				System.out.println("Pixel Location(" + i + "," + j + ")- ["
						+ getARGBPixelData(pixel) + "]");
			}
		}
	}

	/**
	 * Image Pixels are Arrays of Integers [32 bits/4Bytes]
	 * Consider a 32 pixel as 11111111-00110011-00111110-00011110
	 *
	 * First Byte From Left [11111111]= Alpha
	 * Second Byte From Left[00110011]= Red
	 * Third Byte From Left [00111110]= Green
	 * Fourth Byte From Left[00011110]= Blue
	 *
	 * The following method will do a proper bit shift and
	 * logical AND operation to extract the correct values
	 * of different color/alpha components.
	 *
	 */
	public static String getARGBPixelData(int pixel) {
		String pixelARGBData = "";
		/**
		 * Shift all pixels 24 bits to the right.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the alpha value for the pixel
		 */
		int alpha = (pixel >> 24) & 0x000000FF;

		/**
		 * Shift all pixels 16 bits to the right.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the red value for the pixel
		 */

		int red = (pixel >> 16) & 0x000000FF;

		/**
		 * Shift all pixels 8 bits to the right.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the green value for the pixel
		 */
		int green = (pixel >>8 ) & 0x000000FF;

		/**
		 * Dont do any shift.
		 * Do a logical and with 0x000000FF
		 * i.e. 0000 0000 0000 0000 0000 0000 1111 1111
		 * You will get the blue value for the pixel
		 */
		int blue = (pixel) & 0x000000FF;

		pixelARGBData = "Alpha: " + alpha + ", " + "Red: " + red + ", "
				+ "Green: " + green + ", " + "Blue: " + blue;

		return pixelARGBData;
	}

	/**
	 * This method reads an image from the file
	 * @param fileLocation -- > eg. "C:/testImage.jpg"
	 * @return BufferedImage of the file read
	 */
	public static BufferedImage readImage(String fileLocation) {
		BufferedImage img = null;
		try {
			img = ImageIO.read(new File(fileLocation));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return img;
	}

	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
	 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
	 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE LIABLE FOR
	 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
	 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 *
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */
}

Sample Image Used In This Program (You can use any of your own).

Output of this program on a sample Image:
Note that I have shortened the output by removing many lines from in between. This is because I took a 122×122 image and there were a total of 14884 pixel info printed on the screen.

The complete  output file is available here.

Image Dimension: Height-122, Width-122
Total Pixels: 14884
Pixel Location(0,0)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,1)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,2)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,3)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,4)- [Alpha: 255, Red: 255, Green: 254, Blue: 255]
Pixel Location(0,5)- [Alpha: 255, Red: 255, Green: 254, Blue: 255]
Pixel Location(0,6)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,7)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,8)- [Alpha: 255, Red: 254, Green: 255, Blue: 255]
Pixel Location(0,9)- [Alpha: 255, Red: 254, Green: 255, Blue: 255]
Pixel Location(0,10)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,11)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,12)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,13)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,14)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,15)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(0,16)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
.
.
.
Pixel Location(90,26)- [Alpha: 255, Red: 216, Green: 217, Blue: 219]
Pixel Location(90,27)- [Alpha: 255, Red: 219, Green: 215, Blue: 216]
Pixel Location(90,28)- [Alpha: 255, Red: 216, Green: 216, Blue: 216]
Pixel Location(90,29)- [Alpha: 255, Red: 210, Green: 214, Blue: 213]
Pixel Location(90,30)- [Alpha: 255, Red: 206, Green: 210, Blue: 209]
Pixel Location(90,31)- [Alpha: 255, Red: 219, Green: 212, Blue: 202]
Pixel Location(90,32)- [Alpha: 255, Red: 235, Green: 205, Blue: 179]
Pixel Location(90,33)- [Alpha: 255, Red: 221, Green: 167, Blue: 121]
Pixel Location(90,34)- [Alpha: 255, Red: 213, Green: 132, Blue: 66]
Pixel Location(90,35)- [Alpha: 255, Red: 220, Green: 130, Blue: 52]
Pixel Location(90,36)- [Alpha: 255, Red: 212, Green: 133, Blue: 56]
Pixel Location(90,37)- [Alpha: 255, Red: 196, Green: 139, Blue: 72]
Pixel Location(90,38)- [Alpha: 255, Red: 185, Green: 161, Blue: 115]
Pixel Location(90,39)- [Alpha: 255, Red: 206, Green: 203, Blue: 160]
Pixel Location(90,40)- [Alpha: 255, Red: 207, Green: 213, Blue: 153]
Pixel Location(90,41)- [Alpha: 255, Red: 174, Green: 189, Blue: 120]
Pixel Location(90,42)- [Alpha: 255, Red: 160, Green: 183, Blue: 113]
Pixel Location(90,43)- [Alpha: 255, Red: 124, Green: 155, Blue: 114]
.
.
.
Pixel Location(121,105)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,106)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,107)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,108)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,109)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,110)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,111)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,112)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,113)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,114)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,115)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,116)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,117)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,118)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,119)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,120)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]
Pixel Location(121,121)- [Alpha: 255, Red: 255, Green: 255, Blue: 255]

Creating A 3D Pie Chart In Java Using JFreeChart [Example Source Code]

JFreeChart is an open-source framework for the programming language Java, which allows the creation of complex charts in a simple way.

JFreeChart also works with GNU Classpath, a free software implementation of the standard class library for the Java programming language.

Following chart types are supported:

  • * X-Y charts (line, spline and scatter)
  • * Pie charts
  • * Gantt charts
  • * Bar charts (horizontal and vertical, stacked and independent)
  • * Single valued (thermometer, compass, speedometer)

In the following tutorial, I will show you how to create a 3D Pie Chart using JFreeChart. If you do not have the JFreeChart library and API, you can download it from their website www.jfree.org

package com.kushal.charts;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modfied On: 2009-09-23
 * 
 * Using JFreeChart to create 3D Pie Chart
 */
import java.awt.Color;
import java.io.File;
import java.io.IOException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

public class My3DPieChart {
	private static final long serialVersionUID = -8625975218180144099L;

	private PieDataset createPieDataSet() {
		DefaultPieDataset pieDataset = new DefaultPieDataset();
		/**
		 * Filling the data Visit of Sanjaal.com on a random day by Browser
		 */
		pieDataset.setValue("MS Internet Explorer", 184707);
		pieDataset.setValue("Firefox", 144556);
		pieDataset.setValue("Google Chrome", 21638);
		pieDataset.setValue("Opera", 21609);
		pieDataset.setValue("Unknown", 17916);
		pieDataset.setValue("Safari", 10850);
		pieDataset.setValue("Mozilla", 7081);
		pieDataset.setValue("Netscape", 1010);
		pieDataset.setValue("Curl", 405);
		pieDataset.setValue("LibWWW", 121);

		return pieDataset;

	}

	private JFreeChart create3DPieChart(PieDataset dataset) {

		/**
		 * createPieChart3D method Parameters: --java.lang.String title,
		 * --PieDataset dataset, --boolean legend, --boolean tooltips, --boolean
		 * urls
		 */
		JFreeChart chart = ChartFactory.createPieChart3D(
				"Sanjaal.com Visits By Browser", dataset, true, true, true);

		PiePlot3D p = (PiePlot3D) chart.getPlot();
		p.setForegroundAlpha(0.5f);
		p.setBackgroundAlpha(0.2f);

		chart.setBackgroundPaint(Color.white);
		chart.setAntiAlias(true);
		chart.setBorderVisible(true);

		return chart;

	}

	public void saveChart(JFreeChart chart, String fileLocation) {
		String fileName = fileLocation;
		try {
			/**
			 * This utility saves the JFreeChart as a JPEG First Parameter:
			 * FileName Second Parameter: Chart To Save Third Parameter: Height
			 * Of Picture Fourth Parameter: Width Of Picture
			 */
			ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Problem occurred creating chart.");
		}
	}

	public static void main(String[] args) {
		My3DPieChart chartCreator = new My3DPieChart();

		/** Create a PieDataSet* */
		PieDataset pieDataset = chartCreator.createPieDataSet();

		/** Create 3D Pie Chart based on this dataset* */
		JFreeChart chart = chartCreator.create3DPieChart(pieDataset);

		/** Define a file location to save this chart */
		String fileLocation = "C:/temp/my3DPieChart.jpg";

		/** Save the chart to the file system* */
		chartCreator.saveChart(chart, fileLocation);

		System.out.println("3D Pie Chart has been created successfully");
		System.out.println("Chart has been saved to: " + fileLocation);
	}

	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
	 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
	 * LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
	 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
	 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 * 
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */
}

The following is the output if this program:

3D Pie Chart has been created successfully
Chart has been saved to: C:/temp/my3DPieChart.jpg

Generated PieChart for the data provided looks like this: