Introduction to Java

Java is a robust, object-oriented programming language designed for platform independence. "Write once, run anywhere" (WORA) is Java's key principle.

Java Features

  • Platform Independent: Runs on any OS with JVM
  • Object-Oriented: Everything is an object
  • Secure: Built-in security features
  • Robust: Strong memory management
  • Multithreaded: Concurrent programming support
  • High Performance: Compiled to bytecode
  • Large Ecosystem: Extensive libraries
  • Enterprise Ready: Used in large applications

Setup & Installation

Installing Java Development Kit (JDK)

# Download JDK from Oracle or OpenJDK
# Install JDK on your system

# Verify installation
java -version
javac -version

# Set JAVA_HOME environment variable
# Windows: set JAVA_HOME=C:\Program Files\Java\jdk-17
# Linux/Mac: export JAVA_HOME=/usr/lib/jvm/java-17-openjdk

First Java Program

// HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.println("Welcome to Java Programming!");
    }
}

// Compile and run
// javac HelloWorld.java
// java HelloWorld

Java Basics

Variables and Data Types

public class DataTypes {
    public static void main(String[] args) {
        // Primitive data types
        int age = 25;
        double salary = 50000.50;
        char grade = 'A';
        boolean isActive = true;
        
        // String (Reference type)
        String name = "John Doe";
        
        // Constants
        final double PI = 3.14159;
        
        // Type casting
        int number = (int) salary;  // Explicit casting
        double decimal = age;       // Implicit casting
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Control Structures

public class ControlStructures {
    public static void main(String[] args) {
        int score = 85;
        
        // 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
        char grade = 'B';
        switch (grade) {
            case 'A':
                System.out.println("Excellent!");
                break;
            case 'B':
                System.out.println("Good!");
                break;
            default:
                System.out.println("Keep trying!");
        }
        
        // Loops
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);
        }
        
        int j = 1;
        while (j <= 3) {
            System.out.println("While: " + j);
            j++;
        }
    }
}

Object-Oriented Programming

Classes and Objects

// Student.java
public class Student {
    // Instance variables
    private String name;
    private int age;
    private double gpa;
    
    // Constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        this.gpa = 0.0;
    }
    
    // Getter methods
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    // Setter methods
    public void setGpa(double gpa) {
        if (gpa >= 0.0 && gpa <= 4.0) {
            this.gpa = gpa;
        }
    }
    
    // Instance method
    public void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
    }
    
    // Static method
    public static void printSchoolInfo() {
        System.out.println("SD Technology Institute");
    }
}

Inheritance

// Parent class
class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void eat() {
        System.out.println(name + " is eating");
    }
}

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

// Usage
public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy", "Golden Retriever");
        dog.eat();   // Overridden method
        dog.bark();  // Dog-specific method
    }
}

Collections Framework

Lists, Sets, and Maps

import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // ArrayList
        List names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        System.out.println("Names: " + names);
        
        // HashSet (no duplicates)
        Set numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(2);  // Duplicate, won't be added
        System.out.println("Numbers: " + numbers);
        
        // HashMap
        Map ages = new HashMap<>();
        ages.put("Alice", 25);
        ages.put("Bob", 30);
        ages.put("Charlie", 28);
        
        // Iterate through map
        for (Map.Entry entry : ages.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        
        // Using streams (Java 8+)
        names.stream()
             .filter(name -> name.startsWith("A"))
             .forEach(System.out::println);
    }
}

Exception Handling

import java.io.*;

public class ExceptionHandling {
    public static void main(String[] args) {
        // Try-catch block
        try {
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        }
        
        // Multiple catch blocks
        try {
            int[] array = {1, 2, 3};
            System.out.println(array[5]);  // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds");
        } catch (Exception e) {
            System.out.println("General exception: " + e.getMessage());
        } finally {
            System.out.println("Finally block always executes");
        }
        
        // Try-with-resources (automatic resource management)
        try (FileReader file = new FileReader("data.txt");
             BufferedReader reader = new BufferedReader(file)) {
            String line = reader.readLine();
            System.out.println(line);
        } catch (IOException e) {
            System.out.println("File operation failed: " + e.getMessage());
        }
    }
    
    // Custom exception
    static class CustomException extends Exception {
        public CustomException(String message) {
            super(message);
        }
    }
    
    public static void validateAge(int age) throws CustomException {
        if (age < 0) {
            throw new CustomException("Age cannot be negative");
        }
    }
}

Multithreading

// Method 1: Extending Thread class
class MyThread extends Thread {
    private String threadName;
    
    public MyThread(String name) {
        this.threadName = name;
    }
    
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(threadName + ": " + i);
            try {
                Thread.sleep(1000);  // Sleep for 1 second
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted");
            }
        }
    }
}

// Method 2: Implementing Runnable interface
class MyRunnable implements Runnable {
    private String threadName;
    
    public MyRunnable(String name) {
        this.threadName = name;
    }
    
    @Override
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println(threadName + " - Count: " + i);
        }
    }
}

public class MultithreadingDemo {
    public static void main(String[] args) {
        // Using Thread class
        MyThread thread1 = new MyThread("Thread-1");
        MyThread thread2 = new MyThread("Thread-2");
        
        thread1.start();
        thread2.start();
        
        // Using Runnable interface
        Thread thread3 = new Thread(new MyRunnable("Runnable-1"));
        Thread thread4 = new Thread(new MyRunnable("Runnable-2"));
        
        thread3.start();
        thread4.start();
        
        // Using lambda expression (Java 8+)
        Thread thread5 = new Thread(() -> {
            System.out.println("Lambda thread: " + Thread.currentThread().getName());
        });
        thread5.start();
    }
}

Spring Framework Basics

Spring Boot Application

// Main Application Class
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// REST Controller
@RestController
@RequestMapping("/api")
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    @GetMapping("/students")
    public List getAllStudents() {
        return studentService.getAllStudents();
    }
    
    @PostMapping("/students")
    public Student createStudent(@RequestBody Student student) {
        return studentService.saveStudent(student);
    }
    
    @GetMapping("/students/{id}")
    public Student getStudent(@PathVariable Long id) {
        return studentService.getStudentById(id);
    }
}

// Service Layer
@Service
public class StudentService {
    
    @Autowired
    private StudentRepository studentRepository;
    
    public List getAllStudents() {
        return studentRepository.findAll();
    }
    
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }
    
    public Student getStudentById(Long id) {
        return studentRepository.findById(id).orElse(null);
    }
}

// JPA Entity
@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "name")
    private String name;
    
    @Column(name = "email")
    private String email;
    
    // Constructors, getters, setters
}

Practice Projects

Beginner Projects
  1. Calculator Application
  2. Student Management System
  3. Banking System (Console)
  4. Library Management
  5. Tic-Tac-Toe Game
Advanced Projects
  1. E-commerce REST API
  2. Chat Application
  3. File Upload System
  4. Task Management API
  5. Microservices Architecture

Master Java Development

Ready to become a Java expert? Join our comprehensive Java course with enterprise projects, Spring framework, and placement assistance.

View Java Course Back to Tutorials