Writing Your First Java Program Java
If you’ve successfully set up your Java development environment with JDK and an IDE, you’re now ready to write your first Java program! In this tutorial, we’ll go step by step to create, compile, and run a simple Java program.
1. Understanding the Basic Structure of a Java Program
Every Java program follows a basic structure. Let’s take a look at a simple Java program:
Breaking it Down:
public class HelloWorld– Every Java program starts with a class. Here, our class name isHelloWorld. The class name must match the filename (HelloWorld.java).public static void main(String[] args)– This is the main method where the execution starts. Java always looks for this method to run the program.System.out.println("Hello, World!");– This prints"Hello, World!"to the console.
2. Writing and Running Your First Java Program
Step 1: Create a Java File
- Open your preferred IDE (such as IntelliJ IDEA or Eclipse).
- Create a new Java project.
- Inside the project, create a new Java file and name it
HelloWorld.java.
Step 2: Write the Code
Copy and paste the above code into your HelloWorld.java file.
Step 3: Compile and Run the Program
Using an IDE:
- Click the Run button (usually a green triangle).
- You should see the output:
Using the Command Line (Terminal):
-
Open the terminal or command prompt.
-
Navigate to the folder where your
HelloWorld.javafile is saved. -
Compile the program using:
-
Run the compiled file:
-
You should see the output:
3. Common Errors and How to Fix Them
Error 1: "javac is not recognized"
Solution: Ensure that Java is installed correctly and added to the system PATH.
Error 2: "Main method not found"
Solution: Double-check that you’ve written public static void main(String[] args) correctly.
Error 3: "Class name mismatch"
Solution: Make sure your file name and class name are exactly the same (HelloWorld.java and HelloWorld).
.png)
No comments