Writing Your First Java Program
Now that Java is installed, let's write and run your first Java program. In this tutorial, we'll create a simple program that prints "Hello, World!" to the screen.
Step 1: Open a Text Editor or IDE
You can use any text editor (like Notepad or Visual Studio Code) or an Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA to write your code.
Step 2: Write Your Code
In your editor, type the following code:
Java
Copy
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Explanation of the Code:
- public class HelloWorld: Defines a class named HelloWorld. In Java, every program needs a class.
- public static void main(String[] args): This is the main method, where your program starts running.
- System.out.println("Hello, World!");: This line prints "Hello, World!" to the screen.
Step 3: Save Your File
Save the file with the name HelloWorld.java. The filename should match the class name (HelloWorld).
Step 4: Compile the Program
- Open the Command Prompt (Windows) or Terminal (Mac/Linux).
- Navigate to the folder where you saved HelloWorld.java.
- Type javac HelloWorld.java and press Enter. This command compiles your code, creating a file called HelloWorld.class.
javac HelloWorld.java
Step 5: Run the Program
- In the same Command Prompt or Terminal, type java HelloWorld and press Enter.
- You should see the output: Hello, World!
java HelloWorld