Home
Education
D/L Mode
HTML CSS JavaScript Python SQL Node.js PHP Java C++

Welcome to JAVA

Start your journey in object oriented programming

Lessons

Start learning step by step

Question & Answer

Check your understanding

Interview Asked Questions

Prepare for real interviews

Quiz

Test your skills

☕ Java Lesson 1: Introduction to Java

Java is a high-level, object-oriented programming language used for building applications, web apps, Android apps, games, and more. It's platform-independent thanks to the JVM (Java Virtual Machine).

// Print your first message in Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
    

☕ Java Lesson 2: Variables and Data Types

Variables store data. Java has different data types like int, double, boolean, and String.

// Variables in Java
int age = 25;
double price = 19.99;
boolean isJavaFun = true;
String name = "Zohil";

System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Learning Java is fun: " + isJavaFun);
System.out.println("Name: " + name);
    

☕ Java Lesson 3: Operators

Operators are used to perform operations on variables and values. Common types: arithmetic, relational, and logical operators.

// Arithmetic Operators
int a = 10;
int b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));

// Relational Operators
System.out.println(a > b);  // true
System.out.println(a == b); // false

// Logical Operators
System.out.println(a > 5 && b < 10); // true
System.out.println(a < 5 || b < 10); // true
    

☕ Java Lesson 4: Conditional Statements

Use if, else if, and else to make decisions in your program.

int number = 20;

if(number > 0) {
    System.out.println("Positive number");
} else if(number < 0) {
    System.out.println("Negative number");
} else {
    System.out.println("Zero");
}
    

☕ Java Lesson 5: Loops

Loops let you repeat actions. Java supports for, while, and do-while loops.

// For loop
for(int i = 1; i <= 5; i++) {
    System.out.println("For loop iteration: " + i);
}

// While loop
int j = 1;
while(j <= 5) {
    System.out.println("While loop iteration: " + j);
    j++;
}

// Do-while loop
int k = 1;
do {
    System.out.println("Do-while loop iteration: " + k);
    k++;
} while(k <= 5);
    

☕ Java Lesson 6: Arrays

Arrays store multiple values of the same type in a single variable.

// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};

// Access elements
System.out.println("First element: " + numbers[0]);
System.out.println("Third element: " + numbers[2]);

// Loop through array
for(int i = 0; i < numbers.length; i++) {
    System.out.println("Array element: " + numbers[i]);
}
    

☕ Java Lesson 7: Methods

Methods are blocks of code that perform a task and can be reused.

// Method example
public class Main {
    public static void main(String[] args) {
        greet("Zohil");
        int sum = addNumbers(5, 10);
        System.out.println("Sum: " + sum);
    }

    // Method to greet
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Method to add numbers
    public static int addNumbers(int a, int b) {
        return a + b;
    }
}
    

☕ Java Lesson 8: Strings

Strings store sequences of characters. Java has many built-in methods to manipulate strings.

String text = "Hello, Java!";

// String length
System.out.println("Length: " + text.length());

// Convert to uppercase
System.out.println(text.toUpperCase());

// Substring
System.out.println(text.substring(7, 11)); // Java

// Replace
System.out.println(text.replace("Java", "World"));
    

☕ Java Lesson 9: User Input

You can take input from the user using the Scanner class.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = input.nextLine();

        System.out.print("Enter your age: ");
        int age = input.nextInt();

        System.out.println("Name: " + name + ", Age: " + age);
    }
}
    

☕ Java Lesson 10: Switch Statement

Use switch for multiple conditional branches instead of multiple if-else statements.

int day = 3;
String dayName;

switch(day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    default:
        dayName = "Weekend";
}
System.out.println("Day: " + dayName);
    

☕ Java Lesson 11: Classes and Objects

Classes are blueprints for objects. Objects are instances of classes.

// Define a class
public class Car {
    String color;
    String model;
}

// Create objects
public class Main {
    public static void main(String[] args) {
        Car car1 = new Car();
        car1.color = "Red";
        car1.model = "Toyota";

        Car car2 = new Car();
        car2.color = "Blue";
        car2.model = "Honda";

        System.out.println("Car1: " + car1.model + ", " + car1.color);
        System.out.println("Car2: " + car2.model + ", " + car2.color);
    }
}
    

☕ Java Lesson 12: Constructors

Constructors initialize objects when they are created. They have the same name as the class.

public class Car {
    String model;
    String color;

    // Constructor
    public Car(String model, String color) {
        this.model = model;
        this.color = color;
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car("Toyota", "Red");
        Car car2 = new Car("Honda", "Blue");

        System.out.println("Car1: " + car1.model + ", " + car1.color);
        System.out.println("Car2: " + car2.model + ", " + car2.color);
    }
}
    

☕ Java Lesson 13: Methods in Classes

Classes can have methods that define actions the object can perform.

public class Car {
    String model;
    String color;

    public Car(String model, String color) {
        this.model = model;
        this.color = color;
    }

    // Method
    public void drive() {
        System.out.println(model + " is driving");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car("Toyota", "Red");
        car.drive(); // Call method
    }
}
    

☕ Java Lesson 14: Encapsulation

Encapsulation hides the internal state of an object and allows access only through methods (getters and setters).

public class Person {
    private String name;
    private int age;

    // Getter
    public String getName() {
        return name;
    }

    // Setter
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Zohil");
        p.setAge(25);
        System.out.println("Name: " + p.getName() + ", Age: " + p.getAge());
    }
}
    

☕ Java Lesson 15: Static Members

Static variables and methods belong to the class instead of instances. They can be accessed without creating an object.

public class Counter {
    public static int count = 0;

    public static void increment() {
        count++;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter.increment();
        Counter.increment();
        System.out.println("Count: " + Counter.count);
    }
}
    

☕ Java Lesson 16: Inheritance

Inheritance allows a class to inherit fields and methods from another class using extends.

class Vehicle {
    void start() {
        System.out.println("Vehicle starting...");
    }
}

class Car extends Vehicle {
    void drive() {
        System.out.println("Car is driving...");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start(); // Inherited method
        car.drive();
    }
}
    

☕ Java Lesson 17: Method Overriding

Child classes can override parent class methods to provide their own implementation.

class Animal {
    void sound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound(); // Outputs "Bark" due to overriding
    }
}
    

☕ Java Lesson 18: Polymorphism

Polymorphism allows objects to be treated as instances of their parent class, enabling flexibility in code.

class Shape {
    void draw() {
        System.out.println("Drawing shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing circle");
    }
}

class Square extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing square");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape s1 = new Circle();
        Shape s2 = new Square();

        s1.draw(); // Drawing circle
        s2.draw(); // Drawing square
    }
}
    

☕ Java Lesson 19: Abstract Classes

Abstract classes cannot be instantiated. They can have abstract methods (without body) that must be implemented by child classes.

abstract class Animal {
    abstract void sound(); // Abstract method

    void eat() { // Regular method
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.sound();
        dog.eat();
    }
}
    

☕ Java Lesson 20: Interfaces

Interfaces define methods without implementation. Classes implement interfaces to provide the actual behavior.

interface Vehicle {
    void start();
    void stop();
}

class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car starting...");
    }

    @Override
    public void stop() {
        System.out.println("Car stopping...");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle myCar = new Car();
        myCar.start();
        myCar.stop();
    }
}
    

☕ Java Lesson 21: Exception Handling

Exceptions are runtime errors. You can handle them using try, catch, and finally blocks.

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
        } finally {
            System.out.println("This block always executes.");
        }
    }
}
    

☕ Java Lesson 22: Throw and Throws

You can throw exceptions manually using throw and declare exceptions using throws.

class Main {
    static void checkAge(int age) throws Exception {
        if(age < 18) {
            throw new Exception("Age must be at least 18.");
        } else {
            System.out.println("Access granted!");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
    

☕ Java Lesson 23: File I/O

Java can read from and write to files using classes like File, Scanner, and FileWriter.

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            // Write to a file
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, Java File I/O!");
            writer.close();

            // Read from a file
            File file = new File("example.txt");
            Scanner reader = new Scanner(file);
            while(reader.hasNextLine()) {
                String line = reader.nextLine();
                System.out.println(line);
            }
            reader.close();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
    

☕ Java Lesson 24: Packages

Packages organize classes into namespaces. Use package and import to structure code.

// File: vehicles/Car.java
package vehicles;

public class Car {
    public void info() {
        System.out.println("This is a car.");
    }
}

// File: Main.java
import vehicles.Car;

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.info();
    }
}
    

☕ Java Lesson 25: Nested and Inner Classes

Classes can be defined inside other classes. Inner classes have access to the outer class members.

public class Outer {
    private String message = "Hello from Outer";

    class Inner {
        void showMessage() {
            System.out.println(message);
        }
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.showMessage();
    }
}
    

☕ Java Lesson 26: ArrayList

ArrayList is a resizable array from the java.util package.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList fruits = new ArrayList<>();

        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        // Access elements
        System.out.println("First fruit: " + fruits.get(0));

        // Loop through ArrayList
        for(String fruit : fruits) {
            System.out.println(fruit);
        }

        // Remove element
        fruits.remove("Banana");
        System.out.println("After removal: " + fruits);
    }
}
    

☕ Java Lesson 27: HashMap

HashMap stores key-value pairs and allows fast access.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap scores = new HashMap<>();

        // Add key-value pairs
        scores.put("Alice", 90);
        scores.put("Bob", 85);
        scores.put("Charlie", 95);

        // Access value
        System.out.println("Alice's score: " + scores.get("Alice"));

        // Loop through keys
        for(String name : scores.keySet()) {
            System.out.println(name + ": " + scores.get(name));
        }

        // Remove a key
        scores.remove("Bob");
        System.out.println("After removal: " + scores);
    }
}
    

☕ Java Lesson 28: Generics

Generics allow you to create classes, interfaces, and methods with type parameters for type safety.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        for(int num : numbers) {
            System.out.println(num);
        }
    }
}
    

☕ Java Lesson 29: Wrapper Classes

Wrapper classes allow primitive types to be used as objects.

public class Main {
    public static void main(String[] args) {
        int a = 10;
        Integer b = Integer.valueOf(a); // Wrap int to Integer
        int c = b.intValue();           // Unwrap back to int

        System.out.println("Wrapped: " + b);
        System.out.println("Unwrapped: " + c);

        // Auto-boxing and Auto-unboxing
        Integer x = a; // auto-box
        int y = x;     // auto-unbox
        System.out.println("Auto-box: " + x + ", Auto-unbox: " + y);
    }
}
    

☕ Java Lesson 30: Lambda Expressions

Lambda expressions provide a concise way to represent anonymous methods (introduced in Java 8).

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Using lambda to print each element
        names.forEach(name -> System.out.println(name));

        // Lambda with condition
        names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);
    }
}
    

☕ Java Lesson 31: Advanced File Handling

Java can handle files with BufferedReader, BufferedWriter, and FileReader/FileWriter for efficient reading/writing.

import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            // Write using BufferedWriter
            BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"));
            writer.write("Hello, Java File Handling!\n");
            writer.write("BufferedWriter makes writing efficient.");
            writer.close();

            // Read using BufferedReader
            BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

☕ Java Lesson 32: Introduction to Threads

Threads allow concurrent execution. You can create threads by extending Thread or implementing Runnable.

class MyThread extends Thread {
    public void run() {
        for(int i=1; i<=5; i++) {
            System.out.println("Thread running: " + i);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start(); // Start thread
    }
}
    

☕ Java Lesson 33: Runnable Interface

Implement Runnable for multithreading without extending Thread class.

class MyRunnable implements Runnable {
    public void run() {
        for(int i=1; i<=5; i++) {
            System.out.println("Runnable thread: " + i);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}
    

☕ Java Lesson 34: Thread Synchronization

Synchronization prevents race conditions by allowing only one thread to access a block/method at a time.

class Counter {
    private int count = 0;

    // synchronized method
    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for(int i=0; i<1000; i++) counter.increment();
        });

        Thread t2 = new Thread(() -> {
            for(int i=0; i<1000; i++) counter.increment();
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Final count: " + counter.getCount());
    }
}
    

☕ Java Lesson 35: Thread Communication

Threads can communicate using wait(), notify(), and notifyAll().

class Shared {
    int data;
    boolean ready = false;

    public synchronized void produce(int value) {
        data = value;
        ready = true;
        notify(); // Notify waiting thread
    }

    public synchronized int consume() throws InterruptedException {
        while(!ready) wait(); // Wait until data is ready
        ready = false;
        return data;
    }
}

public class Main {
    public static void main(String[] args) {
        Shared shared = new Shared();

        Thread producer = new Thread(() -> {
            for(int i=1; i<=5; i++) {
                shared.produce(i);
                System.out.println("Produced: " + i);
            }
        });

        Thread consumer = new Thread(() -> {
            for(int i=1; i<=5; i++) {
                try {
                    int val = shared.consume();
                    System.out.println("Consumed: " + val);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
    

☕ Java Lesson 36: Networking Basics

Java provides java.net package to work with networking, like sockets and URLs.

import java.net.*;

public class Main {
    public static void main(String[] args) {
        try {
            // URL example
            URL url = new URL("https://www.example.com");
            System.out.println("Protocol: " + url.getProtocol());
            System.out.println("Host: " + url.getHost());
            System.out.println("File: " + url.getFile());
        } catch (MalformedURLException e) {
            System.out.println("Invalid URL");
        }
    }
}
    

☕ Java Lesson 37: Socket Programming

Sockets allow communication between client and server over the network.

import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(5000);
            System.out.println("Server started, waiting for client...");
            Socket socket = server.accept(); // accept client connection
            System.out.println("Client connected");

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = in.readLine();
            System.out.println("Client says: " + message);

            server.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

☕ Java Lesson 38: JDBC (Database Connectivity)

JDBC allows Java to connect to databases like MySQL or SQLite.

import java.sql.*;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/testdb";
        String user = "root";
        String password = "password";

        try {
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();

            // Create table
            stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users(id INT PRIMARY KEY, name VARCHAR(50))");

            // Insert data
            stmt.executeUpdate("INSERT INTO users VALUES(1, 'Zohil')");

            // Query data
            ResultSet rs = stmt.executeQuery("SELECT * FROM users");
            while(rs.next()) {
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }

            conn.close();
        } catch (SQLException e) {
            System.out.println("Database error: " + e.getMessage());
        }
    }
}
    

☕ Java Lesson 39: JavaFX Basics

JavaFX is used to create graphical user interfaces (GUI) in Java.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button("Click Me!");
        btn.setOnAction(e -> System.out.println("Button clicked!"));

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 200);
        primaryStage.setTitle("JavaFX Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
    

☕ Java Lesson 40: Final Project Idea

Build a complete project to practice everything you learned in Java:

Project: Student Management System

Features:
- Add, update, delete, and view students (OOP + ArrayList/HashMap)
- Save data to a file or database (File I/O or JDBC)
- GUI with JavaFX
- Exception handling and validation
- Multithreading for background tasks
- Optional: Network feature to sync students across systems

This project will combine all major concepts: OOP, Collections, File/DB, GUI, Threads, and Networking.
    
🎉 Congratulations! You have completed all JAVA lessons!
Keep practicing and building amazing Applications!

💡JAVA Questions & Answers

❓ What is Java?
Java is a high-level, class-based, object-oriented programming language that is designed to be platform-independent. Java applications are compiled into bytecode and run on the Java Virtual Machine (JVM), allowing them to work on any platform with a JVM.
❓ What are the key features of Java?
Java features include: platform independence (via JVM), object-oriented programming, robustness, security, multithreading support, automatic memory management (garbage collection), and high performance.
❓ What is the difference between JDK, JRE, and JVM?
- JVM (Java Virtual Machine): Runs Java bytecode on any platform.
- JRE (Java Runtime Environment): Includes JVM and libraries required to run Java programs.
- JDK (Java Development Kit): Includes JRE plus development tools like compiler (`javac`) to write and compile Java programs.
❓ What is the difference between `==` and `.equals()` in Java?
`==` compares reference equality (whether two objects point to the same memory location). `.equals()` compares logical equality (whether two objects have the same content), and can be overridden in classes.
❓ What is the difference between an abstract class and an interface?
- Abstract class: Can have abstract methods and concrete methods; supports constructors and state (fields); single inheritance.
- Interface: Can have abstract methods and default/static methods; no constructors; multiple inheritance is possible.
❓ What is the difference between `ArrayList` and `LinkedList` in Java?
`ArrayList` is backed by a dynamic array, allowing fast random access but slower insertions/deletions in the middle.
`LinkedList` is a doubly linked list, allowing fast insertions/deletions but slower random access.
❓ What is the difference between `HashMap` and `Hashtable`?
`HashMap` is non-synchronized and allows null keys and values.
`Hashtable` is synchronized (thread-safe) and does not allow null keys or values.
❓ What is multithreading in Java?
Multithreading is the concurrent execution of two or more threads to maximize CPU utilization. Threads share memory but execute independently, improving performance in multitasking programs.
❓ What is the difference between `checked` and `unchecked` exceptions?
Checked exceptions are checked at compile-time and must be handled using `try-catch` or `throws`.
Unchecked exceptions (RuntimeExceptions) occur at runtime and do not need mandatory handling.
❓ What is the difference between `final`, `finally`, and `finalize` in Java?
- `final`: Keyword used to declare constants, prevent method overriding, and inheritance of classes.
- `finally`: Block that always executes after `try-catch`, used for cleanup.
- `finalize()`: Method called by garbage collector before object destruction for cleanup.
❓ What is the difference between `==` and `equals()` for Strings in Java?
`==` checks if two String references point to the same object (reference equality).
`equals()` checks if two Strings have the same sequence of characters (content equality).
❓ What is the difference between `String`, `StringBuilder`, and `StringBuffer`?
- `String`: Immutable sequence of characters.
- `StringBuilder`: Mutable, faster, not synchronized, used in single-threaded programs.
- `StringBuffer`: Mutable, synchronized, thread-safe, used in multi-threaded programs.
❓ What is the difference between `abstract class` and `concrete class`?
Abstract class contains at least one abstract method and cannot be instantiated directly.
Concrete class has all implemented methods and can be instantiated to create objects.
❓ What is the difference between `interface` and `abstract class` in Java 8?
In Java 8, interfaces can have default and static methods, but cannot have instance variables or constructors.
Abstract classes can have instance variables, constructors, and both abstract and concrete methods. Classes can implement multiple interfaces but extend only one abstract class.
❓ What is Java Garbage Collection and how does it work?
Garbage collection is the process of automatically freeing memory by removing objects that are no longer referenced. The JVM uses algorithms like Mark-and-Sweep, Generational GC, and Reference Counting to manage memory.
❓ What is the difference between `overloading` and `overriding` in Java?
- Overloading: Same method name with different parameter lists in the same class (compile-time polymorphism).
- Overriding: Subclass provides a new implementation for a method already defined in the superclass (runtime polymorphism).
❓ What is the difference between `throw` and `throws`?
- `throw` is used to explicitly throw an exception within a method.
- `throws` is used in a method signature to declare the exceptions that the method might throw.
❓ What is the difference between `static` and `non-static` methods in Java?
Static methods belong to the class and can be called without creating an object.
Non-static methods belong to an instance of the class and require an object to be called.
❓ What is the difference between `Array` and `ArrayList` in Java?
- Array: Fixed size, can hold primitive types and objects, less flexible.
- ArrayList: Dynamic size, holds only objects, more flexible with methods like add(), remove(), and contains().
❓ What is the difference between `HashMap`, `HashSet`, and `Hashtable`?
- `HashMap`: Key-value pairs, non-synchronized, allows null keys and values.
- `HashSet`: Stores unique elements, backed by a HashMap internally, no duplicates.
- `Hashtable`: Synchronized (thread-safe), key-value pairs, does not allow null keys or values.
❓ What is the difference between `==` and `equals()` for objects in Java?
`==` checks reference equality (if two references point to the same object).
`equals()` checks logical equality (if two objects have the same content), and can be overridden in classes.
❓ What is the difference between `final`, `finally`, and `finalize()` in Java?
- `final`: Keyword to declare constants, prevent method overriding, or inheritance of classes.
- `finally`: Block that always executes after `try-catch`, used for cleanup.
- `finalize()`: Method called by garbage collector before object destruction.
❓ What is the difference between `Checked` and `Unchecked` exceptions in Java?
- Checked exceptions: Checked at compile-time and must be handled using `try-catch` or `throws`.
- Unchecked exceptions (RuntimeExceptions): Occur at runtime and do not require mandatory handling.
❓ What is the difference between `abstract class` and `interface` in Java?
Abstract classes can have both abstract and concrete methods, instance variables, and constructors.
Interfaces can have abstract methods, default/static methods, but cannot have instance variables or constructors. Java supports multiple interfaces but only single inheritance for classes.
❓ What is the difference between `stack` and `heap` memory in Java?
- Stack: Stores method calls and local variables; memory is managed automatically; fast access; memory is freed when method exits.
- Heap: Stores objects and instance variables; garbage collector manages memory; slower access; shared across threads.
❓ What is the difference between `public`, `private`, `protected`, and default access modifiers in Java?
- `public`: Accessible from any class.
- `private`: Accessible only within the same class.
- `protected`: Accessible within the same package and subclasses.
- Default (no modifier): Accessible only within the same package.
❓ What is the difference between `synchronized` method and block in Java?
- Synchronized method: Locks the whole method, ensuring only one thread can access it at a time.
- Synchronized block: Locks only the specific block of code, improving performance by reducing unnecessary locking.
❓ What is the difference between `==` and `equalsIgnoreCase()` in Java Strings?
`==` checks reference equality (same object), while `equalsIgnoreCase()` compares the content of two Strings ignoring case sensitivity.
❓ What is the difference between `Iterator` and `ListIterator` in Java?
- `Iterator`: Can traverse collections in one direction, supports `remove()`.
- `ListIterator`: Works only on lists, can traverse forward and backward, supports `add()`, `remove()`, and `set()` methods.
❓ What are Java Generics and why are they used?
Generics enable classes, interfaces, and methods to operate on types specified by the programmer, providing type safety at compile-time. They eliminate the need for casting and reduce runtime errors.

🎯 JAVA Interview Questions

❓ What is Java?
Java is a high-level, class-based, object-oriented programming language designed to be platform-independent. Java code is compiled into bytecode and run on the Java Virtual Machine (JVM), making it portable across platforms.
❓ What are the key features of Java?
Key features include platform independence, object-oriented programming, robustness, security, multithreading support, automatic memory management (garbage collection), and high performance.
❓ What is the difference between JDK, JRE, and JVM?
JVM (Java Virtual Machine) runs Java bytecode on any platform. JRE (Java Runtime Environment) includes JVM and libraries required to run Java programs. JDK (Java Development Kit) includes JRE plus development tools like the compiler.
❓ What is the difference between `==` and `.equals()` in Java?
`==` checks reference equality (if two references point to the same object). `.equals()` checks logical equality (if two objects have the same content), and it can be overridden in classes.
❓ What is the difference between an abstract class and an interface?
Abstract classes can have abstract and concrete methods, instance variables, and constructors; a class can extend only one abstract class. Interfaces can have abstract, default, and static methods; a class can implement multiple interfaces.
❓ What is the difference between `ArrayList` and `LinkedList`?
`ArrayList` is backed by a dynamic array, allowing fast random access but slower insertions/deletions in the middle. `LinkedList` is a doubly linked list, allowing fast insertions/deletions but slower random access.
❓ What is the difference between `HashMap` and `Hashtable`?
`HashMap` is non-synchronized and allows null keys/values. `Hashtable` is synchronized (thread-safe) and does not allow null keys or values.
❓ What is multithreading in Java?
Multithreading is the concurrent execution of two or more threads to maximize CPU utilization. Threads share memory but execute independently, improving performance in multitasking programs.
❓ What is the difference between `checked` and `unchecked` exceptions?
Checked exceptions are checked at compile-time and must be handled using `try-catch` or `throws`. Unchecked exceptions (RuntimeExceptions) occur at runtime and do not require mandatory handling.
❓ What is Java Garbage Collection and how does it work?
Garbage collection automatically frees memory by removing objects that are no longer referenced. JVM uses algorithms like Mark-and-Sweep and Generational GC to manage memory efficiently.

📝 Java Quiz: Test Your Knowledge

1. What is Java primarily used for?

2. Which keyword is used to define a class in Java?

3. Which method is the entry point for a Java program?

4. Which keyword is used for inheritance in Java?

5. Which of these is a valid Java data type?

6. Which operator is used for comparison in Java?

7. Which keyword is used to prevent a class from being inherited?

8. Which method is used to get the length of a string in Java?

9. Which exception is thrown when dividing by zero?

10. Which keyword is used to declare an interface?

11. What is the default value of a boolean in Java?

12. Which loop is guaranteed to execute at least once?

13. Which package is automatically imported in every Java program?

14. Which operator is used for logical AND in Java?

×