In this article, we'll walk you through writing and running a basic Java program on Windows. We'll start with a simple example where we create a Car class, set some properties like color and model, and have the car "start its engine." The Java program will then print out details about the car and simulate starting the engine.
Step 1. Install Java Development Kit (JDK).
Before you can write and run Java programs, you need to install Java. Here's how.
-
Visit the official Java download page and download the Java Development Kit (JDK). You can choose the latest version for Windows.
-
After downloading the installer, run it and follow the steps to install Java on your computer.
-
Set Up the Environment
- Right-click on This PC or Computer, and select Properties.
- Click on Advanced system settings and then on Environment Variables.
- Under System variables, find the Path variable, click Edit, and add the path to your bin folder inside the JDK directory (e.g., C:\Program Files\Java\jdk-xx\bin).
Step 2. Write Your First Java Program.
Now, let’s create a simple Java program that represents a car. Here’s the code.
import java.util.*;
public class Car {
// Properties (fields)
String color;
String model;
// Method (function) to start the engine
public void startEngine() {
System.out.println("The engine is now running.");
}
// Main method to run the program
public static void main(String[] args) {
// Create an instance of Car
Car myCar = new Car();
// Set properties (color and model)
myCar.color = "Red";
myCar.model = "Toyota";
// Print car details
System.out.println("Car model: " + myCar.model);
System.out.println("Car color: " + myCar.color);
// Call method to start the engine
myCar.startEngine();
}
}
Step 3. Compile and Run the Program.
To run this Java program, follow these steps.
3.1. Save the Code.
- Open Visual Studio code on your computer.
- Copy and paste the Java code from above.
- Save the file as Car.java (make sure to include the .java extension).
3.2. Open Command Prompt.
- Press Windows + R, type cmd, and press Enter to open the Command Prompt.
3.3. Navigate to Your Program's Folder.
Use the cd command to go to the folder where you saved Car.java. For example, if you saved it in C:\Java, type.
3.4. Compile the Program.
To compile your Java program, type the following command.
This will create a file called Car.class, which is the compiled version of your program.
3.5. Run the Program.
Now, to run the program, type.
You should see the following output.
Conclusion
Running a simple Java program on Windows is easy once you have the JDK installed and set up properly. In this guide, we created a Car class, defined properties for the car, and wrote a method to simulate starting the engine. By following the steps, you should be able to write, compile, and run your own Java programs!