What is Java?
Java is a powerful, object-oriented programming language created by Sun Microsystems (now Oracle) in 1995. It runs on over 3 billion devices worldwide and follows the principle "Write Once, Run Anywhere" (WORA).
🖥️ JVM
Java code compiles to bytecode that runs on the Java Virtual Machine (JVM), making it platform-independent.
🏗️ Object-Oriented
Everything in Java is an object (except primitives). Supports encapsulation, inheritance, and polymorphism.
🔒 Robust & Secure
Strong memory management, exception handling, and security features make Java ideal for enterprise applications.
Basic Syntax
Every Java program starts with a class. The main method is the entry point.
public class HelloWorld { public static void main(String[] args) { // This is a comment System.out.println("Hello, World!"); // Variables int age = 25; String name = "Alice"; boolean isActive = true; // Output with concatenation System.out.println("My name is " + name + " and I am " + age); } }
Object-Oriented Programming
Java's core OOP concepts: Classes, Objects, Inheritance, Polymorphism, Encapsulation, and Abstraction.
public class Car { // Fields (attributes) private String brand; private int year; // Constructor public Car(String brand, int year) { this.brand = brand; this.year = year; } // Methods public void start() { System.out.println(brand + " is starting..."); } // Getters and Setters (encapsulation) public String getBrand() { return brand; } } // Inheritance public class ElectricCar extends Car { private int batteryCapacity; public ElectricCar(String brand, int year, int battery) { super(brand, year); this.batteryCapacity = battery; } // Method overriding (polymorphism) @Override public void start() { System.out.println("Electric car silently starts..."); } }
Variables & Data Types
Java is statically typed — every variable must have a declared type.
// Primitive types byte b = 100; short s = 1000; int i = 50000; long l = 1000000000L; float f = 3.14f; double d = 3.14159265359; char c = 'A'; boolean bool = true; // Reference types String text = "Hello Java"; int[] numbers = {1, 2, 3, 4, 5}; // Type casting double pi = 3.14; int piInt = (int) pi; // 3 (explicit casting) // var (Java 10+) - local variable type inference var message = "Inferred type";
Control Flow
Java supports standard control structures: if-else, switch, for, while, do-while.
// If-else 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 (supports strings and expressions) switch (day) { case "Monday": System.out.println("Start of week"); break; case "Friday": System.out.println("TGIF!"); break; default: System.out.println("Regular day"); } // For loop for (int i = 0; i < 5; i++) { System.out.println("Count: " + i); } // Enhanced for loop (for-each) int[] nums = {10, 20, 30}; for (int num : nums) { System.out.println(num); } // While loop int count = 3; while (count > 0) { System.out.println("Countdown: " + count); count--; }
Collections Framework
Java's Collections Framework provides powerful data structures like ArrayList, HashMap, HashSet.
import java.util.*; // ArrayList - dynamic array List<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.remove(1); System.out.println(fruits.get(0)); // Apple // HashMap - key-value pairs Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.put("Bob", 87); int aliceScore = scores.get("Alice"); // HashSet - unique elements Set<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(2); // duplicate ignored numbers.size(); // 2 // Iteration for (String fruit : fruits) { System.out.println(fruit); } // Using streams (Java 8+) fruits.stream() .filter(f -> f.startsWith("A")) .forEach(System.out::println);
Exception Handling
Java uses try-catch-finally blocks to handle exceptions gracefully.
try { int result = 10 / 0; // Throws ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero: " + e.getMessage()); } catch (Exception e) { System.out.println("General error: " + e.getMessage()); } finally { System.out.println("This always executes"); } // Try-with-resources (auto-closes resources) try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line = reader.readLine(); System.out.println(line); } catch (IOException e) { e.printStackTrace(); } // Creating custom exception class InsufficientFundsException extends Exception { public InsufficientFundsException(String message) { super(message); } }
🛠 Project: Bank Account System
Create a simple banking system with deposit, withdrawal, and balance check functionality.
public class BankAccount { private String accountNumber; private String accountHolder; private double balance; public BankAccount(String accountNumber, String accountHolder, double initialDeposit) { this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.balance = initialDeposit; } public void deposit(double amount) { if (amount > 0) { balance += amount; System.out.println("Deposited: $" + amount); } else { System.out.println("Invalid deposit amount"); } } public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException("Insufficient funds. Balance: $" + balance); } balance -= amount; System.out.println("Withdrawn: $" + amount); } public double getBalance() { return balance; } public void displayInfo() { System.out.println("Account: " + accountNumber); System.out.println("Holder: " + accountHolder); System.out.println("Balance: $" + balance); } public static void main(String[] args) { try { BankAccount account = new BankAccount("12345", "John Doe", 1000.00); account.displayInfo(); account.deposit(500); account.withdraw(200); account.withdraw(1500); // This will throw exception } catch (InsufficientFundsException e) { System.out.println("Error: " + e.getMessage()); } } }