Running Java Programs in the Terminal
After compiling your Java source code, you can run the resulting bytecode using the java
command. The java
command is also part of the Java Development Kit (JDK) and is used to execute Java programs.
To run the HelloWorld
program we compiled earlier, follow these steps:
-
Open a terminal and navigate to the directory where the HelloWorld.class
file is located.
-
Run the java
command, followed by the name of the main class (without the .class
extension):
java HelloWorld
This will execute the main()
method in the HelloWorld
class and output the message "Hello, World!" to the console.
The process of running a Java program can be summarized as follows:
graph TD
A[Java Bytecode] --> B[java Command]
B --> C[Execute on JVM]
In addition to running simple programs, the java
command also supports various options and flags that can be used to customize the execution of your Java application. For example, you can use the -cp
or -classpath
option to specify the classpath, which is the directory or set of directories where the JVM should look for the compiled class files.
Here's an example of running a Java program with a custom classpath:
java -cp /path/to/my/classes HelloWorld
You can also pass command-line arguments to your Java program using the String[] args
parameter in the main()
method. These arguments can be accessed and used within your Java code.
public class HelloWorld {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0] + "!");
} else {
System.out.println("Hello, World!");
}
}
}
To run this program with a command-line argument, you would use the following command:
java HelloWorld "LabEx"
This would output "Hello, LabEx!" to the console.
By understanding how to compile and run Java programs in the terminal, you have taken the first steps towards becoming a proficient Java developer. In the next section, we'll explore more advanced topics and techniques for working with Java.