Look up the last train when you arrive, not at midnight.
Japanese trains are so reliable that visitors assume they run late. They do not. City lines generally stop around midnight, and country lines stop far earlier — some mountain and rural services finish in the afternoon.
The habit that prevents every version of this problem: Photograph the timetable at the bus stop. It takes five seconds and it decides your evening.
Big city lines: last trains around midnight, first around 05:00.
Suburban lines: earlier, and the last one may not go all the way.
Country lines: often finish between 19:00 and 21:00.
Mountain and sightseeing buses: can finish in the early or mid afternoon.
Ferries to islands: weather-dependent as well as time-dependent.
Japan is a safe country to be stuck in, and cities have places built for exactly this. It will cost you money and sleep, not your safety.
Available in cities, expensive over distance, and metered. Show your hotel’s card rather than saying the name.
Open all night, priced by the hour, with a private booth, drinks and a shower in some. The normal local answer.
A clean bunk, a locker and a bath, in city centres. Some are men-only, some have separate floors — ask at the door.
Around 05:00. A 24-hour cafe or a convenience store is a fine place to sit. Stations themselves close overnight, so book a capsule hotel or take a night bus.
If the last bus down from a Ask your inn to arrange a pick-up before the last bus leaves, not after — and tell them where you are going in the morning, so somebody knows.