Before writing your first Java program, make sure you have the following:
-
Java Development Kit (JDK): This essential software is needed to write and run Java programs. You can download it from Oracle’s website.
-
Text Editor or Integrated Development Environment (IDE): While you can use basic text editors like Notepad, an IDE like IntelliJ IDEA or Eclipse provides helpful features that simplify coding.
Once these are ready, you’re set to begin coding! Let’s jump into writing your first "Hello World" in Java.
Writing Your First Java Program
Setting Up Your Environment
First, open your IDE or text editor. Create a new file with a .java
extension. For this guide, let’s name our file HelloWorld.java
.
Writing the Code
Here’s the simple Java code to print "Hello World":
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Let’s break this down line by line so it all makes sense.
Understanding the Code
Declaring the Class
public class HelloWorld {
Every Java program has at least one class. In this case, HelloWorld
is the class name. A class in Java is merely a blueprint for creating objects. The keyword public
is an access modifier, which dictates the visibility of who can use the class.
The Main Method
public static void main(String[] args) {
The main
method is the starting point of any Java application. Here’s the lowdown:
-
public
: Again, this is an access modifier. It allows themain
method to be accessible from anywhere. -
static
: This keyword means that the method belongs to the class, not instances of the class. Simply put, you don’t need to instantiate the class to use this method. -
void
: This means the method doesn’t return any value. -
String[] args
: This is an array of strings. It allows the program to accept arguments from the command line, though you won’t need this for "Hello World."
Printing the Message
System.out.println("Hello World");
This line is where the action happens. Here’s how it works:
-
System
: A pre-defined class that provides access to the system. -
out
: A static member of theSystem
class, usually connected to the console. -
println
: A method of thePrintStream
class. It prints the argument passed to it, followed by a new line.
Running Your Java Program
Compiling the Code
After saving your Java file, you need to compile it. Open the command prompt (or terminal on MacOS/Linux) and navigate to the directory containing your HelloWorld.java
file.
Run the following command:
javac HelloWorld.java
This command compiles the file, converting the Java code into bytecode that the Java Virtual Machine (JVM) can understand. If you don’t see any errors, you’re good to go!
Executing the Program
To run your program, use the java
command in your terminal:
java HelloWorld
If you’ve done everything right, you should see this output:
Hello World
Congratulations! You’ve just written and executed your first Java program.