Skip to main content

Java Fundamentals

Java is a high-level, object-oriented programming language that was released by Sun Microsystems in 1995. It has become one of the most widely used programming languages for enterprise and web applications.

Java Language Overview

Key Features

Java achieves platform independence through the Java Virtual Machine (JVM). The principle is:
  • Source code (.java) → Compiled to bytecode (.class)
  • Bytecode runs on any platform with a JVM
  • “Write Once, Run Anywhere” (WORA)
// Java code is compiled to bytecode
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Java is a pure object-oriented language supporting:
  • Encapsulation: Data hiding through access modifiers
  • Inheritance: Code reuse through class hierarchies
  • Polymorphism: Method overriding and overloading
  • Abstraction: Abstract classes and interfaces
  • Strong type checking at compile time
  • Automatic memory management through garbage collection
  • Exception handling mechanism
  • Security features like bytecode verification

Basic Syntax

Variables and Data Types

Java has 8 primitive data types:
// Integer types
byte b = 127;        // 8-bit: -128 to 127
short s = 32767;     // 16-bit: -32768 to 32767
int i = 2147483647;  // 32-bit: -2^31 to 2^31-1
long l = 9223372036854775807L; // 64-bit

// Floating-point types
float f = 3.14f;     // 32-bit IEEE 754
double d = 3.14159;  // 64-bit IEEE 754

// Character type
char c = 'A';        // 16-bit Unicode character

// Boolean type
boolean flag = true; // true or false

Control Flow Statements

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

// switch statement
switch (day) {
    case "Monday":
        System.out.println("Start of work week");
        break;
    case "Friday":
        System.out.println("End of work week");
        break;
    default:
        System.out.println("Mid week");
}

Object-Oriented Programming

Classes and Objects

public class Person {
    // Instance variables (encapsulation)
    private String name;
    private int age;
    
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Getter and Setter methods
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    // Method
    public void introduce() {
        System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
    }
}

// Usage
Person person = new Person("Alice", 25);
person.introduce();

Inheritance

Inheritance allows a class to inherit properties and methods from another class, promoting code reuse.
// Parent class
public class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void eat() {
        System.out.println(name + " is eating");
    }
}

// Child class
public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // Call parent constructor
        this.breed = breed;
    }
    
    // Method overriding
    @Override
    public void eat() {
        System.out.println(name + " the " + breed + " is eating dog food");
    }
    
    // New method
    public void bark() {
        System.out.println(name + " is barking");
    }
}

Interfaces and Abstract Classes

// Interface defines a contract
public interface Drawable {
    void draw();  // Abstract method
    
    // Default method (Java 8+)
    default void display() {
        System.out.println("Displaying drawable object");
    }
    
    // Static method (Java 8+)
    static void info() {
        System.out.println("This is a Drawable interface");
    }
}

// Implementation
public class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Exception Handling

Proper exception handling is crucial for building robust applications.
public class ExceptionExample {
    public static void main(String[] args) {
        try {
            // Code that might throw an exception
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Handle specific exception
            System.out.println("Error: Cannot divide by zero");
        } catch (Exception e) {
            // Handle any other exception
            System.out.println("An error occurred: " + e.getMessage());
        } finally {
            // Always executed
            System.out.println("Execution completed");
        }
    }
    
    public static int divide(int a, int b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return a / b;
    }
}

Collections Framework

Common Collection Types

List

Ordered collection that allows duplicates
  • ArrayList (resizable array)
  • LinkedList (doubly-linked list)

Set

Unordered collection with no duplicates
  • HashSet (hash table)
  • TreeSet (sorted set)

Map

Key-value pairs
  • HashMap (hash table)
  • TreeMap (sorted map)

Queue

FIFO data structure
  • LinkedList
  • PriorityQueue
import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // List example
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("JavaScript");
        
        // Set example
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(2);  // Duplicate, will not be added
        
        // Map example
        Map<String, Integer> map = new HashMap<>();
        map.put("Alice", 25);
        map.put("Bob", 30);
        
        // Iteration
        for (String item : list) {
            System.out.println(item);
        }
        
        // Lambda with streams (Java 8+)
        list.stream()
            .filter(s -> s.startsWith("J"))
            .forEach(System.out::println);
    }
}

Best Practices

1

Follow Naming Conventions

  • Classes: PascalCase (e.g., UserService)
  • Methods and variables: camelCase (e.g., getUserName)
  • Constants: UPPER_SNAKE_CASE (e.g., MAX_SIZE)
2

Use Proper Access Modifiers

  • Keep instance variables private
  • Use getters and setters for access
  • Make classes and methods public only when necessary
3

Handle Exceptions Properly

  • Catch specific exceptions
  • Don’t swallow exceptions silently
  • Use try-with-resources for resource management
4

Write Clean Code

  • Keep methods short and focused
  • Use meaningful variable names
  • Add comments for complex logic
  • Follow SOLID principles

Further Reading

JVM Internals

Learn about Java Virtual Machine architecture

Concurrency

Master multithreading in Java

Spring Framework

Explore enterprise Java development

Build docs developers (and LLMs) love