Loading...
Loading...
Java ek compiled + interpreted, platform-independent, object-oriented language hai.
Java Architecture:
Source code (.java) → [javac compiler] → Bytecode (.class) → [JVM] → Execution
↑ Platform independent!
"Write once, run anywhere"
JVM (Java Virtual Machine): OS-specific, runs bytecode
JRE (Java Runtime Environment): JVM + libraries
JDK (Java Development Kit): JRE + compiler + tools
// Full class with all OOP features
public class BankAccount {
// Encapsulation — private fields
private String accountNo;
private String owner;
private double balance;
private static int totalAccounts = 0; // class-level
// Constructor
public BankAccount(String accountNo, String owner, double initialBalance) {
this.accountNo = accountNo;
this.owner = owner;
this.balance = initialBalance;
totalAccounts++;
}
// Methods
public void deposit(double amount) {
if (amount > 0) balance += amount;
else throw new IllegalArgumentException("Amount must be positive");
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) throw new InsufficientFundsException(amount);
balance -= amount;
}
// Getters (no setters for immutable fields)
public double getBalance() { return balance; }
public String getAccountNo() { return accountNo; }
// Static method
public static int getTotalAccounts() { return totalAccounts; }
@Override
public String toString() {
return String.format("Account[%s, %s, ₹%.2f]", accountNo, owner, balance);
}
}
// Usage
BankAccount acc = new BankAccount("SBI001", "Alice", 10000);
acc.deposit(5000);
System.out.println(acc); // Account[SBI001, Alice, ₹15000.00]
System.out.println(BankAccount.getTotalAccounts()); // 1
// Base class
abstract class Shape {
protected String color;
public Shape(String color) { this.color = color; }
public abstract double area(); // must override
public abstract double perimeter(); // must override
public void display() {
System.out.printf("%s [color=%s, area=%.2f]%n",
getClass().getSimpleName(), color, area());
}
}
// Subclasses
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color); this.radius = radius;
}
@Override public double area() { return Math.PI * radius * radius; }
@Override public double perimeter() { return 2 * Math.PI * radius; }
}
class Rectangle extends Shape {
private double w, h;
public Rectangle(String color, double w, double h) {
super(color); this.w = w; this.h = h;
}
@Override public double area() { return w * h; }
@Override public double perimeter() { return 2 * (w + h); }
}
// Polymorphism — runtime dispatch
Shape[] shapes = { new Circle("red", 5), new Rectangle("blue", 4, 6) };
for (Shape s : shapes) {
s.display(); // each calls its OWN area() — polymorphism!
}
// Interface — multiple implementation
interface Drawable { void draw(); }
interface Resizable { void resize(double factor); }
class Square extends Shape implements Drawable, Resizable {
private double side;
public Square(String color, double side) { super(color); this.side = side; }
@Override public double area() { return side * side; }
@Override public double perimeter() { return 4 * side; }
@Override public void draw() { System.out.println("Drawing square"); }
@Override public void resize(double f) { side *= f; }
}
import java.util.*;
import java.util.stream.*;
// List
List<String> subjects = new ArrayList<>(Arrays.asList("Java", "DBMS", "CN", "SE"));
subjects.add("OS");
subjects.remove("CN");
subjects.sort(Comparator.naturalOrder());
System.out.println(subjects); // [DBMS, Java, OS, SE]
// Map — key-value pairs
Map<String, Integer> marks = new HashMap<>();
marks.put("Alice", 92); marks.put("Bob", 85); marks.put("Charlie", 90);
marks.putIfAbsent("David", 88);
marks.computeIfPresent("Alice", (k, v) -> v + 5); // Alice gets +5
// Iterate with streams
marks.entrySet().stream()
.filter(e -> e.getValue() >= 90)
.sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
.forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
// Alice: 97
// Charlie: 90
// Set — unique elements
Set<String> attended = new HashSet<>(Arrays.asList("Alice", "Bob", "Alice"));
System.out.println(attended.size()); // 2 (duplicate removed)
// Queue
Queue<String> printQueue = new LinkedList<>();
printQueue.offer("doc1.pdf");
printQueue.offer("doc2.pdf");
System.out.println(printQueue.poll()); // doc1.pdf (FIFO)
// PriorityQueue — min-heap
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.addAll(Arrays.asList(30, 10, 50, 20));
while (!pq.isEmpty()) System.out.print(pq.poll() + " "); // 10 20 30 50
// Custom exception hierarchy
public class AppException extends Exception {
private int errorCode;
public AppException(String message, int errorCode) {
super(message); this.errorCode = errorCode;
}
public int getErrorCode() { return errorCode; }
}
public class InsufficientFundsException extends AppException {
private double required;
public InsufficientFundsException(double required) {
super("Insufficient funds. Required: ₹" + required, 1001);
this.required = required;
}
public double getRequired() { return required; }
}
// Comprehensive try-catch
public void processTransaction(String file) {
try (FileReader fr = new FileReader(file); // auto-close
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
double amount = Double.parseDouble(line); // NumberFormatException
account.withdraw(amount); // InsufficientFundsException
}
} catch (InsufficientFundsException e) {
System.err.println("Error " + e.getErrorCode() + ": " + e.getMessage());
System.err.println("Required: ₹" + e.getRequired());
} catch (NumberFormatException e) {
System.err.println("Invalid amount format: " + e.getMessage());
} catch (IOException e) {
System.err.println("File error: " + e.getMessage());
} finally {
System.out.println("Transaction processing complete"); // always runs
}
}
import java.nio.file.*;
import java.io.*;
// Modern NIO.2 approach (Java 7+)
Path filePath = Paths.get("students.txt");
// Write file
List<String> lines = Arrays.asList("Alice,92", "Bob,85", "Charlie,90");
Files.write(filePath, lines, StandardOpenOption.CREATE);
// Read all lines
List<String> read = Files.readAllLines(filePath);
for (String line : read) {
String[] parts = line.split(",");
System.out.println(parts[0] + " scored " + parts[1]);
}
// Traditional BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true))) {
bw.write("New line of data");
bw.newLine();
}
// Read with Scanner
try (Scanner sc = new Scanner(new File("students.txt"))) {
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
}
// Serialize object
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("account.ser"))) {
oos.writeObject(account); // class must implement Serializable
}
// Method 1: extend Thread
class PrintTask extends Thread {
private String name;
public PrintTask(String name) { this.name = name; }
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + " - " + i);
try { Thread.sleep(100); } catch (InterruptedException e) {}
}
}
}
// Method 2: implement Runnable (preferred — allows inheritance)
class Counter implements Runnable {
private int count = 0;
@Override
public void run() {
for (int i = 0; i < 1000; i++) count++;
}
public int getCount() { return count; }
}
// Method 3: Lambda (Java 8+)
Thread t = new Thread(() -> System.out.println("Lambda thread!"));
t.start();
// Synchronization — prevent race conditions
class SafeCounter {
private int count = 0;
public synchronized void increment() { count++; } // only one thread at a time
// Or use AtomicInteger (faster)
private AtomicInteger atomicCount = new AtomicInteger(0);
public void incrementAtomic() { atomicCount.incrementAndGet(); }
}
// ExecutorService — thread pool
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
final int taskId = i;
pool.submit(() -> System.out.println("Task " + taskId + " by " + Thread.currentThread().getName()));
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
import java.sql.*;
public class StudentDAO {
private static final String URL = "jdbc:mysql://localhost:3306/bca_db";
private static final String USER = "root";
private static final String PASS = "password";
// Get connection
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASS);
}
// INSERT — use PreparedStatement to prevent SQL injection!
public void addStudent(int roll, String name, double gpa) {
String sql = "INSERT INTO students (roll_no, name, gpa) VALUES (?, ?, ?)";
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, roll);
ps.setString(2, name);
ps.setDouble(3, gpa);
int rows = ps.executeUpdate();
System.out.println(rows + " row(s) inserted");
} catch (SQLException e) {
e.printStackTrace();
}
}
// SELECT — read results
public List<String> getAllStudents() {
List<String> students = new ArrayList<>();
String sql = "SELECT * FROM students ORDER BY gpa DESC";
try (Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
students.add(rs.getInt("roll_no") + " | " +
rs.getString("name") + " | " +
rs.getDouble("gpa"));
}
} catch (SQLException e) { e.printStackTrace(); }
return students;
}
// UPDATE
public void updateGpa(int roll, double newGpa) {
String sql = "UPDATE students SET gpa = ? WHERE roll_no = ?";
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setDouble(1, newGpa);
ps.setInt(2, roll);
ps.executeUpdate();
} catch (SQLException e) { e.printStackTrace(); }
}
// Transaction
public void transfer(int from, int to, double amount) {
try (Connection conn = getConnection()) {
conn.setAutoCommit(false); // begin transaction
try {
// Debit
PreparedStatement ps1 = conn.prepareStatement(
"UPDATE accounts SET balance = balance - ? WHERE id = ?");
ps1.setDouble(1, amount); ps1.setInt(2, from);
ps1.executeUpdate();
// Credit
PreparedStatement ps2 = conn.prepareStatement(
"UPDATE accounts SET balance = balance + ? WHERE id = ?");
ps2.setDouble(1, amount); ps2.setInt(2, to);
ps2.executeUpdate();
conn.commit(); // save both or none
System.out.println("Transfer successful");
} catch (SQLException e) {
conn.rollback(); // undo on error
throw e;
}
} catch (SQLException e) { e.printStackTrace(); }
}
}
Q: Java mein String immutable kyun hai? A: String pool me caching hoti hai — same string literal ek hi object. Thread-safe automatically. Security — database URLs, passwords as strings safe. Immutability se hashCode cache hota hai — HashMap key ke liye efficient.
Q: == aur .equals() mein kya fark hai?
A: == reference comparison (same memory address?). .equals() value comparison (logically equal?). String: "abc" == "abc" → true (string pool), new String("abc") == new String("abc") → false. Always use .equals() for objects.
Q: Garbage collection kaise kaam karta hai Java mein? A: JVM automatically unreachable objects ki memory free karta hai — programmer ko free() nahi karna padta. GC algorithms: Serial, Parallel, G1 (default), ZGC. finalize() deprecated — use try-with-resources ya Cleaner.
Complete Java Programming notes for BCA Sem 4 — OOP concepts, Collections, Exception handling, File I/O, Multithreading, JDBC database connectivity with practical examples.
44 pages · 2.2 MB · Updated 2026-03-11
Encapsulation (data hiding — private fields, public getters/setters), Inheritance (extends keyword, IS-A relationship), Polymorphism (method overloading + overriding), Abstraction (abstract classes + interfaces).
ArrayList: random access fast O(1), insert/delete slow O(n) — general use, iteration. LinkedList: insert/delete head/tail O(1), random access slow O(n) — queue/deque implementation. 90% cases ArrayList better.
Checked: compile time pe handle karna mandatory — IOException, SQLException. Unchecked (Runtime): optional handle — NullPointerException, ArrayIndexOutOfBoundsException. Error: serious system errors — OutOfMemoryError.
Process: independent program execution, own memory space. Thread: process ka lightweight unit, shared memory. Java mein Thread class extend ya Runnable interface implement karo. Concurrency ke liye threads.
1. Driver load (Class.forName), 2. Connection establish (DriverManager.getConnection), 3. Statement create, 4. Query execute, 5. ResultSet process, 6. Connection close. PreparedStatement use karo SQL injection rokne ke liye.
Your feedback helps us improve notes and tutorials.