The class I am trying to access is Program.java. Is there also a way to make this work for any computer, as long as they have a class named Program?
You (or they) need to compile the program. (That is no different to C, C++ and numerous other programming languages.)
They need to have Java installed on their machine.
They need to invoke the command correctly, depending on where Java is installed, where your (compiled) program is, and so on1.
There are various things you can do to simplify this for the end user. For example, you can implement an installer that installs the software in a standard place and provides a launcher or a wrapper script for running it.
Launching a Java application programmatically (as per your example) has a couple of extra problems:
You need to know where the java
command is installed (unless you can rely on the search path being sane).
You need to know where your application's bytecode files and dependent libraries have been installed.
These things are typically dealt with by creating a wrapper script, or by putting the information into an application specific configuration file.
Why do we need to add "java program" in creating a new process ....
Because that is the way that mainstream Java works. The Java compiler (javac
) generates "bytecode" files rather than conventional (platform specific) executables. You need the java
command to run the bytecode files, 'cos the operating system doesn't know haw to deal with them itself.
1 - The things that need to be correct are: 1) the pathname of the java
command, 2) the classpath has to include the class directories and the JAR files that the application requires ... with the correct paths, 3) the classname must be correctly specified. And if you are invoking the command programmatically from Java, then you cannot assume that exec
knows how to split a command string into arguments correctly.