What terminates java program?

Hello! I am totally new to Java, so please explain this to me.

Usually a program that started in Java is launched and keeps running untill a user closes it. This is basically just like any other Windows program.

But then there are some java .jar programs that designed to execute once, do their thing and terminate.

For example, from command like I can type
java -jar someprog.jar /tmp/input.txt /tmp/output.txt
This program would, for example parse some text file, does some thing to it and saves it to the output.txt and then exits.

What I don’t understand is how is it that some programs, expecially those that have GUI stay running until closed and some programs are designed to just do one thing and exit?

Also I want to write a program in Java that will be a client to Twitter streaming API and would basically ‘listen’ to Twitters streams and when some tweets have certain keywords it would record the tweet into database.
For this situation I want to program keep running forever and also without any GUI since it will be running on the server. Do I need it to be a servlet or can it just run as a normal Java program and just keep running like a daemon?

I have years of experience with php, most of it in OOP, so it’s not that hard for me to start with Java, but I need to understand these concepts first.

I hope someone can explain it to me . thanks.

Java is like any other programming language. It has an entry point, which is the “main” method of the class you pass to java.exe and once the “main” method is done the program ends. You can also end a program with System.exit(0).

Programs that keep running have a loop. Think of a simple web server that only accepts one connection at a time. Sockets block until a connection arrives. So you have a loop, in the loop you have a socket which accepts a connection. The application will wait for a connection. Once a client connects, it handles the request and sends back some response and the loop starts again. Waiting for another connection. To stop the program there is a special request to send. When the socket receives this request it breaks the loop.

I am not 100% sure if this what you are asking, skim this link: http://www.cs.usfca.edu/~parrt/course/601/lectures/io.html

What I don’t understand is when does the program keep running and how is it that some programs just execute one thing and exit.

In php it’s straight forward, you have a script, usually you give it an input, it does all the things it’s supposed to do and then it returns some output and it’s done. Process ended.

But in Java a program can keep running, keep listening to inputs and generate outputs and keep running and running until someone specifically terminates it.

How is this done?

The basic idea is:


while not quit
  do stuff (listen for input (which could be a quit command), check for a new file, sleep, etc)
end loop