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:

  1. Open any text editor (e.g., Notepad, Notepad++, or an IDE like Eclipse, IntelliJ, or VS Code).
  2. Type the following code:
  3.     public class MyFirstProgram {
            public static void main(String[] args) {
                System.out.println("Hello, Java!");
            }
        }
                
  4. Save the file with a .java extension. For example, MyFirstProgram.java. Ensure the file name matches the class name.

Step 2: Compiling the Java Program

To compile the Java program, follow these steps:

  1. Open a terminal or command prompt.
  2. Navigate to the directory where you saved the .java file.
  3. Type the following command and press Enter:
  4.     javac MyFirstProgram.java
                
  5. If there are no errors, a file named MyFirstProgram.class will be generated in the same directory.

Step 3: Running the Java Program

To run the compiled Java program, follow these steps:

  1. Ensure you are still in the directory containing the .class file.
  2. Type the following command and press Enter:
  3.     java MyFirstProgram
                
  4. You should see the following output:
  5.     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.





Advertisement