Java Get Started
Java is a general-purpose programming language used to build everything from desktop applications to Android apps and large-scale web services. Getting started means installing the Java Development Kit and running your first program.
What You Need
To write and run Java programs, you need the Java Development Kit, or JDK. The JDK includes the compiler, javac, which turns your source code into bytecode, and the java command, which runs that bytecode on the Java Virtual Machine, or JVM. Because Java code compiles to bytecode instead of machine code, the same compiled program can run on any operating system that has a JVM installed.
You can check whether Java is already installed by opening a terminal or command prompt and typing java -version. If a version number appears, Java is installed and ready to use. If not, download and install the JDK from a trusted source such as Oracle’s or OpenJDK’s website, then confirm the installation the same way.
Writing Your First Java Program
Every Java program lives inside a class, and every standalone program needs a main method, which is where the program starts running. Here is the smallest useful Java program, a classic Hello World example.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output:
Hello, World!
Save this file as Main.java. The file name must match the public class name exactly, including capitalization.
Compiling and Running
Open a terminal in the same folder and compile the file with javac Main.java. This creates a file named Main.class containing the bytecode. Run the compiled program with java Main. When running, use the class name only, without the .java or .class extension.
How It Works
public class Main declares a class named Main; this must match the file name. public static void main(String[] args) declares the main method, the entry point every Java application needs. public means the method is accessible from outside the class, static means it belongs to the class itself rather than to an instance of it, and void means it returns no value. System.out.println("Hello, World!") prints the text inside the parentheses to the console, followed by a new line.
A Few Details to Notice
- Java is case-sensitive, so
Mainandmainare different identifiers. - Every statement ends with a semicolon.
- Curly braces mark the start and end of the class body and the method body.
Once you can compile and run this program, you have a working Java environment and understand the basic shape of every Java program you will write from here on. The next lesson covers Java syntax in more detail, including variables and comments.
