Next, consider the same initial situation but now with the walls at the same temperature as the gas. When the piston is pushed slowly to compress the gas, the gas molecule collides with the piston coming towards it and the speed of the molecule increases on collision (assuming elastic collision, v2= v1 + 2u in the figure below). This way the internal energy of the molecules increases as the piston is pushed in.
We see that the total internal energy of the gas can increase either due to the temperature difference between the walls and the gas (heat transfer) or due to the motion of the piston (work done on the gas).
In a general situation, both modes of energy transfer may happen together. As an example, consider a gas kept in a cylindrical can, fitted with a movable piston. If the can is kept on a heater, the hot bottom of the cylinder supplies heat to the gas. If the piston is pushed out to some distance, as the piston moves out, the gas does work and the gas loses that amount of energy. Thus, the gas gains energy as heat gets supplied to it and it loses energy as work is done by it.Suppose, in a process, an amount DQ of heat is given to the gas and an amount DW of work is done by it, the total energy of the gas must increase by (DQ - DW). As a result, the entire gas, together with its container, may start moving (systematic motion) or the internal energy (random motion of the molecules) of the gas may increase. If the energy does not appear as a systematic motion of the gas, then this net energy (DQ - DW) must go in the form of its internal energy. If we denote the change in internal energy as DU, we get
Equation (1) is the statement of the first law of thermodynamics. In an ideal monatomic gas, the internal energy of the gas is simply translational kinetic energy of all its molecules. In general, the internal energy may get contributions from the vibrational kinetic energy of molecules, rotational kinetic energy of molecules as well as from the potential energy corresponding to the molecular forces. Equation (1) represents a statement of conservation of energy and is applicable to any system, however complicated it might be.