Java Get Started
Java is a general-purpose, object-oriented programming language that runs on almost every kind of computer, from laptops to servers to mobile devices. What makes Java special is that you write your code once, and the same compiled program can run anywhere a Java Virtual Machine is installed, without changes. In this lesson you will set up your environment, write your very first Java program, and understand exactly what happens when you compile and run it.
Overview: How Java Works
Before writing any code, it helps to understand three terms that are often confused: the JDK, the JRE, and the JVM.
- JVM (Java Virtual Machine) — a program that executes Java bytecode. It is the piece that actually runs your compiled program, and it is different for each operating system, which is why Java programs are portable.
- JRE (Java Runtime Environment) — the JVM plus the standard class libraries needed to run Java programs. If you only want to run Java applications (not write your own), the JRE used to be enough.
- JDK (Java Development Kit) — the JRE plus development tools, most importantly the compiler (
javac). To write and compile Java code, you need the JDK. Modern JDK downloads (from Oracle, or open-source builds like Eclipse Temurin/OpenJDK) bundle the JRE inside them.
Java is a compiled and interpreted language at the same time. When you write a file such as Main.java, the Java compiler (javac) does not translate it directly into machine code for your specific CPU. Instead, it translates it into an intermediate, platform-independent format called bytecode, stored in a .class file. That bytecode is what makes Java’s “write once, run anywhere” promise possible: the same .class file can be handed to a JVM on Windows, macOS, or Linux, and each JVM knows how to translate that bytecode into instructions its own operating system and CPU understand. This is fundamentally different from a language like C, where the compiler produces machine code tied to one specific platform.
Once bytecode exists, the java command launches the JVM, which loads the class, verifies that the bytecode is safe and well-formed, and then executes it. Modern JVMs use a technique called Just-In-Time (JIT) compilation: frequently executed bytecode is compiled into native machine code on the fly, while it runs, so long-running Java programs end up nearly as fast as natively compiled code, while still keeping the portability of bytecode.
Installing the JDK
To follow along, install a JDK (Java 17 or newer is a good default, since these are Long-Term Support releases). After installing, open a terminal and check the versions of the compiler and the runtime:
javac -version
java -version
If both commands print a version number instead of an error, you are ready to write Java code.
Syntax
Every runnable Java program needs at least one class, and that class needs a special method named main, which is the entry point the JVM looks for when it starts your program. The general shape looks like this:
public class Main {
public static void main(String[] args) {
// your code goes here
}
}
| Part | Meaning |
|---|---|
public class Main |
Declares a class named Main. The class name must exactly match the file name (Main.java), including capitalization. |
public static void main(String[] args) |
The method the JVM calls to start the program. It must be spelled exactly this way (lowercase main). |
public |
Access modifier meaning the JVM (from outside the class) is allowed to call this method. |
static |
Means the method belongs to the class itself, so the JVM can call it without first creating an object of the class. |
void |
The method returns no value. |
String[] args |
An array of command-line arguments passed to the program; it is required in the signature even if you don’t use it. |
Examples
Example 1: Hello, World!
The traditional first program in any language simply prints a message to the screen. In Java, that means using System.out.println, which writes text to the console followed by a new line.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("Welcome to Java programming.");
}
}
Output:
Hello, World!
Welcome to Java programming.
Each call to System.out.println prints its argument and then moves to a new line, which is why the two messages appear on separate lines. System is a built-in class, out is a stream object representing the console, and println is a method on that stream.
Example 2: Variables and Output
Real programs store data in variables. This example declares a few variables of different types and prints them by concatenating strings with the + operator.
public class Main {
public static void main(String[] args) {
String language = "Java";
int version = 21;
double releaseYear = 1995;
boolean isObjectOriented = true;
System.out.println("Language: " + language);
System.out.println("Current LTS version: " + version);
System.out.println("First released in: " + (int) releaseYear);
System.out.println("Object-oriented: " + isObjectOriented);
}
}
Output:
Language: Java
Current LTS version: 21
First released in: 1995
Object-oriented: true
Java is statically typed: every variable is declared with a fixed type (String, int, double, boolean) and can only ever hold values of that type. When a non-string value is concatenated with + next to a String, Java automatically converts it to text for you.
Example 3: A Small Calculation
Here is a slightly more realistic example that performs arithmetic and formats the output using System.out.printf, which works like a template with placeholders.
public class Main {
public static void main(String[] args) {
double width = 12.5;
double height = 4.0;
double area = width * height;
double perimeter = 2 * (width + height);
System.out.printf("Width: %.1f, Height: %.1f%n", width, height);
System.out.printf("Area: %.2f%n", area);
System.out.printf("Perimeter: %.2f%n", perimeter);
}
}
Output:
Width: 12.5, Height: 4.0
Area: 50.00
Perimeter: 33.00
The format specifier %.2f means “print a floating-point number rounded to 2 decimal places,” and %n inserts a platform-correct new line. printf is useful whenever you need aligned or precisely formatted numeric output.
How It Works Step by Step (Under the Hood)
When you compile and run Main.java, several distinct steps happen:
- 1. Compilation: Running
javac Main.javareads your source file, checks it for syntax and type errors, and — if it is valid — produces a file namedMain.classcontaining Java bytecode. - 2. Launching the JVM: Running
java Mainstarts a new instance of the Java Virtual Machine for your program. - 3. Class loading: The JVM’s class loader locates
Main.classon the classpath and loads its bytecode into memory. - 4. Bytecode verification: Before executing anything, the JVM verifies the bytecode is structurally valid and doesn’t violate Java’s safety rules (for example, it can’t fabricate memory addresses).
- 5. Execution: The JVM locates the
public static void main(String[] args)method and begins executing its bytecode instructions one by one, using an interpreter at first and switching hot code paths to compiled native code via the JIT compiler as the program runs. - 6. Memory management: As objects are created, they are allocated on the heap; local variables and method call information live on the stack. The JVM’s garbage collector automatically frees heap memory that is no longer reachable, so you don’t manually free memory like in C.
- 7. Program exit: When
mainreturns (or all non-daemon threads finish), the JVM shuts down and control returns to the operating system.
Common Mistakes
Mistake 1: Class name doesn’t match the file name. If you save your file as Main.java but declare public class HelloWorld { ... } inside it, javac will refuse to compile with an error like “class HelloWorld is public, should be declared in a file named HelloWorld.java”. The fix is simple: the public class name and the file name (minus .java) must match exactly, including capitalization — as shown correctly in Example 1, where the file is Main.java and the class is Main.
Mistake 2: Misspelling or mis-casing the main method. Java is case-sensitive, so writing public static void Main(String[] args) (capital M) or leaving out static compiles fine as ordinary code, but the JVM will report “Error: Main method not found in class Main” because it is looking for the exact signature public static void main(String[] args). Always copy this signature precisely, as shown in the Syntax section above.
Mistake 3: Forgetting semicolons or mismatched braces. Every statement in Java must end with a semicolon (;), and every opening brace { needs a matching closing brace }. Missing either one produces a compiler error pointing near the mistake — sometimes on a later line than where the real problem is, so when you get a confusing compiler error, check the line just above the one reported first.
Best Practices
- Name your source file after its public class exactly, using UpperCamelCase for class names (e.g.,
BankAccount.javaforclass BankAccount). - Compile with
javac YourFile.javaand run withjava YourFile(no.javaextension and no.classextension on the run command). - Use a modern LTS JDK version (17 or 21) unless you have a specific reason to target an older one.
- Read compiler error messages from the top down — the first error is usually the real cause; later ones can be side effects of it.
- Use an IDE (IntelliJ IDEA, Eclipse, or VS Code with the Java extension pack) once you’re comfortable with the command line — it will catch many mistakes as you type.
- Keep
mainsmall: use it to kick off your program’s logic rather than writing all your code inside it.
Practice Exercises
- Exercise 1: Write a program called
Main.javathat prints your name, your favorite programming language, and one sentence about why you’re learning Java, each on its own line. - Exercise 2: Declare an
intvariable for a temperature in Celsius, compute the Fahrenheit equivalent using the formulaF = C * 9 / 5 + 32, and print both values with a clear label. Try it with a Celsius value of25and check that the printed Fahrenheit value is77. - Exercise 3: Intentionally rename your public class to something different from the file name, try to compile it with
javac, and read the exact error message the compiler gives you. Then fix it and confirm it compiles.
Summary
- The JDK includes the compiler (
javac) and tools needed to develop Java programs; the JVM is what actually executes compiled bytecode. javaccompiles.javasource files into platform-independent.classbytecode files;javalaunches the JVM to run that bytecode.- Every Java program needs a class whose name matches its file name, containing a method with the exact signature
public static void main(String[] args). - Java is statically typed: variables are declared with a fixed type and the compiler checks type correctness before your program ever runs.
- The JVM handles memory automatically via garbage collection, and uses JIT compilation to make bytecode run close to native speed.
- Most beginner errors come from filename/class name mismatches, incorrect
mainsignatures, or missing semicolons/braces — read the compiler’s error message carefully, it usually tells you exactly what’s wrong.
