Writing, Compiling, and Running Java Programs
Introduction
This tutorial provides a step-by-step guide to writing, compiling, and running Java programs. By the end of this tutorial, you will know how to create a simple Java program and execute it successfully.
Step 1: Writing a Java Program
Follow these steps to write a basic Java program:
- Open any text editor (e.g., Notepad, Notepad++, or an IDE like Eclipse, IntelliJ, or VS Code).
- Type the following code:
- Save the file with a .java extension. For example, MyFirstProgram.java. Ensure the file name matches the class name.
public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello, Java!"); } }
Step 2: Compiling the Java Program
To compile the Java program, follow these steps:
- Open a terminal or command prompt.
- Navigate to the directory where you saved the .java file.
- Type the following command and press Enter:
- If there are no errors, a file named MyFirstProgram.class will be generated in the same directory.
javac MyFirstProgram.java
Step 3: Running the Java Program
To run the compiled Java program, follow these steps:
- Ensure you are still in the directory containing the .class file.
- Type the following command and press Enter:
- You should see the following output:
java MyFirstProgram
Hello, Java!
Understanding the Code
- public class MyFirstProgram: Defines a class named MyFirstProgram. The file name must match this class name.
- public static void main(String[] args): This is the entry point of the program. The JVM starts execution from this method.
- System.out.println("Hello, Java!"): Prints the message "Hello, Java!" to the console.
Conclusion
By following this guide, you have successfully written, compiled, and run your first Java program. Practice writing more programs to gain confidence and explore additional Java features like variables, loops, and functions.