Q:

Data type of variable size in Java?

In Java I want to create a data type, let's say Atom, which contains an index number, and when that index = 0, the Atom will contain a String datum, otherwise the Atom is just an index (Integer).
How can I do that?
I guess it would save some space if most Atoms are just indexes and only some contain Strings.

A:

The following Factory Pattern illustrates how a static factory method createAtom creates instances of different classes (all Atom), with different data.
Here I made index final as changing it to 0, will not change the class of the object. Also Atom has to offer access to the optional datum.
public class Atom {
    public final int index;

    private Atom(int ix) {
        this.index = ix;
    }

    public String getDatum() {
        return null;
    }

    public static Atom createAtom(int index) {
        return index != 0 ? new Atom(index) : new ExtendedAtom(index);
    }
}

class ExtendedAtom extends Atom {
    private String datum;

    ExtendedAtom(int ix) {
        super(ix);
    }

    @Override
    public String getDatum() {
        return datum;
    }

}

