Recipe 1.6 - Fetching Atoms and Molecules


You want to create Atom and Molecule.


Flyweight objects Atoms are accessible through the singleton class PeriodicTable. Molecules have to be built from the Composition class. Getting main isotope atom given an AtomicSymbol

PeriodicTable periodicTable = PeriodicTable.getInstance();

Atom hydrogen = periodicTable.getAtom(AtomicSymbol.H);

Assert.assertEquals(1, hydrogen.getMassNumber());

Getting specific isotope given an AtomicSymbol

Atom deuterium = periodicTable.getAtom(AtomicSymbol.H, 2);

Assert.assertEquals(2, deuterium.getMassNumber());

Getting Atom from a String

Atom hydrogen = periodicTable.getAtom(AtomicSymbol.valueOf("H"), 2);

Assert.assertEquals(2, hydrogen.getMassNumber());

PeriodicTable also provides static Atoms and masses that are the most used

Atom atom = PeriodicTable.C;
Assert.assertEquals(PeriodicTable.C_MASS, atom.getMass(), 0.0001);

Accessors from Atoms

AtomicSymbol symbol = atom.getSymbol();
Assert.assertEquals(AtomicSymbol.C, symbol);

double abundance = atom.getAbundance();
Assert.assertEquals(0.989, abundance, 0.001);

double mass = atom.getMass();
Assert.assertEquals(12, mass, 0.0001);

Lastly PeriodicTable provides a method that fetch the list of isotopes from an AtomicSymbol

PeriodicTable periodicTable = PeriodicTable.getInstance();

List<Atom> isotopes = periodicTable.getAtoms(AtomicSymbol.C);

Assert.assertEquals(Arrays.asList(PeriodicTable.C, PeriodicTable.C13, periodicTable.getAtom(AtomicSymbol.valueOf("C"), 14)), isotopes);

Creating Composition given atoms and an overall optional charge

Composition sulfateComp = new Composition.Builder(AtomicSymbol.S).add(AtomicSymbol.O, 4).charge(-2).build();

// accessors
Set<Atom> atoms = sulfateComp.getAtoms();

Assert.assertEquals(4, sulfateComp.getCount(PeriodicTable.O));
Assert.assertEquals(0, sulfateComp.getCount(PeriodicTable.C));

double exactMass = sulfateComp.getMolecularMass();
Assert.assertEquals(95.9528, exactMass, 0.0001);

double avgMass = MassCalculator.calculateAverageMass(sulfateComp);
Assert.assertEquals(96.0627, avgMass, 0.0001);

Creating Composition from a string

Composition sulfateComp = Composition.parseComposition("SO4(2-)");


Composition parses chemical formula expressions. An expression is composed of many atoms, each atom is represented by

  1. a symbol
  2. an optional neutron number
  3. and an optional quantifier (can be negative)
An overall charge can be defined at the end of expression For example SO4(2-) or H[2]3O(+) are valid expressions.

See also

See AtomicCompositionParser to learn more about the Composition format