Programs started and stopped automatically when systems startup or power down are called services. With Linux they are called
daemons and are controlled by the system service management (mainly
systemd - Wikipedia[
^] nowadays).
To stop such daemons they must be able to receive a stop event and terminate themself. That is done traditionally by handling the
SIGTERM
POSIX signal (
Signal (IPC) - Wikipedia[
^]). See
Handle Signals and Exceptions[
^] for Java.
While it is not always necessary to provide such a handler it is recommended to perform a proper shutdown by closing files and sockets, and terminating child threads.
How to make a Java daemon with start-stop-daemon - Leonid Shevtsov[
^] describes how to start and stop a Java application as daemon.
When a daemon provides some kind of
Inter-process communication - Wikipedia[
^] that can be also used to handle stop conditions.
But such daemons are not attached to a user shell so that they can't get input from the keyboard. If an application should be executed as daemon and as normal application, a common solution is to use a command line argument to define the execution state. This is especially useful during development.
If an application has to handle asynchronous events like keyboard input and listening on network sockets without blocking other execution paths, these have to be implemented in own threads. This applies to all kind of applications.
So you would have to learn about the above concepts. Matching web research keywords might be for example "javal linux daemon" and "java handle sigterm". Handling IO events and using threads depends on the kind of asynchronous events to be handled.