The recent discovery of massive planets around other stars has aroused a lot of debate on this very point.
Stars form directly from the collapse of dense clouds of interstellar gas and dust.
Because of rotation, these clouds form flattened disks that surround the central, growing stars. After the star has nearly reached its final mass, by accreting gas from the disk, the leftover matter in the disk is free to form planets. Jupiter is generally believed to have formed in a two-step process. First, a vast swarm of ice and rock 'planetesimals' formed. Once an embryo became about as massive as ten Earths, its self-gravity became strong enough to pull in gas directly from the disk.