Welcome to Java! Your First Program
Hello, future Java developer! Welcome to the very first chapter of your journey from zero to mastery in Java. We’re incredibly excited to have you here. In this chapter, we’re going to take our very first “baby steps” into the world of Java. Don’t worry if you’ve never coded before – we’ll guide you through every single detail.
Our mission in this chapter is simple yet crucial: we’ll get your computer set up for Java development, understand the fundamental components that make Java tick, and then write, compile, and run your very first Java program. This “Hello, World!” program is a rite of passage for every programmer and will lay the foundation for everything we build together.
There are no prerequisites for this chapter, as this is where we begin our adventure! Just bring your curiosity, a willingness to learn, and a desire to build amazing things. Let’s dive in!
What Exactly Is Java?
Before we start typing code, let’s get a high-level understanding of what Java is. Imagine Java as a powerful, versatile toolkit for building all sorts of software.
Java is:
- Platform-Independent: This is one of Java’s superpowers! Write once, run anywhere. This means Java code compiled on a Windows machine can run on macOS, Linux, or even embedded devices, without needing to be rewritten. How cool is that?
- Object-Oriented: Java organizes code into “objects” which are like blueprints for creating things in your program. This approach helps in creating modular, reusable, and maintainable code. We’ll explore this much more in depth later!
- Widely Used: From Android apps and enterprise systems to scientific applications and big data processing, Java is everywhere. Learning Java opens up a world of possibilities.
The Java Ecosystem: JDK, JRE, and JVM
When you hear “Java,” you’re often referring to a whole ecosystem. Let’s demystify three core components:
- JDK (Java Development Kit): Think of the JDK as the complete toolbox for a Java developer. It includes everything you need to write, compile, and run Java applications. It contains the JRE (we’ll get to that next) plus development tools like the compiler (
javac). - JRE (Java Runtime Environment): The JRE is what you need to run Java applications. If you’re just a user who wants to use a Java program, you only need the JRE. It contains the JVM and core libraries. It’s like the engine that powers Java applications.
- JVM (Java Virtual Machine): This is the heart of Java’s “write once, run anywhere” philosophy. The JVM is an abstract machine that provides a runtime environment for Java bytecode (the compiled form of your Java code) to execute. When you run a Java program, the JVM translates that bytecode into machine-specific instructions for your computer. It’s the magic translator!
Analogy Time: Imagine you’re building a LEGO spaceship.
- The JDK is like the entire LEGO factory: it has all the molds, raw materials, instructions, and tools to design and build LEGO pieces and entire spaceships.
- The JRE is like a pre-assembled LEGO kit with all the necessary pieces and instructions to build and play with a specific spaceship model. You can’t make new pieces, but you can assemble and use what’s given.
- The JVM is the person actually assembling the spaceship according to the instructions, making sure each piece fits and functions as intended, regardless of where they are building it (on a table, on the floor, etc.).
Choosing Your JDK Version: Latest vs. LTS (as of Dec 2025)
As of December 4, 2025, Java has a rapid release cycle. Here’s what you need to know about versions:
- JDK 25: This is the latest stable release of Java, having been released in September 2025. It includes the newest features and improvements. You can find its official documentation here: JDK 25 Documentation
- JDK 21: This is the previous Long-Term Support (LTS) release, released in September 2023. LTS versions receive extended support and are often preferred by large organizations for their stability and predictability in production environments.
For this guide, we’ll generally proceed with JDK 25 as it represents the most current version. However, please know that the core concepts you’ll learn are highly transferable across JDK 21, 25, and future versions. If your workplace or a specific project requires JDK 21, you’ll still be perfectly equipped!
Setting Up Your Java Development Environment
Let’s get the JDK installed! We’ll recommend Adoptium Temurin as it’s a popular, open-source, and freely redistributable build of the JDK.
Step 1: Download the JDK (Temurin 25)
- Open your web browser and go to the Adoptium website: https://adoptium.net/temurin/releases/
- Look for the “Temurin 25 (Latest)” section.
- Choose the installer appropriate for your operating system:
- Windows: Select the
x64architecture and download the.msiinstaller. - macOS: Select the
x64(for Intel Macs) oraarch64(for Apple Silicon Macs) architecture and download the.pkginstaller. - Linux: Select your architecture (
x64,aarch64) and download the.tar.gzarchive. (For Linux, you might also find specific packages for your distribution, e.g.,aptfor Debian/Ubuntu,yumfor Fedora/RHEL).
- Windows: Select the
Step 2: Install the JDK
- Windows:
- Double-click the downloaded
.msifile. - Follow the on-screen instructions. It’s generally safe to accept the default options. Make sure the option to “Set JAVA_HOME variable” and “Add to PATH” is selected (it usually is by default).
- Double-click the downloaded
- macOS:
- Double-click the downloaded
.pkgfile. - Follow the installation wizard. Enter your password when prompted.
- Double-click the downloaded
- Linux (using
.tar.gz- general approach):- Open a terminal.
- Create a directory for Java installations (e.g.,
sudo mkdir /usr/lib/jvm). - Extract the archive:
sudo tar -xvf <downloaded_file>.tar.gz -C /usr/lib/jvm/(replace<downloaded_file>with the actual file name). - You’ll then need to configure your
PATHandJAVA_HOMEenvironment variables. This varies slightly by distribution, but typically involves adding lines like these to your~/.bashrc,~/.zshrc, or~/.profilefile:Remember toexport JAVA_HOME="/usr/lib/jvm/jdk-<version>" # e.g., /usr/lib/jvm/jdk-25.0.1 export PATH="$JAVA_HOME/bin:$PATH"sourceyour shell configuration file (e.g.,source ~/.bashrc) after making changes.
Step 3: Verify Your Installation
After installation, open a new terminal or command prompt and type the following commands:
java -version
You should see output similar to this (the exact build number might vary):
openjdk version "25.0.1" 2025-09-16
OpenJDK Runtime Environment Temurin-25.0.1+1 (build 25.0.1+1)
OpenJDK 64-Bit Server VM Temurin-25.0.1+1 (build 25.0.1+1, mixed mode)
Now try the compiler:
javac -version
You should see:
javac 25.0.1
If you see these outputs, congratulations! Java JDK 25 is successfully installed on your system. If not, don’t worry, we’ll cover common pitfalls later.
Choosing Your Code Editor / IDE
While you can write Java code in a simple text editor, an IDE (Integrated Development Environment) makes coding much, much easier. It provides features like code auto-completion, error highlighting, debugging tools, and much more.
For beginners, we highly recommend Visual Studio Code (VS Code). It’s lightweight, free, and incredibly versatile.
- Download VS Code: Go to https://code.visualstudio.com/ and download the installer for your OS.
- Install VS Code: Follow the standard installation steps.
- Install Java Extension Pack:
- Open VS Code.
- Go to the Extensions view by clicking the square icon on the sidebar (or press
Ctrl+Shift+X/Cmd+Shift+X). - Search for “Java Extension Pack” by Microsoft.
- Click “Install.” This pack includes essential tools for Java development in VS Code.
Alternatively, more powerful (and resource-intensive) IDEs like IntelliJ IDEA Community Edition or Eclipse IDE are also excellent choices for Java development, especially as you progress. Feel free to explore them later!
Your First Java Program: Hello, World!
The “Hello, World!” program is a classic for a reason: it’s the simplest way to get a program up and running. Let’s break down its structure and then write it step-by-step.
Understanding the Basic Structure
A minimal Java program looks something like this:
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Let’s dissect this line by line:
public class MyProgram { ... }class: In Java, all code lives inside classes. A class is a blueprint for creating objects. Think of it as a container for your code.MyProgram: This is the name of our class. It should always start with an uppercase letter and match the filename (e.g.,MyProgram.java).public: This is an “access modifier.”publicmeans this class can be accessed from anywhere.{ }: These curly braces define the “body” of the class, containing all its members (like methods).
public static void main(String[] args) { ... }- This is the main method, the entry point of every standalone Java application. When you run a Java program, the JVM looks for this specific method and starts executing code from here.
public: Again, an access modifier, meaning it can be accessed from anywhere.static: This keyword means themainmethod belongs to the class itself, not to any specific object of the class. You don’t need to create an object ofMyProgramto callmain.void: This means themainmethod doesn’t return any value after it finishes executing.main: This is the specific name the JVM looks for. It must bemain.(String[] args): This defines the parameters themainmethod can accept.argsis an array ofStringobjects, which can be used to pass command-line arguments to your program when you run it. We won’t use them today, but it’s good to know they’re there!{ }: These curly braces define the “body” of themainmethod, containing the instructions to be executed.
System.out.println("Hello, World!");- This is the instruction that actually does something visible: it prints text to your console (the screen where you run your program).
System: A built-in Java class that provides access to system resources.out: A static member of theSystemclass, representing the standard output stream (usually your console).println: A method of theoutobject (and thus theSystemclass) that prints the given argument to the console, followed by a new line. (printwould print without a new line).("Hello, World!"): This is the “argument” being passed to theprintlnmethod – the text we want to display. Text in Java is enclosed in double quotes (").;: Every statement in Java must end with a semicolon. It’s like the period at the end of a sentence.
Step-by-Step Implementation: Creating Your First Program
Let’s put this knowledge into practice!
Step 1: Create a Project Folder
First, create a new folder on your computer to store your Java code. Let’s call it JavaProjects. Inside JavaProjects, create another folder called MyFirstProgram.
- Windows:
C:\Users\YourUser\JavaProjects\MyFirstProgram - macOS/Linux:
/Users/youruser/JavaProjects/MyFirstProgram
Step 2: Open VS Code in Your Project Folder
Open VS Code and then go to File > Open Folder... (or Cmd+K Cmd+O on macOS, Ctrl+K Ctrl+O on Windows/Linux) and select your MyFirstProgram folder.
Step 3: Create Your Java File
In VS Code’s Explorer view (the sidebar on the left), click the “New File” icon (looks like a page with a plus sign) and name the file HelloWorld.java. Remember, the class name and file name must match, including capitalization!
Step 4: Add the Class Definition
Now, type the following into your HelloWorld.java file:
// HelloWorld.java
public class HelloWorld {
}
Explanation: We’re defining our first class, HelloWorld. The public keyword means it’s accessible from anywhere, and class declares it as a class. The curly braces {} define its boundaries. Right now, it’s an empty container.
Step 5: Add the Main Method
Next, inside the curly braces of your HelloWorld class, add the main method:
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
}
}
Explanation: We’ve added the special main method. This is where our program’s execution will begin. It’s public (accessible), static (belongs to the class), returns void (nothing), and takes an array of String arguments. Still an empty method, though!
Step 6: Add the Print Statement
Finally, inside the curly braces of your main method, add the line to print “Hello, Java Learners!”:
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java Learners!");
}
}
Explanation: This is the core instruction! System.out.println() is a method call that prints the string “Hello, Java Learners!” to the console, followed by a new line. Don’t forget that crucial semicolon ; at the end!
Save your file (Ctrl+S or Cmd+S).
Step 7: Compile Your Java Code
Now, let’s turn your human-readable Java code into bytecode that the JVM can understand.
Open the terminal in VS Code: Go to
Terminal > New Terminal(or pressCtrl+``/ `Cmd+).Make sure your terminal is in the
MyFirstProgramdirectory. If not, usecd MyFirstProgramto navigate there.Type the following command and press Enter:
javac HelloWorld.javaExplanation:
javacis the Java Compiler. It takes your.javasource file and translates it into bytecode.HelloWorld.javais the name of the source file we want to compile.
If successful, you won’t see any output in the terminal. However, if you look in your
MyFirstProgramfolder (or VS Code’s Explorer), you’ll now see a new file:HelloWorld.class. This is your compiled bytecode!
Step 8: Run Your Java Program
With the bytecode ready, let’s execute it using the JVM!
In the same terminal window (still in
MyFirstProgramdirectory), type:java HelloWorldExplanation:
javais the Java Launcher (which invokes the JVM). It takes the name of your compiled class file (without the.classextension) and tells the JVM to execute itsmainmethod.HelloWorldis the name of the class containing themainmethod we want to run.
You should see the output:
Hello, Java Learners!
Congratulations! You’ve just written, compiled, and run your very first Java program! Take a moment to celebrate this achievement.
Mini-Challenge: Personalize Your Greeting!
Now that you’ve got the hang of the basic “Hello, World!” program, let’s make a small change.
Challenge: Modify your HelloWorld.java program to print a personalized greeting that includes your name, and then print a simple arithmetic calculation (e.g., 5 + 3).
Hint:
- You can put any text you want inside the double quotes for
System.out.println(). - You can also print numbers or the result of calculations directly using
System.out.println(). For example,System.out.println(5 + 3);
What to Observe/Learn:
- How easy it is to change the output of your program.
- That
System.out.println()can handle different types of data (strings and numbers). - The compile-run cycle: you always need to
javac(recompile) after making changes to your.javafile before youjava(run) it again.
Common Pitfalls & Troubleshooting
Don’t worry if your program didn’t run perfectly the first time. Everyone makes mistakes, especially when starting out! Here are some common issues and how to fix them:
'javac' is not recognized as an internal or external command...(or similar on Linux/macOS)- Problem: Your operating system can’t find the
javac(Java compiler) command. This almost always means yourPATHenvironment variable isn’t set up correctly. - Solution:
- Recheck JDK Installation: Go back to “Setting Up Your Java Development Environment” and ensure the JDK was installed correctly.
- Verify PATH: For Windows users, during installation, ensure “Add to PATH” was selected. For macOS/Linux, double-check your
~/.bashrc,~/.zshrc, or~/.profilefile for theJAVA_HOMEandPATHexports, and ensure you’vesourced the file or opened a new terminal. - Restart Terminal/Computer: Sometimes a simple restart of your terminal or even your computer can resolve environment variable issues.
- Problem: Your operating system can’t find the
Error: Could not find or load main class HelloWorld(or similar)- Problem: The Java Virtual Machine (JVM) couldn’t find your compiled
HelloWorld.classfile, or there was a problem with the class itself. - Solution:
- Compile First: Did you forget to run
javac HelloWorld.javabeforejava HelloWorld? You must compile first! - Correct Directory: Are you running the
javacommand from the same directory whereHelloWorld.classis located? Usecdto navigate to the correct folder. - Matching Names: Does your filename (
HelloWorld.java) exactly match your class name (public class HelloWorld)? Is yourmainmethod spelled exactlypublic static void main(String[] args)? Java is case-sensitive! - No
.classextension: When runningjava, you specify the class name, not the file name with.classextension (e.g.,java HelloWorld, notjava HelloWorld.class).
- Compile First: Did you forget to run
- Problem: The Java Virtual Machine (JVM) couldn’t find your compiled
Missing Semicolons or Curly Braces
- Problem: Java is strict about syntax. Forgetting a
;at the end of a statement or mismatching{}braces will lead to compilation errors. - Solution: The
javaccompiler will usually give you helpful error messages, pointing to the line number where it found the issue. For example:
Carefully read the error message and check the indicated line. VS Code’s Java Extension Pack will also often highlight these errors in red before you even compile!HelloWorld.java:6: error: ';' expected System.out.println("Hello, Java Learners!") ^ 1 error
- Problem: Java is strict about syntax. Forgetting a
Summary: Key Takeaways from Chapter 1
Phew! You’ve accomplished a lot in this first chapter. Here’s a quick recap of what we covered:
- Java Fundamentals: We introduced Java as a platform-independent, object-oriented programming language.
- Java Ecosystem: You learned the difference between JDK (Development Kit), JRE (Runtime Environment), and JVM (Virtual Machine).
- JDK Versioning: We discussed the latest stable release (JDK 25) and the previous Long-Term Support release (JDK 21), and why you might choose one over the other.
- Setup: You successfully installed Adoptium Temurin JDK 25 and verified your installation.
- Development Tools: You set up Visual Studio Code and its Java Extension Pack.
- First Program: You wrote your first
HelloWorld.javaprogram, understanding the purpose of classes, themainmethod, andSystem.out.println(). - Compile & Run: You mastered the
javaccommand to compile your code into bytecode and thejavacommand to execute it via the JVM. - Troubleshooting: We looked at common errors and how to fix them.
You’re now officially a Java developer in training! Giving yourself this solid foundation is the most important first step.
What’s Next?
In Chapter 2: Variables and Data Types - Storing Information, we’ll dive into how Java stores and manipulates data. You’ll learn about different types of information your programs can handle, like numbers and text, and how to declare variables to hold them. Get ready to make your programs even more dynamic!