Java Introduction

Java is a general-purpose, object-oriented programming language created by Sun Microsystems in 1995 (now owned by Oracle). It powers everything from Android apps and enterprise backend systems to embedded devices and big data platforms like Hadoop and Spark. Java’s defining promise is “write once, run anywhere”: you compile your code once, and it can run unmodified on any device that has a Java Virtual Machine installed, whether that’s Windows, macOS, Linux, or a server in the cloud.

Overview / How Java Works

Unlike languages such as C that compile directly to machine code for a specific processor, Java uses a two-step process. First, the Java compiler (javac) translates your human-readable .java source file into an intermediate format called bytecode, stored in a .class file. This bytecode is not tied to any particular operating system or CPU architecture. Second, the Java Virtual Machine (JVM) reads that bytecode and executes it, translating it into native instructions for whatever machine it’s running on. This is the core idea behind Java’s portability: the JVM is platform-specific, but your compiled bytecode is not.

Java is also a strongly, statically typed language, meaning every variable’s type is known at compile time and checked before the program ever runs. This catches a large class of bugs early. Java is object-oriented, meaning code is organized around classes and objects that bundle data (fields) with behavior (methods). Every Java program starts execution from a special method called main, which the JVM looks for as the entry point.

Java also manages memory automatically through a process called garbage collection. When you create objects with the new keyword, they’re allocated on a region of memory called the heap. When an object is no longer reachable by your running program, the garbage collector reclaims that memory for you, so you don’t manually allocate and free memory the way you would in C or C++. This makes Java significantly less prone to memory leaks and dangling-pointer bugs, at the cost of some runtime overhead.

The combination of the JVM, the standard library (a huge collection of pre-written, tested classes for strings, collections, networking, file I/O, and more), and strict typing is why Java became the backbone of large-scale, long-lived enterprise software: it favors predictability and safety over raw speed of writing quick scripts.

Syntax

Every standalone Java program needs at least one class, and if that class is meant to be run directly, it needs a main method with this exact signature:

public class Main {
    public static void main(String[] args) {
        // your code goes here
    }
}
Part Meaning
public class Main Declares a class named Main. The file must be named Main.java to match the public class.
public static void main(String[] args) The entry point the JVM calls first. public means accessible from anywhere, static means it belongs to the class itself (no object needed), void means it returns nothing, and String[] args holds command-line arguments.
{ } Curly braces mark the start and end of a block of code, such as a class body or method body.
; Every statement in Java must end with a semicolon.
// or /* */ Single-line and multi-line comments, ignored by the compiler.

Java is also case-sensitive (Main and main are different identifiers) and whitespace-insensitive (indentation is for humans, not the compiler).

Examples

Example 1: Hello, World!

The traditional first program simply prints text to the console using System.out.println, which writes a line of text followed by a newline.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Hello, World!

Here, System.out is a pre-built object representing the standard output stream (usually your terminal), and println is a method on that object that prints its argument followed by a line break.

Example 2: Variables and Types

Real programs store and manipulate data using variables. This example declares several variables of different types and computes the area of a rectangle.

public class Main {
    public static void main(String[] args) {
        String shape = "rectangle";
        double length = 12.5;
        double width = 4.0;
        double area = length * width;
        int sides = 4;
        boolean isSquare = (length == width);

        System.out.println("Shape: " + shape);
        System.out.println("Sides: " + sides);
        System.out.println("Area: " + area);
        System.out.println("Is square? " + isSquare);
    }
}
Shape: rectangle
Sides: 4
Area: 50.0
Is square? false

This example shows four of Java’s built-in types: String for text, double for decimal numbers, int for whole numbers, and boolean for true/false values. The + operator concatenates strings with other values, automatically converting numbers and booleans to text.

Example 3: Reading User Input

Programs become interactive using the Scanner class from java.util, which reads input typed at the console. This example reads a price and quantity, then calculates a total including tax.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter item price: ");
        double price = scanner.nextDouble();
        System.out.println("Enter quantity: ");
        int quantity = scanner.nextInt();

        double subtotal = price * quantity;
        double taxRate = 0.07;
        double total = subtotal + (subtotal * taxRate);

        System.out.printf("Subtotal: $%.2f%n", subtotal);
        System.out.printf("Total with tax: $%.2f%n", total);

        scanner.close();
    }
}
Enter item price: 
Enter quantity: 
Subtotal: $59.97
Total with tax: $64.17

Assuming the user enters 19.99 for the price and 3 for the quantity, the subtotal is 59.97 and the 7% tax brings the total to 64.17. scanner.nextDouble() and scanner.nextInt() block program execution until the user types a value and presses Enter. System.out.printf formats numbers precisely, here rounding to two decimal places with %.2f.

Under the Hood: From Source to Execution

Understanding what actually happens when you run a Java program clarifies a lot of behavior you’ll see later. The process has four stages:

  • Writing: You write source code in a file such as Main.java.
  • Compiling: Running javac Main.java invokes the Java compiler. It checks your code for syntax and type errors, and if everything is valid, produces a Main.class file containing bytecode. If there are errors, compilation stops and no class file is produced.
  • Loading: Running java Main starts the JVM, which locates Main.class, loads its bytecode into memory via the class loader, and verifies it is safe and well-formed.
  • Executing: The JVM’s execution engine runs the bytecode. Modern JVMs use a Just-In-Time (JIT) compiler that translates frequently executed bytecode into native machine code on the fly, so hot code paths run nearly as fast as natively compiled languages, while less frequently used code stays interpreted to save startup time.

Throughout execution, the JVM manages two key memory regions: the stack, which holds local variables and method call frames (and is reclaimed automatically as methods return), and the heap, which holds objects created with new and is cleaned up periodically by the garbage collector. Understanding this split explains why primitive local variables are fast and short-lived, while objects can persist and be shared as long as something still references them.

Common Mistakes

Mistake 1: Mismatched file name and class name. Java requires the file name to match the public class name exactly, including capitalization.

// File named hello.java, but class is named Main -- fails to compile
public class Main {
    public static void main(String[] args) {
        System.out.println("Hi");
    }
}

The fix is simple: save the file as Main.java whenever the public class is named Main.

Mistake 2: Forgetting the exact main method signature. Beginners sometimes write void main() or public void main(String[] args) without static.

public class Main {
    public void main(String[] args) {  // missing 'static'
        System.out.println("This will not run as expected");
    }
}

Without static, the JVM cannot call main without first creating an object, so it reports that no main method was found. Always use the full signature: public static void main(String[] args).

Mistake 3: Confusing = with ==, or int division with decimal division. A very common bug is expecting 5 / 2 to produce 2.5. Because both operands are int, Java performs integer division and truncates the result to 2. To get a decimal result, at least one operand must be a floating-point type, for example 5.0 / 2 or (double) 5 / 2.

Best Practices

  • Name classes with UpperCamelCase (Main, BankAccount) and variables/methods with lowerCamelCase (totalPrice, calculateTotal).
  • Always match the source file name to the public class name.
  • Close resources like Scanner when you’re done with them to free underlying system handles.
  • Favor descriptive variable names over short cryptic ones; clarity matters more than brevity in Java.
  • Use comments to explain why code does something non-obvious, not to restate what the code already says.
  • Compile often while learning so you catch type and syntax errors early rather than after writing a lot of code.

Practice Exercises

  • Exercise 1: Write a program that declares your name, age, and favorite programming language as variables, then prints a sentence combining all three using string concatenation.
  • Exercise 2: Write a program that reads two integers from the user with Scanner and prints their sum, difference, product, and integer quotient.
  • Exercise 3: Predict, then verify, what System.out.println(7 / 2) and System.out.println(7.0 / 2) each print, and explain the difference in one sentence.

Summary

  • Java compiles to platform-independent bytecode, which the JVM executes, enabling “write once, run anywhere.”
  • Every runnable Java program needs a class containing public static void main(String[] args) as its entry point.
  • Java is statically typed and object-oriented, with automatic memory management via garbage collection.
  • The JVM’s JIT compiler translates hot bytecode paths to native machine code for performance.
  • Common beginner pitfalls include file/class name mismatches, incorrect main signatures, and integer division surprises.