Java Programming

Java is a popular, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. It follows the "Write Once, Run Anywhere" (WORA) principle, meaning compiled Java code can run on all platforms that support Java without the need for recompilation.

This guide covers the core concepts of Java, from setup to intermediate topics, using clear explanations and practical code examples.


1. Understanding the Java Ecosystem

Before writing code, it is helpful to understand the three core components of the Java platform:

  • JDK (Java Development Kit): The software development environment used to develop Java applications. It includes the JRE and development tools (like the compiler javac and debugger).
  • JRE (Java Runtime Environment): The software package that provides the minimum requirements for executing a Java application. It includes the JVM and core libraries.
  • JVM (Java Virtual Machine): The engine that drives the Java code. It converts Java bytecode into machine-specific language.
+-------------------------------------------------------------+
| JDK (Development Tools: javac, debugger, etc.)              |
|   +-------------------------------------------------------+ |
|   | JRE (Standard Libraries, Configuration Files)         | |
|   |   +-------------------------------------------------+ | |
|   |   | JVM (Executes the bytecode on host OS)          | | |
|   |   +-------------------------------------------------+ | |
|   +-------------------------------------------------------+ |
+-------------------------------------------------------------+

2. Setting Up and Writing Your First Program

Installation Steps

1. Download and install the JDK (such as OpenJDK or Oracle JDK) for your operating system.
2. Install an Integrated Development Environment (IDE) to write your code. Popular choices include:

  • IntelliJ IDEA
  • Eclipse
  • Visual Studio Code (with Java Extension Pack)

The "Hello World" Program

Create a file named Main.java and paste the following code:

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

Compiling and Running via Terminal

1. Open your terminal or command prompt.
2. Compile the code using the Java compiler (javac):

   javac Main.java

This creates a bytecode file named Main.class.
3. Run the compiled class using the JVM (java):

   java Main

Code Explanation

  • public class Main: Defines a class named Main. In Java, every line of code must live inside a class, and the class name must match the filename.
  • public static void main(String[] args): This is the entry point of any Java program. The JVM looks for this specific method to start execution.
  • System.out.println("Hello, World!");: Prints the text inside the quotation marks to the console.

3. Variables and Data Types

Variables are containers for storing data values. Java is a statically typed language, meaning you must declare the variable type before using it.

Primitive Data Types

Java has 8 built-in primitive data types:

TypeSizeDescriptionExample
byte1 byteStores whole numbers from -128 to 127byte age = 25;
short2 bytesStores whole numbers from -32,768 to 32,767short year = 2024;
int4 bytesStores whole numbers from -2 billion to 2 billionint salary = 50000;
long8 bytesStores very large whole numbers (append 'L')long distance = 9876543210L;
float4 bytesStores fractional numbers up to 6-7 decimal digits (append 'f')float pi = 3.14f;
double8 bytesStores fractional numbers up to 15 decimal digitsdouble price = 19.99;
boolean1 bitStores true or false valuesboolean isJavaFun = true;
char2 bytesStores a single character/ASCII valuechar grade = 'A';

Non-Primitive (Reference) Data Types

These refer to objects and are created by the programmer (except for String, which is built-in but behaves as a reference type).

String greeting = "Hello, Java!";

4. Control Flow Statements

Control flow statements determine the order in which code instructions are executed.

Conditional Statements (if-else, switch)

If-Else Example:

int score = 85;

if (score >= 90) {
    System.out.println("Grade: A");
} else if (score >= 80) {
    System.out.println("Grade: B");
} else {
    System.out.println("Grade: C");
}

Switch Example:

int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Invalid day");
}

Looping Statements (for, while, do-while)

For Loop:

Used when you know exactly how many times you want to loop.

for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

While Loop:

Repeats a statement as long as a given condition is true.

int count = 0;
while (count < 3) {
    System.out.println("Count: " + count);
    count++;
}

5. Object-Oriented Programming (OOP)

Java is an Object-Oriented Programming language. Everything in Java is associated with classes and objects.

  • Class: A blueprint or template for creating objects.
  • Object: An instance of a class.

Creating a Class and Object

// Defining the Class
class Car {
    // Attributes (Fields)
    String brand;
    int year;

    // Constructor (Used to initialize objects)
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    // Method (Behavior)
    public void displayDetails() {
        System.out.println("Car Brand: " + brand + ", Year: " + year);
    }
}

// Using the Class
public class Main {
    public static void main(String[] args) {
        // Creating an Object
        Car myCar = new Car("Toyota", 2021);
        myCar.displayDetails(); // Output: Car Brand: Toyota, Year: 2021
    }
}

The Four Pillars of OOP

1. Inheritance

Inheritance allows one class (child/subclass) to inherit the fields and methods of another class (parent/superclass).

class Vehicle {
    protected String brand = "Ford";
    public void honk() {
        System.out.println("Beep, beep!");
    }
}

// Car inherits from Vehicle using the 'extends' keyword
class ElectricCar extends Vehicle {
    private int batteryCapacity = 100;
    
    public void showSpecs() {
        System.out.println("Brand: " + brand + ", Battery: " + batteryCapacity + "%");
    }
}

2. Polymorphism

Polymorphism means "many forms". It occurs when we have classes related to each other by inheritance. It allows us to perform a single action in different ways (e.g., method overriding).

class Animal {
    public void sound() {
        System.out.println("The animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("The dog barks");
    }
}

class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("The cat meows");
    }
}

3. Encapsulation

Encapsulation is the practice of hiding sensitive data from users. This is achieved by declaring class variables as private and providing access via public getter and setter methods.

class Account {
    // Private variable cannot be accessed directly outside this class
    private double balance;

    // Getter
    public double getBalance() {
        return balance;
    }

    // Setter (allows validation)
    public void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        }
    }
}

4. Abstraction

Abstraction hides implementation details and shows only the essential features of an object. It can be achieved using either abstract classes or interfaces.

// Interface defining structure
interface AnimalInterface {
    void makeNoise(); // Interface methods do not have a body
}

// Class implementing the interface
class Pig implements AnimalInterface {
    public void makeNoise() {
        System.out.println("The pig says: Wee wee");
    }
}

6. Exception Handling

Exceptions are events that disrupt the normal flow of the program. Java uses try-catch blocks to handle errors and prevent the program from crashing.

public class Main {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[10]); // This index does not exist
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Attempted to access an out-of-bounds index.");
        } finally {
            // The finally block always runs, regardless of the exception
            System.out.println("Execution of try-catch block complete.");
        }
    }
}

7. The Java Collections Framework

The Collections Framework provides interfaces and classes to handle groups of objects, acting similarly to dynamic arrays and data structures.

ArrayList (Dynamic Array)

An ArrayList can grow and shrink in size dynamically, unlike standard Java arrays which have fixed sizes.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        
        // Adding items
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Accessing items
        System.out.println(fruits.get(1)); // Output: Banana

        // Iterating through the list
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

HashMap (Key-Value Pairs)

A HashMap stores items in "key/value" pairs, useful for looking up values by a unique key.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> studentGrades = new HashMap<>();

        // Adding keys and values
        studentGrades.put("Alice", 90);
        studentGrades.put("Bob", 85);

        // Accessing values
        System.out.println("Alice's grade: " + studentGrades.get("Alice")); // Output: 90
    }
}

The guide was created in June 2026.