How was water formed if oxygen and hydrogen exist as molecules? I have learnt that both hydrogen and oxygen  exist as molecules. If so how was $\ce {H2O}$ formed?

In water there is two hydrogen molecule and one oxygen atoms but how is this possible? Oxygen only exists as a molecule in our earth then how does the molecule oxygen react with molecule hydrogen to form water.

Moreover, if water is formed by combining of hydrogen and oxygen molecules, then the chemical formula of water should be $\ce{H2O2}$, shouldn't it?
Water does not have two oxygen atoms (has one) and one hydrogen (has two) hence the molecular formula of water is H2O. Water forms when there is enough energy to break the molecular bonds within the Hydrogen and Oxygen diatoms, they then combine and form water. As Mathew said, look at the Standard Gibbs free energy of formation. It will explain that H2O is much more favourable to be formed than H2O2.