How does the texture know exactly where its supposed to be applied? Totally new to this stuff and this just seems like magic to me. So the cake is one single model; it is not subdivided into top, bottom and middle. I add this texture.jpg and it goes exactly where its supposed to be. Topping on top, fruits on fruits and bottom on the bottom of the cake. How? 

How does the model take the correct texture for fruits and put it perfectly on the fruits and to take the bottom and put it onto the bottom etc. And how does it extract the 3 textures so precisely from the jpg?

Some explanation or a source to get into the topic would be appreciated greatly! Thanks in advance.
Do a google search for "UV mapping."  "UV"s are texture coordinates that Blender or other software uses to know where to apply the texture.  That texture you have happens to coincide with the UV coordinates of the cake.  Try another texture and you'll see it doesn't match at all.  

Here are a few links to get you started:
https://en.wikibooks.org/wiki/Blender_3D:_Noob_to_Pro/UV_Map_Basics
https://en.wikipedia.org/wiki/UV_mapping
https://www.creativebloq.com/features/uv-mapping-for-beginners