Loading...
Loading...
Java is a class-based, object-oriented, platform-independent programming language developed by James Gosling at Sun Microsystems in 1995.
Key Features:
Java Execution Process: Source code (.java) → javac compiler → Bytecode (.class) → JVM → Machine code
public class BankAccount {
// Instance variables (attributes)
private String accountNumber;
private double balance;
private String owner;
// Constructor
public BankAccount(String accNum, String owner, double initialBalance) {
this.accountNumber = accNum;
this.owner = owner;
this.balance = initialBalance;
}
// Methods
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.printf("Deposited ₹%.2f. New balance: ₹%.2f%n", amount, balance);
}
}
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
return true;
}
System.out.println("Insufficient funds!");
return false;
}
// Getters
public double getBalance() { return balance; }
public String getOwner() { return owner; }
@Override
public String toString() {
return String.format("Account[%s, Owner: %s, Balance: %.2f]",
accountNumber, owner, balance);
}
}
// Usage
BankAccount acc = new BankAccount("ACC001", "Rahul", 10000);
acc.deposit(5000);
acc.withdraw(2000);
System.out.println(acc); // toString()
class Animal {
protected String name;
protected String sound;
public Animal(String name, String sound) {
this.name = name;
this.sound = sound;
}
public void makeSound() {
System.out.println(name + " says " + sound);
}
}
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name, "Woof"); // Call parent constructor
this.breed = breed;
}
@Override // Method overriding
public void makeSound() {
System.out.println(name + " barks: " + sound + "!");
}
public void fetch(String item) {
System.out.println(name + " fetches " + item);
}
}
// Polymorphism
Animal[] animals = {new Dog("Tommy", "Labrador"), new Animal("Cat", "Meow")};
for (Animal a : animals) {
a.makeSound(); // Calls correct version (runtime polymorphism)
}
// Abstract class
abstract class Shape {
abstract double area(); // Must be implemented
abstract double perimeter(); // Must be implemented
void display() { // Concrete method
System.out.printf("Area: %.2f, Perimeter: %.2f%n", area(), perimeter());
}
}
// Interface
interface Drawable {
void draw(); // All abstract by default
default void print() { // Java 8+ default method
System.out.println("Printing " + this.getClass().getSimpleName());
}
}
class Circle extends Shape implements Drawable {
double radius;
Circle(double r) { this.radius = r; }
@Override public double area() { return Math.PI * radius * radius; }
@Override public double perimeter() { return 2 * Math.PI * radius; }
@Override public void draw() { System.out.println("Drawing circle"); }
}
Abstract Class vs Interface:
| Feature | Abstract Class | Interface | |---|---|---| | Inheritance | Single (extends) | Multiple (implements) | | Methods | Abstract + concrete | Abstract + default + static | | Variables | Any (instance, static) | Only public static final | | Constructor | Yes | No | | Access modifiers | Any | Public only |
Collection Hierarchy:
Collection
├── List (ordered, duplicates allowed)
│ ├── ArrayList (resizable array, O(1) access)
│ ├── LinkedList (doubly linked, O(1) insert/delete at ends)
│ └── Vector (thread-safe ArrayList)
├── Set (unique elements)
│ ├── HashSet (O(1) operations, no order)
│ ├── LinkedHashSet (insertion order maintained)
│ └── TreeSet (sorted, O(log n))
└── Queue
├── PriorityQueue (heap-based, natural ordering)
└── ArrayDeque (double-ended queue)
Map (key-value pairs, not Collection)
├── HashMap (O(1) avg, no order)
├── LinkedHashMap (insertion order)
├── TreeMap (sorted by key)
└── Hashtable (thread-safe, legacy)
// ArrayList example
List<String> names = new ArrayList<>();
names.add("Rahul");
names.add("Priya");
names.add(1, "Amit"); // Insert at index 1
names.remove("Rahul");
Collections.sort(names);
System.out.println(names.get(0));
// HashMap example
Map<String, Integer> scores = new HashMap<>();
scores.put("Maths", 95);
scores.put("Physics", 88);
scores.getOrDefault("Chemistry", 0); // Safe get
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Streams API (Java 8+)
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sumOfEvens = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum(); // 30
public class ExceptionDemo {
// Method that declares checked exception
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) throw new ArithmeticException("Cannot divide by zero!");
return a / b;
}
// Custom exception
static class InsufficientBalanceException extends Exception {
private double shortfall;
InsufficientBalanceException(double shortfall) {
super("Insufficient balance. Short by: " + shortfall);
this.shortfall = shortfall;
}
}
public static void main(String[] args) {
try {
System.out.println(divide(10, 0));
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected: " + e.getMessage());
} finally {
System.out.println("This always runs (cleanup)");
}
// Try-with-resources (auto-closes)
try (FileReader fr = new FileReader("file.txt")) {
// fr automatically closed after this block
} catch (IOException e) {
System.out.println("File error: " + e);
}
}
}
// Method 1: Extend Thread
class Counter extends Thread {
private String name;
Counter(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)
class PrintTask implements Runnable {
@Override
public void run() {
System.out.println("Thread: " + Thread.currentThread().getName());
}
}
// Usage
Counter c1 = new Counter("Thread-A");
Thread t2 = new Thread(new PrintTask());
c1.start();
t2.start();
// Synchronization (prevent race conditions)
class SyncCounter {
private int count = 0;
public synchronized void increment() { count++; } // Only one thread at a time
public synchronized int getCount() { return count; }
}
Thread States: New → Runnable → Running → Blocked/Waiting → Terminated
Thread Methods: start(), run(), sleep(), join(), wait(), notify(), interrupt()
import java.sql.*;
public class DatabaseExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/wohotech";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM students WHERE branch = ?")) {
pstmt.setString(1, "CS");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.printf("ID: %d, Name: %s, CGPA: %.2f%n",
rs.getInt("id"),
rs.getString("name"),
rs.getDouble("cgpa"));
}
} catch (SQLException e) {
System.out.println("DB Error: " + e.getMessage());
}
}
}
Q1 (2023): Explain the difference between method overloading and overriding. Overloading (compile-time polymorphism): Same method name, different parameters — same class. Overriding (runtime polymorphism): Same name and parameters — different classes (inheritance). @Override annotation recommended for clarity.
Q2 (2022): Write a Java program to implement Stack using ArrayList.
class Stack<T> {
private ArrayList<T> list = new ArrayList<>();
public void push(T item) { list.add(item); }
public T pop() { return list.remove(list.size()-1); }
public T peek() { return list.get(list.size()-1); }
public boolean isEmpty() { return list.isEmpty(); }
}
Q3 (2024): What is generics in Java and why is it useful?
Generics allow type-safe containers and methods without casting. Instead of List list = new ArrayList(); String s = (String)list.get(0); we write List<String> list = new ArrayList<>(); String s = list.get(0);. Errors caught at compile time, not runtime. Examples: List<T>, Map<K,V>, Collections.sort().
Complete Java programming notes — OOP concepts, collections framework, exception handling, multithreading, JDBC, and design patterns with solved programs.
58 pages · 2.9 MB · Updated 2026-03-11
Abstract class can have concrete methods, constructors, instance variables. Interface (Java 8+) can have default/static methods but no instance variables. A class can implement multiple interfaces but extend only one abstract class.
Checked exceptions (IOException, SQLException) must be handled at compile time using try-catch or throws. Unchecked exceptions (RuntimeException, NullPointerException) don't need to be declared — they indicate programming errors.
Web Technologies — HTML, CSS, JavaScript, Node.js Complete Notes
Web Technologies
Computer Organization & Architecture — B.Tech IT Sem 3
Computer Organization
Digital Electronics — Complete Notes IT Sem 1
Digital Electronics
Cloud Computing Notes — B.Tech IT Sem 5
Cloud Computing
Information Security Notes — B.Tech IT Sem 6
Information Security
Your feedback helps us improve notes and tutorials.