Java programming language introduction

Java is a general-purpose programming language used to build command-line tools, server applications, desktop software, data-processing systems, and applications for other supported platforms. This Java tutorial starts with installation and program structure, then progresses through control flow, methods, object-oriented programming, collections, exception handling, file operations, and concurrency.

The examples are intended for beginners, but they also provide a structured review for programmers moving to Java from another language. You can follow them with a text editor and terminal or use a Java-compatible integrated development environment (IDE).

What is Java?

Java is a high-level, class-based programming language originally developed at Sun Microsystems and now maintained through the Java ecosystem led by Oracle and the OpenJDK community. Java source code is normally compiled into bytecode, which a Java Virtual Machine executes on a supported system.

This source-to-bytecode model supports Java’s platform-neutral approach. The same compiled application can run on compatible Java Virtual Machine implementations, although applications must still account for external libraries, operating-system services, filesystem behavior, and processor architecture where relevant.

Core characteristics of Java programming

  • Statically typed: Variables, method parameters, and return values have declared or inferred types that the compiler checks.
  • Object-oriented: Java supports classes, objects, inheritance, interfaces, encapsulation, and polymorphism.
  • Automatic memory management: The Java Virtual Machine manages object memory and reclaims unreachable objects through garbage collection.
  • Exception handling: Java provides a structured mechanism for reporting and responding to errors and exceptional conditions.
  • Standard library: The Java API includes facilities for collections, files, networking, date and time operations, concurrency, database access, and other common tasks.
  • Multithreading support: Java provides language and library features for running and coordinating concurrent work.

JDK, JVM, and Java runtime terminology

Beginners often encounter the terms JDK, JVM, and JRE while setting up Java. They refer to different parts of the Java platform:

Java termMeaningPrimary role
JVMJava Virtual MachineLoads and executes Java bytecode and manages runtime services such as memory
JDKJava Development KitProvides the compiler, runtime, launcher, documentation tools, debugger tools, and other development utilities
JREJava Runtime EnvironmentTraditionally refers to the JVM and libraries required to run Java applications without development tools

Install a JDK when learning Java because it includes the tools needed to compile and run programs. Modern Java deployment can also use application-specific runtime images, so current JDK distributions may not provide a separate general-purpose JRE download.

Prerequisites for learning Java programming

No previous programming experience is required. The following basic skills will help:

  • Creating, renaming, and locating files and directories.
  • Opening a terminal or command prompt and changing the current directory.
  • Reading short error messages and comparing them with the relevant source line.
  • Breaking a problem into input, processing, and output steps.
  • Practising examples by typing, running, modifying, and debugging the code.

Knowledge of variables, conditions, or loops is helpful but not mandatory. These concepts are included in the learning path below.

Install the Java Development Kit

Download a current JDK suitable for your operating system and processor. The official Java getting-started guide explains available setup approaches. Installation commands and supported versions differ across Windows, macOS, and Linux, so follow the instructions for the selected distribution.

After installation, open a new terminal and check the Java launcher and compiler:

</>
Copy
java --version
javac --version

Both commands should report an installed Java version. If a command is not found, confirm that the JDK’s executable directory is included in the system path and reopen the terminal after changing environment variables.

Text editor and Java IDE options

A text editor is sufficient for the first examples. An IDE can later provide code completion, project management, refactoring, test integration, and debugging. Whichever tool you choose, learn how to compile a small program from the terminal at least once. It makes the relationship between source files, class files, the compiler, and the Java launcher easier to understand.

Write and run your first Java program

Create a file named HelloJava.java and add the following code:

</>
Copy
public class HelloJava {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Open a terminal in the directory containing the file. Compile the source and run the resulting class:

</>
Copy
javac HelloJava.java
java HelloJava

The program prints:

Hello, Java!

javac compiles HelloJava.java into a class file containing bytecode. The java command starts the JVM and invokes the class’s main method. Do not add .class to the class name in the run command.

Java program structure explained

  • public class HelloJava declares a class. When a public top-level class is used, its name must match the source filename.
  • main is the entry point used by the Java launcher for this program.
  • String[] args receives command-line arguments as an array of strings.
  • System.out.println writes a value followed by a line break to standard output.
  • Braces group the class and method bodies, while a semicolon terminates the print statement.

Java variables, data types, and operators

A variable associates a name with a value of a particular type. Java has primitive types for simple values and reference types for objects and arrays.

</>
Copy
public class DataTypesExample {
    public static void main(String[] args) {
        int quantity = 4;
        double unitPrice = 12.50;
        boolean available = true;
        char category = 'A';
        String itemName = "Notebook";

        double total = quantity * unitPrice;

        System.out.println(itemName);
        System.out.println(total);
        System.out.println(available);
        System.out.println(category);
    }
}

The primitive types include integer types such as int and long, floating-point types such as float and double, boolean, and char. String is a class, not a primitive type. Operators perform arithmetic, comparisons, logical operations, assignment, and other language-defined actions.

Java conditions, switch statements, and loops

Control-flow statements determine which instructions run and how often they run. The following program uses an if statement and a for loop:

</>
Copy
public class ControlFlowExample {
    public static void main(String[] args) {
        int score = 72;

        if (score >= 50) {
            System.out.println("Pass");
        } else {
            System.out.println("Review and try again");
        }

        for (int number = 1; number <= 3; number++) {
            System.out.println("Number: " + number);
        }
    }
}
  • Use if, else if, and else to select code based on boolean conditions.
  • Use switch when one expression must be matched against several supported cases.
  • Use a for loop when iteration follows a clear initialization, condition, and update pattern.
  • Use while when repetition should continue while a condition remains true.
  • Use the enhanced for loop to visit elements in an array or iterable collection.

Java methods, parameters, and return values

Methods divide a program into named operations. A method can accept parameters and return a value whose type is declared in the method signature.

</>
Copy
public class MethodExample {
    static int add(int first, int second) {
        return first + second;
    }

    public static void main(String[] args) {
        int result = add(7, 5);
        System.out.println(result);
    }
}

Here, add accepts two int parameters and returns an int. Java also supports method overloading, which permits methods in the same class to share a name when their parameter lists differ.

Java classes, objects, constructors, and encapsulation

A class defines state and behavior, while an object is an instance of that class. The following example keeps a field private and provides a method that operates on it:

</>
Copy
class BankAccount {
    private double balance;

    BankAccount(double openingBalance) {
        balance = openingBalance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    double getBalance() {
        return balance;
    }
}

public class AccountExample {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(100.0);
        account.deposit(25.0);
        System.out.println(account.getBalance());
    }
}

The constructor initializes each new BankAccount. Declaring balance as private prevents unrelated code from modifying it directly. This is an example of encapsulation: the class controls access to its internal state through defined operations.

Java inheritance, interfaces, and polymorphism

  • Inheritance: A class can extend another class and inherit accessible state and behavior.
  • Interface: An interface defines a contract that implementing classes agree to provide.
  • Polymorphism: Code can work with an interface or superclass reference while the referenced object supplies its specific implementation.
  • Abstract class: An abstract class can share implementation and state while leaving selected operations for subclasses to implement.

Prefer inheritance when the relationship accurately models one type as a specialized form of another. Composition, in which one object uses other objects, is often clearer when classes merely need to collaborate.

Java arrays, collections, and generics

An array stores a fixed number of elements of one type. The Java Collections Framework provides resizable and specialized structures such as lists, sets, queues, and maps.

</>
Copy
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> topics = new ArrayList<>();
        topics.add("Variables");
        topics.add("Methods");
        topics.add("Classes");

        for (String topic : topics) {
            System.out.println(topic);
        }
    }
}

The generic type List<String> tells the compiler that this list stores strings. Choose a collection according to the required behavior: ordering, duplicate handling, lookup method, insertion pattern, and concurrency requirements.

Java exception handling and resource management

Exceptions represent conditions that interrupt normal execution. Java uses try, catch, finally, throw, and throws to define how such conditions are reported and handled.

</>
Copy
public class NumberExample {
    public static void main(String[] args) {
        String input = "42";

        try {
            int number = Integer.parseInt(input);
            System.out.println(number * 2);
        } catch (NumberFormatException exception) {
            System.out.println("Input must be a whole number");
        }
    }
}

Catch an exception only when the program can handle it meaningfully, add relevant context, or translate it at an appropriate boundary. Do not use an empty catch block. For closeable files, streams, database statements, and similar resources, learn Java’s try-with-resources statement so that resources are closed reliably.

Java tutorial learning path from basics to practical programs

  1. Java setup and execution: Install a JDK, understand the JVM, and compile and run a class from the command line.
  2. Java syntax fundamentals: Study identifiers, variables, primitive types, strings, operators, type conversion, input, and output.
  3. Java control flow: Practise boolean expressions, conditions, switch statements, loops, break, and continue.
  4. Java methods: Learn parameters, return values, scope, overloading, recursion, and how to divide a problem into operations.
  5. Java object-oriented programming: Work with classes, objects, constructors, access modifiers, encapsulation, inheritance, interfaces, abstract classes, and polymorphism.
  6. Java data structures: Compare arrays with lists, sets, queues, and maps; then learn iteration and generics.
  7. Java error handling: Read compiler diagnostics, debug runtime behavior, handle exceptions, and create suitable application exceptions.
  8. Java files and APIs: Read and write files, use paths and streams, and become comfortable consulting API documentation.
  9. Java testing and project tools: Write automated tests and learn the build tool used by the project you are working on.
  10. Java concurrency and application development: Study threads, executors, synchronization, immutability, and the libraries or frameworks relevant to the intended application type.

The official Learn Java resources and Oracle Java Tutorials can be used as references while following this sequence. Check the version context of older examples because language features and recommended APIs can change between Java releases.

Java practice projects for beginners

Small programs are useful for connecting individual language features. Start with terminal-based projects before adding user interfaces, databases, or web frameworks.

  • Number analyser: Read numbers and report totals, averages, minimums, maximums, and invalid input.
  • Unit converter: Use methods and conditions to convert temperatures, lengths, or weights.
  • Contact manager: Model contacts as objects and store them in a collection.
  • Expense tracker: Create transaction objects, group values by category, and save records to a file.
  • Library catalogue: Use classes, interfaces, lists, maps, searching, sorting, and exception handling.

For each project, first write the expected inputs and outputs. Divide the solution into methods, test boundary cases, and revise names after the program works. Rebuilding a project without consulting the first solution is an effective way to check understanding.

Common Java beginner errors and how to diagnose them

Java problemWhat to check
Public class name does not match the filenameSave public class Example in Example.java, including matching letter case
javac or java is not foundConfirm that a JDK is installed and its executable directory is available through the system path
Class cannot be found when running the programRun the command from the correct directory and provide the class name without the .class suffix
Text is compared with ==Use an appropriate string comparison method, such as equals, when comparing string content
Integer division gives an unexpected whole numberCheck operand types and convert an operand to a floating-point type when a fractional result is required
NullPointerException occursFind which reference is null, determine why it was not initialized, and correct the data flow rather than catching the exception indiscriminately
Loop never terminatesCheck whether the loop condition can become false and whether the controlling value changes on every relevant path

Start with the first compiler error because later diagnostics may be consequences of it. For runtime problems, reproduce the issue with a small input, read the exception type and stack trace, and inspect the first relevant line in your own source.

Java tutorial frequently asked questions

Can a complete beginner learn Java?

Yes. Begin with variables, expressions, conditions, loops, and methods before studying object-oriented design and frameworks. Type and modify examples instead of reading them only, and build small programs after each group of concepts.

What software is required to learn Java?

You need a supported JDK and a text editor or Java-compatible IDE. The JDK supplies the compiler and runtime tools. An IDE is optional for introductory programs but becomes useful for larger projects, debugging, testing, and refactoring.

What is the difference between Java and JavaScript?

Java and JavaScript are separate programming languages with different type systems, runtimes, standard libraries, and common uses. Similar names do not make their source code or execution environments interchangeable.

Should beginners learn Java from the command line or an IDE?

Compile and run a few small programs from the command line to understand source files, bytecode, class names, and the JVM. After that, an IDE can reduce repetitive work while you continue learning the underlying compilation and execution process.

What should be learned after core Java?

Learn testing, build tools, dependency management, database access, networking, concurrency, and application design. Then choose libraries and frameworks according to the intended field, such as server development, desktop software, data processing, or another Java-supported platform.

Java tutorial editorial QA checklist

  • Compile and run every Java example with a currently supported JDK, checking filenames, class names, imports, and output.
  • Confirm that Java syntax examples distinguish primitive types, reference types, objects, and arrays accurately.
  • Check that JDK, JVM, and JRE descriptions reflect modern Java packaging without assuming that every distribution supplies a separate JRE.
  • Review version-sensitive Java features and APIs, and state the required Java version when an example depends on one.
  • Verify that code blocks escape HTML-sensitive characters while preserving valid Java source when copied.
  • Ensure that exception examples handle specific failures and do not encourage empty catch blocks or suppressed diagnostics.
  • Confirm that the learning sequence covers command-line compilation before frameworks and other application-specific tools.