
{{ $('Map tags to IDs').item.json.title }}
How to Run Java Programs
Running Java programs involves compiling the source code with the Java Compiler and then executing the compiled bytecode using the Java Runtime Environment. This tutorial will guide you through the steps to compile and run Java applications effectively.
1. Installing Java Development Kit (JDK)
Before running Java programs, ensure you have the Java Development Kit (JDK) installed. You can verify if it’s installed by running:
java -version
If it’s not installed, you can do so using the following commands:
- For Ubuntu:
sudo apt update sudo apt install default-jdk
- For CentOS:
sudo yum install java-1.8.0-openjdk-devel
2. Creating a Java Source File
Create a new file named HelloWorld.java
:
nano HelloWorld.java
Insert the following Java code into the file:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Save the file and exit the text editor.
3. Compiling the Java Program
Before running the program, it needs to be compiled. Use the javac
command to compile your Java source file:
javac HelloWorld.java
If there are no syntax errors, this command will create a file named HelloWorld.class
, which contains the compiled bytecode.
4. Running the Compiled Java Program
To run the compiled Java program, use the java
command followed by the class name (without the .class
extension):
java HelloWorld
The output should display:
Hello, World!
5. Running Java Programs with Command-Line Arguments
If your program expects command-line arguments, you can provide them when running the program:
java HelloWorld arg1 arg2
Inside your Java code, access these arguments using the String[] args
parameter in the main
method.
6. Conclusion
By following this tutorial, you have successfully learned how to run Java programs from the command line. Understanding how to compile and execute Java applications is vital for effective development and testing. Continue to explore Java’s capabilities and libraries to enhance your programming skills!