Basics
Java Running Code
Running Java Code
Java code runs via javac and java commands with .java files.
Understanding Java Program Execution
Java is a popular programming language known for its platform independence, achieved through its unique compilation and execution process. To run a Java program, you need to compile the source code using the javac command, which generates bytecode—a platform-independent code. This bytecode is then executed by the Java Virtual Machine (JVM) using the java command.
Setting Up Your Environment
Before you can run Java code, ensure that the Java Development Kit (JDK) is installed on your system. You can verify the installation by running the following commands in your terminal or command prompt:
If both commands return version information, your setup is correct. If not, you need to install the JDK, which is covered in our previous post on Installation.
Writing a Simple Java Program
Let's start by writing a simple Java program. Create a new file called HelloWorld.java
and add the following code:
Compiling the Java Program
Once your Java code is ready, you need to compile it to generate the bytecode. Use the javac command followed by the filename to compile:
This command will produce a HelloWorld.class
file in the same directory. This file contains the bytecode that can be executed by the JVM.
Running the Compiled Java Program
After compilation, you can execute the program using the java command and the class name (without the .class
extension):
If everything is set up correctly, you should see the output Hello, World!
displayed in your terminal or command prompt.
Troubleshooting Common Issues
Here are a few common issues you might encounter:
- Command not found: Ensure your JDK is correctly installed and the
bin
directory is included in your system'sPATH
environment variable. - Class not found: Verify that you are in the correct directory and are using the correct class name when running the
java
command. - Syntax errors: Double-check your code for typos or missing syntax components like semicolons or braces.
Basics
- Previous
- Installation
- Next
- Syntax