All perfect praise be to Allah, the Lord of the worlds. I testify that there is none worthy of worship except Allah and that Muhammad, sallallaahu ʻalayhi wa sallam, is His slave and Messenger.
Thinking about women in a sexual way is one of the doors of the devil that leads to Fitnah (temptation/tribulation). The Islamic Shariah considered it fornication in a figurative sense because it is a means to actual fornication. The Shariah instructs the Muslims to eliminate the means that lead to committing sins. Abu Hurayrah narrated that the Prophet, sallallaahu ʻalayhi wa sallam, said:
“Allah has written one's inevitable portion of fornication, which he will inevitably indulge in, for every son of Adam. The fornication of the eye is the looking; the fornication of the ears is the listening; the fornication of the tongue is the talking; the fornication of the hand is the gripping; and the fornication of the feet is the walking (to the place where adultery is committed). The heart yearns and desires, and the private parts approve all that (i.e. put that into effect) or disapprove it (i.e. refrain from submitting to the temptation).” [Al-Bukhaari and Muslim] This wording was cited in Saheeh Muslim.
An-Nawawi commented on the hadeeth, saying, “The hadeeth means that it has been decreed that each and every person shall inevitably commit a share of adultery; some will commit actual physical fornication by engaging in unlawful sexual intercourse, and others will commit fornication only in a figurative sense by means of lustful gazes ... or by mere sinful thoughts harbored within their hearts. All of these acts are considered figurative forms of fornication...” [Sharh Saheeh Muslim]
Al-Mulla ʻAli Al-Qaari wrote, “It is deduced from the hadeeth that if sinful wishing settles in the heart and the person insists upon it and does not repel it, it is called fornication. It is a sin and it deserves punishment, even if he does not act upon it.” [Mirqaat Al-Mafateeh Sharh Mishkaat Al-Masaabeeh]
Hence, this must be avoided regardless of whether it leads to ejaculation or not.
Allah knows best.