Coding Questions Questions

Question Bank › Technical › Java › Coding Questions

12345

Anonymous Inner Classes

Q1.Easy
Write a Java program demonstrating an anonymous inner class that extends a class. Define an abstract class Vehicle with an abstract method run(). In main(), create an anonymous inner class extending Vehicle that implements run() to print "bus is moving", assign it to a Vehicle reference v, and call v.run().
Show answer & explanation
Answer:
abstract class Vehicle {
    abstract void run();
}

class TestAnonymousInner {
    public static void main(String[] args) {
        Vehicle v = new Vehicle() {
            void run() {
                System.out.println("bus is moving");
            }
        };
        v.run();
    }
}
Explanation: 1. Vehicle is an abstract class with abstract method run(). 2. 'new Vehicle(){ void run(){...} }' defines an anonymous inner class extending Vehicle and overriding run(). 3. The compiler generates a hidden subclass providing the run() implementation. 4. An object of that subclass is assigned to the Vehicle reference 'v'. 5. Calling v.run() prints "bus is moving".
Q2.Easy
Write a Java program that shows a Java anonymous inner class example using an interface. Define an interface Speaker with a method void speak(). In main, create a Speaker using an anonymous inner class whose speak() prints "hello bharat", then invoke speak().
Show answer & explanation
Answer:
interface Speaker {
    void speak();
}

class TestAnonymousInner2 {
    public static void main(String[] args) {
        Speaker s = new Speaker() {
            public void speak() {
                System.out.println("hello bharat");
            }
        };
        s.speak();
    }
}
Explanation: 1) Interface Speaker declares speak(). 2) 'new Speaker(){ public void speak(){...} }' defines an anonymous class implementing Speaker. 3) The object is assigned to the Speaker reference s. 4) s.speak() calls the overridden method and prints "hello bharat".
Q3.Medium
Write a Java program that shows how the compiler internally generates a class for an anonymous inner class. Create an abstract class Animal with an abstract method sound(). In main(), create an anonymous inner class that extends Animal and implements sound() to print "sweet mangoes", assign it to an Animal reference variable a, and call a.sound(). Also include a comment-style demonstration (as a static nested class named Demo$1 extending Animal) showing what the compiler generates internally.
Show answer & explanation
Answer:
abstract class Animal {
    abstract void sound();
}

class Demo {
    static class Demo$1 extends Animal {
        Demo$1() {}
        void sound() {
            System.out.println("sweet mangoes");
        }
    }

    public static void main(String[] args) {
        Animal a = new Animal() {
            void sound() {
                System.out.println("sweet mangoes");
            }
        };
        a.sound();
    }
}
Explanation: 1. Animal is an abstract class with abstract method sound(). 2. In main, 'new Animal(){ ... }' creates an anonymous inner class that extends Animal and overrides sound(). 3. The compiler internally generates a class (shown here as Demo$1) that extends Animal and provides the sound() implementation. 4. An object of that generated class is created and referred to by the Animal reference 'a'. 5. Calling a.sound() prints "sweet mangoes".
Q4.Medium
Write a Java program that demonstrates how the compiler generates an internal class for an anonymous inner class. Define an interface Greeter with a method void greet(). In main, create a Greeter reference g using an anonymous inner class that implements greet() to print "namaste duniya", then call g.greet().
Show answer & explanation
Answer:
interface Greeter {
    void greet();
}

class TestAnonymousInner {
    public static void main(String[] args) {
        Greeter g = new Greeter() {
            public void greet() {
                System.out.println("namaste duniya");
            }
        };
        g.greet();
    }
}
Explanation: 1) The interface Greeter declares greet(). 2) In main, 'new Greeter(){...}' creates an anonymous class that implements Greeter and defines greet(). 3) The compiler generates an internal class (e.g., TestAnonymousInner$1) implementing Greeter. 4) An object of that class is created and assigned to the Greeter reference g. 5) Calling g.greet() prints "namaste duniya".

Classes and Objects

Q5.Easy
Write a Java program to demonstrate a class and object. Create a class named 'Book' with two data members: 'bookId' (int) and 'title' (String). In the main method (inside the Book class), create an object of Book using the new keyword and print its data members. The output should be the default values (0 and null).
Show answer & explanation
Answer:
class Book {
    int bookId;
    String title;
    public static void main(String[] args) {
        Book b = new Book();
        System.out.println(b.bookId);
        System.out.println(b.title);
    }
}
Explanation: 1. Define class Book with fields bookId (int) and title (String). 2. In main method, create object b using new Book(). 3. Print b.bookId, which is 0 by default. 4. Print b.title, which is null by default. 5. The program outputs 0 and null on separate lines.
Q6.Easy
Write a Java program that initializes objects through a method. Create a class Student with fields rollno (int) and name (String), a method insertRecord(int r, String n) that assigns these values, and a method displayInformation() that prints rollno and name separated by a space. In the main method of class TestStudent4, create two Student objects, initialize them by calling insertRecord with (305, "Ananya") and (406, "Vikram"), then call displayInformation() on both objects.
Show answer & explanation
Answer:
class Student {
    int rollno;
    String name;
    void insertRecord(int r, String n) {
        rollno = r;
        name = n;
    }
    void displayInformation() {
        System.out.println(rollno + " " + name);
    }
}

class TestStudent4 {
    public static void main(String args[]) {
        Student s1 = new Student();
        Student s2 = new Student();
        s1.insertRecord(305, "Ananya");
        s2.insertRecord(406, "Vikram");
        s1.displayInformation();
        s2.displayInformation();
    }
}
Explanation: 1) Student declares instance fields rollno and name. 2) insertRecord(r, n) stores the passed values into the calling object's fields. 3) displayInformation() prints rollno, a space and name. 4) main creates two independent Student objects s1 and s2. 5) s1 is initialized with 305 and "Ananya"; s2 with 406 and "Vikram". 6) Calling displayInformation() prints: 305 Ananya then 406 Vikram.
Q7.Easy
Write a Java program that keeps records of employees using a class and objects. Create a class Employee with fields id (int), name (String) and salary (float), and a method insert(int i, String n, float s) that sets these fields, plus a method display() that prints id, name and salary separated by spaces. In the main method of a public class TestEmployee, create three Employee objects and initialize them by calling insert with (201, "Rohan", 38000), (202, "Meera", 42000) and (203, "Suresh", 51000), then call display() on each object in that order.
Show answer & explanation
Answer:
class Employee {
    int id;
    String name;
    float salary;
    void insert(int i, String n, float s) {
        id = i;
        name = n;
        salary = s;
    }
    void display() {
        System.out.println(id + " " + name + " " + salary);
    }
}

public class TestEmployee {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        Employee e3 = new Employee();
        e1.insert(201, "Rohan", 38000);
        e2.insert(202, "Meera", 42000);
        e3.insert(203, "Suresh", 51000);
        e1.display();
        e2.display();
        e3.display();
    }
}
Explanation: 1) The Employee class declares three instance fields: id, name and salary. 2) insert(i, n, s) copies the arguments into the object's fields, so each object stores its own data. 3) display() prints id, a space, name, a space and salary on one line. 4) main creates three separate Employee objects e1, e2, e3. 5) Each object is initialized with its own values via insert. 6) Calling display() on e1, e2, e3 prints: 201 Rohan 38000.0, 202 Meera 42000.0, 203 Suresh 51000.0 (float values print with .0).
Q8.Easy
Write a Java program with a class named Plot that has two integer fields, length and breadth, a method setDimensions(int l, int b) to assign them, and a method printArea() that prints the area (length * breadth). In the main method, create two Plot objects: set the first to length 12 and breadth 4, the second to length 7 and breadth 9, then print the area of each.
Show answer & explanation
Answer:
class Plot {
    int length;
    int breadth;

    void setDimensions(int l, int b) {
        length = l;
        breadth = b;
    }

    void printArea() {
        System.out.println(length * breadth);
    }
}

class TestPlot {
    public static void main(String args[]) {
        Plot p1 = new Plot();
        Plot p2 = new Plot();
        p1.setDimensions(12, 4);
        p2.setDimensions(7, 9);
        p1.printArea();
        p2.printArea();
    }
}
Explanation: 1. Define class Plot with fields length and breadth. 2. setDimensions(l, b) assigns the given values to the fields. 3. printArea() prints length * breadth. 4. In main, create two objects p1 and p2 of class Plot. 5. p1.setDimensions(12, 4) gives area 12*4 = 48; p2.setDimensions(7, 9) gives area 7*9 = 63. 6. p1.printArea() prints 48 and p2.printArea() prints 63.
Q9.Easy
Write a Java program to demonstrate creating multiple objects of the same class. Create a class `Rectangle` with integer fields `length` and `width`. Include a method `insert(int l, int w)` to set the dimensions and a method `calculateArea()` that prints the area. In the main method, create two Rectangle objects `r1` and `r2` using a single declaration statement (e.g., `Rectangle r1 = new Rectangle(), r2 = new Rectangle();`). Initialize `r1` with length 8 and width 6, and `r2` with length 5 and width 9. Call `calculateArea()` for both objects.
Show answer & explanation
Answer:
class Rectangle {
    int length;
    int width;

    void insert(int l, int w) {
        length = l;
        width = w;
    }

    void calculateArea() {
        System.out.println(length * width);
    }
}

public class TestRectangle2 {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle(), r2 = new Rectangle();
        r1.insert(8, 6);
        r2.insert(5, 9);
        r1.calculateArea();
        r2.calculateArea();
    }
}
Explanation: 1. Define class Rectangle with fields length and width. 2. insert() sets length and width. 3. calculateArea() prints length * width. 4. In main, declare and create two objects r1 and r2 in one statement. 5. Call r1.insert(8,6) and r2.insert(5,9). 6. Call r1.calculateArea() which prints 48, and r2.calculateArea() which prints 45.
Q10.Medium
Write a Java program to simulate a simple bank account. Create a class `BankAccount` with fields for account number, account holder name, and balance. Include methods to initialize the account details, deposit an amount, withdraw an amount (with insufficient balance check), check the current balance, and display account details. In the main method, create an object of `BankAccount`, initialize it with account number 123456, name "Rahul", and balance 5000. Display the account details, check balance, deposit Rs. 20000, check balance, withdraw Rs. 8000, and check balance again.
Show answer & explanation
Answer:
class BankAccount {
    int accNo;
    String name;
    double balance;

    void insert(int a, String n, double bal) {
        accNo = a;
        name = n;
        balance = bal;
    }

    void deposit(double amt) {
        balance += amt;
        System.out.println(amt + " deposited");
    }

    void withdraw(double amt) {
        if (balance < amt) {
            System.out.println("Insufficient Balance");
        } else {
            balance -= amt;
            System.out.println(amt + " withdrawn");
        }
    }

    void checkBalance() {
        System.out.println("Balance is: " + balance);
    }

    void display() {
        System.out.println(accNo + " " + name + " " + balance);
    }
}

public class TestBankAccount {
    public static void main(String[] args) {
        BankAccount a1 = new BankAccount();
        a1.insert(123456, "Rahul", 5000);
        a1.display();
        a1.checkBalance();
        a1.deposit(20000);
        a1.checkBalance();
        a1.withdraw(8000);
        a1.checkBalance();
    }
}
Explanation: 1. Define class BankAccount with fields accNo, name, balance. 2. insert() initializes the fields. 3. deposit() adds amount to balance and prints a message. 4. withdraw() checks if balance is sufficient; if not, prints 'Insufficient Balance'; else subtracts and prints message. 5. checkBalance() prints current balance. 6. display() prints account details. 7. In main, create object a1, call insert(123456, "Rahul", 5000), then display and checkBalance. 8. Deposit 20000, checkBalance; withdraw 8000, checkBalance.

Custom Exceptions

Q11.Easy
Write a Java program that creates a custom checked exception named InvalidRollNumberException. The class must extend Exception and have a constructor that accepts a String error message and passes it to the parent class using super(). Include a main method that throws this exception for a roll number less than 1, catches it, and prints the message.
Show answer & explanation
Answer:
class InvalidRollNumberException extends Exception {
    public InvalidRollNumberException(String errorMessage) {
        super(errorMessage);
    }
}

public class TestRollNumber {
    static void validateRoll(int roll) throws InvalidRollNumberException {
        if (roll < 1) {
            throw new InvalidRollNumberException("Roll number must be positive: " + roll);
        }
        System.out.println("Valid roll number: " + roll);
    }

    public static void main(String[] args) {
        try {
            validateRoll(23);
            validateRoll(0);
        } catch (InvalidRollNumberException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Explanation: 1) InvalidRollNumberException extends Exception, so it is a custom checked exception. 2) The constructor receives the error message and calls super(errorMessage) to store it in the parent Exception class. 3) validateRoll throws the exception when roll < 1. 4) main calls validateRoll(23), which prints 'Valid roll number: 23'. 5) validateRoll(0) throws the exception, which is caught and printed as 'Caught: Roll number must be positive: 0'.
Q12.Medium
Write a Java program that defines a custom checked exception named InvalidMarksException. Its constructor must accept a String error message and pass it to the parent Exception class using super(). Then write a small main method that throws this exception when a student's marks are below 0 or above 100, catches it, and prints the message.
Show answer & explanation
Answer:
class InvalidMarksException extends Exception {
    public InvalidMarksException(String str) {
        super(str);
    }
}

public class TestMarksException {
    static void checkMarks(int marks) throws InvalidMarksException {
        if (marks < 0 || marks > 100) {
            throw new InvalidMarksException("Marks must be between 0 and 100: " + marks);
        }
        System.out.println("Valid marks: " + marks);
    }

    public static void main(String[] args) {
        try {
            checkMarks(85);
            checkMarks(120);
        } catch (InvalidMarksException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Explanation: 1) InvalidMarksException extends Exception, making it a checked custom exception. 2) Its constructor takes a String and calls super(str) so the message is stored in the parent Exception. 3) checkMarks throws the exception when marks are outside 0-100. 4) main calls checkMarks(85) which prints 'Valid marks: 85'. 5) checkMarks(120) throws InvalidMarksException, caught in the catch block, printing 'Caught: Marks must be between 0 and 100: 120'.
Q13.Medium
Write a Java program that defines a custom exception class named InvalidAgeException (extending Exception). In the main method, read an integer age from the user via Scanner. If the age is less than 18, throw an InvalidAgeException with the message "Not eligible to vote"; otherwise print "Eligible to vote". Handle the exception with try-catch and print the exception message.
Show answer & explanation
Answer:
import java.util.Scanner;

class InvalidAgeException extends Exception {
    InvalidAgeException(String msg) {
        super(msg);
    }
}

public class AgeCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        try {
            if (age < 18) {
                throw new InvalidAgeException("Not eligible to vote");
            }
            System.out.println("Eligible to vote");
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
        sc.close();
    }
}
Explanation: 1) Define InvalidAgeException extending Exception with a constructor that passes the message to super(). 2) In main, read an integer age using Scanner. 3) Inside try, check if age < 18; if so, throw new InvalidAgeException("Not eligible to vote"). 4) If no exception is thrown, print "Eligible to vote". 5) The catch block catches InvalidAgeException and prints its message via getMessage(). 6) Close the Scanner at the end.

Exception Handling

Q14.Easy
Write a Java program that demonstrates a NullPointerException when calling compareTo() on a null String reference. Declare a String variable named 'city' and initialize it to null. Then attempt to call compareTo("Delhi") on it and print the result. The program should compile and run, but will throw NullPointerException at runtime.
Show answer & explanation
Answer:
public class NullCompareDemo {
    public static void main(String[] args) {
        String city = null;
        // This will throw NullPointerException because city is null
        int result = city.compareTo("Delhi");
        System.out.println(result);
    }
}
Explanation: 1. Declare a String variable 'city' and assign null. 2. Call compareTo("Delhi") on city. Since city is null, invoking a method on it causes NullPointerException. 3. The program compiles because the compiler does not check for null at compile time. 4. At runtime, the JVM throws NullPointerException when trying to execute the method call. 5. The println statement is never reached.
Q15.Easy
Write a Java program that demonstrates ArrayIndexOutOfBoundsException. Create an integer array with elements {15, 25, 35, 45} and use a for loop that iterates from 0 to arr.length (inclusive). Inside the loop, print the array element. The program should compile and run, but it will throw ArrayIndexOutOfBoundsException when trying to access an index equal to the array length.
Show answer & explanation
Answer:
public class ArrayExceptionDemo {
    public static void main(String[] args) {
        int[] arr = {15, 25, 35, 45};
        for (int i = 0; i <= arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
Explanation: 1. Declare and initialize an integer array arr with values {15, 25, 35, 45}. The length of arr is 4, so valid indices are 0,1,2,3. 2. Start a for loop with i=0; condition i <= arr.length (i <= 4); increment i by 1 each iteration. 3. In each iteration, print arr[i]. 4. When i=0,1,2,3, it prints 15,25,35,45 respectively. 5. When i=4, the condition i <= 4 is true, but arr[4] is out of bounds because the last valid index is 3. The JVM throws ArrayIndexOutOfBoundsException. 6. The program terminates with that exception.
Q16.Medium
Write a Java program that demonstrates a ClassCastException when comparing incompatible types using compareTo(). Create a class 'Student' with a String name and a constructor. In the main method, create an ArrayList<String> and add "Rahul". Then attempt to cast the ArrayList to a String and call compareTo("Rahul") on it. This will throw ClassCastException at runtime.
Show answer & explanation
Answer:
import java.util.*;

class Student {
    private String name;
    public Student(String name) {
        this.name = name;
    }
}

public class ClassCastDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Rahul");
        // Attempt to cast ArrayList to String (via Object so it compiles)
        String str = (String) (Object) list; // throws ClassCastException at runtime
        int result = str.compareTo("Rahul");
        System.out.println(result);
    }
}
Explanation: 1. Define a class Student with a String field and constructor (though not directly used in the exception). 2. In main, create an ArrayList<String> and add "Rahul". 3. Attempt to cast the ArrayList object to String: (String) list. Since ArrayList is not a String, this cast is invalid. 4. At runtime, the JVM throws ClassCastException because the actual object is not a String. 5. The subsequent compareTo call is never executed.
Q17.Medium
Write a Java program: Example 2. Let's consider the following example. Here the try block within nested try block (inner try block 2) do not handle the exception. The control is then transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. It is termed as nesting. NestedTryBlock.java
Show answer & explanation
Answer:
public class NestedTryBlock {
    public static void main(String args[]) {
        try {
            try {
                try {
                    int arr[] = { 10, 20, 30, 40 };
                    System.out.println(arr[6]);
                } catch (ArithmeticException e) {
                    System.out.println("Arithmetic exception");
                    System.out.println(" inner try block 2");
                }
            } catch (ArithmeticException e) {
                System.out.println("Arithmetic exception");
                System.out.println("inner try block 1");
            }
        } catch (ArrayIndexOutOfBoundsException e4) {
            System.out.print(e4);
            System.out.println(" outer (main) try block");
        } catch (Exception e5) {
            System.out.print("Exception");
            System.out.println(" handled in main try-block");
        }
    }
}
Explanation: 1. The outer try block contains an inner try block 1, which contains inner try block 2. 2. Inside inner try block 2, an array arr of size 4 is created with elements {10,20,30,40}. 3. Accessing arr[6] throws ArrayIndexOutOfBoundsException because index 6 is out of bounds. 4. Inner try block 2 has a catch for ArithmeticException, which does not match, so it does not handle the exception. 5. The exception propagates to inner try block 1, which also catches ArithmeticException, so it does not handle it. 6. The exception propagates to the outer try block, which has a catch for ArrayIndexOutOfBoundsException. This catch handles the exception. 7. The catch block prints the exception message (e4) followed by " outer (main) try block". 8. Thus, the program demonstrates nested try blocks and exception propagation.
Q18.Medium
Write a Java program that demonstrates handling a checked exception using a try-catch block. Create a class 'Resource' with a method 'access()' that throws an IOException with the message "Resource unavailable". In the main method, call this method inside a try-catch block that catches Exception and prints "Exception caught". After the try-catch, print "Program continues". The program should compile and run without terminating abnormally.
Show answer & explanation
Answer:
import java.io.*;

class Resource {
    void access() throws IOException {
        throw new IOException("Resource unavailable");
    }
}

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            Resource res = new Resource();
            res.access();
        } catch (Exception e) {
            System.out.println("Exception caught");
        }
        System.out.println("Program continues");
    }
}
Explanation: 1. Define a class Resource with a method access() that declares throws IOException and throws a new IOException with message "Resource unavailable". 2. In the main method of ExceptionDemo, create a Resource object inside a try block and call access(). 3. The catch block catches Exception (superclass of IOException) and prints "Exception caught". 4. After the try-catch, print "Program continues". 5. When run, the exception is thrown, caught, and the program continues normally.
Q19.Medium
Write a Java program that demonstrates IllegalArgumentException. Create a class named PriorityDemo that extends Thread. In the main method, try to set the priority of the current (main) thread to 15 using Thread.currentThread().setPriority(15). Since valid thread priority ranges from 1 to 10, this call throws an IllegalArgumentException. Catch the exception and print the message "Invalid priority value caught". Also, before setting the priority, print the default priority of the main thread.
Show answer & explanation
Answer:
public class PriorityDemo extends Thread {
    public static void main(String[] args) {
        Thread t = Thread.currentThread();
        System.out.println("Default priority of main thread: " + t.getPriority());
        try {
            t.setPriority(15);
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid priority value caught");
        }
        System.out.println("Priority after attempt: " + t.getPriority());
    }
}
Explanation: 1. Thread.currentThread() returns the main thread object. 2. The default priority of any thread is NORM_PRIORITY = 5, so the first print shows 5. 3. setPriority(15) is invalid because allowed values are 1 to 10, so Java throws IllegalArgumentException. 4. The try-catch block catches it and prints the custom message. 5. The priority remains unchanged (5), which is shown by the final print.

Exception Handling - Multiple Catch Blocks

Q20.Easy
Write a Java program that declares an integer array of size 4, then inside a try block tries to print the element at index 7. Add three catch blocks in this order: ArithmeticException (print "Arithmetic problem"), ArrayIndexOutOfBoundsException (print "Index problem"), and Exception (print "General problem"). After the try-catch, print "program continues".
Show answer & explanation
Answer:
public class MultiCatchDemo {
    public static void main(String[] args) {
        try {
            int marks[] = new int[4];
            System.out.println(marks[7]);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic problem");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index problem");
        } catch (Exception e) {
            System.out.println("General problem");
        }
        System.out.println("program continues");
    }
}
Explanation: 1) An int array of size 4 has valid indices 0 to 3. 2) Accessing marks[7] throws ArrayIndexOutOfBoundsException. 3) Java checks catch blocks top to bottom; the first matching one is ArrayIndexOutOfBoundsException, so it prints "Index problem". 4) The ArithmeticException and Exception blocks are skipped. 5) Execution continues after the try-catch, printing "program continues".
Q21.Medium
Write a Java program that declares an integer array of size 3 and, inside a try block, executes the statement a[3] = 50 / 0;. Add catch blocks for ArithmeticException (print "Arithmetic Exception occurs"), ArrayIndexOutOfBoundsException (print "ArrayIndexOutOfBounds Exception occurs") and Exception (print "Parent Exception occurs"). After the try-catch, print "rest of the code".
Show answer & explanation
Answer:
public class MultiCatchDemo2 {
    public static void main(String[] args) {
        try {
            int a[] = new int[3];
            a[3] = 50 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");
        } catch (Exception e) {
            System.out.println("Parent Exception occurs");
        }
        System.out.println("rest of the code");
    }
}
Explanation: 1) The array a has size 3, so valid indices are 0 to 2; index 3 is out of range. 2) In the statement a[3] = 50 / 0;, Java evaluates the right-hand side first: 50 / 0 throws ArithmeticException. 3) So the ArithmeticException catch block runs and prints "Arithmetic Exception occurs". 4) The remaining catch blocks are skipped. 5) Control moves past the try-catch and prints "rest of the code".
Q22.Medium
Write a Java program that demonstrates what happens when catch blocks are NOT ordered from most specific to most general. In the program, inside a try block declare an int array of size 4 and then execute the statement arr[4] = 50 / 0;. Add catch blocks in this order: first catch(Exception e) printing "general task done", then catch(ArithmeticException e) printing "division task done", then catch(ArrayIndexOutOfBoundsException e) printing "index task done". After the try-catch, print "remaining code...". (Note: the program will fail to compile because a more general exception is caught before more specific ones.)
Show answer & explanation
Answer:
class MultipleCatchOrderDemo {
    public static void main(String args[]) {
        try {
            int arr[] = new int[4];
            arr[4] = 50 / 0;
        }
        catch (Exception e) {
            System.out.println("general task done");
        }
        catch (ArithmeticException e) {
            System.out.println("division task done");
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("index task done");
        }
        System.out.println("remaining code...");
    }
}
Explanation: 1. The try block creates an int array of size 4 (valid indices 0-3) and then evaluates arr[4] = 50 / 0. 2. The catch blocks are written with Exception (the most general) first, followed by ArithmeticException and ArrayIndexOutOfBoundsException (more specific). 3. Java requires that a catch block for a subclass exception must come before a catch block for its superclass; otherwise the later block is unreachable. 4. Since Exception is the parent of both ArithmeticException and ArrayIndexOutOfBoundsException, the compiler reports an error: 'exception ArithmeticException has already been caught' (and similarly for the array exception). 5. Hence the program does not compile; to fix it, order the catch blocks from most specific to most general.

Exception Handling in Overriding

Q23.Medium
Write a Java program to demonstrate the rule: If the superclass method does not declare an exception, the subclass overridden method cannot declare a checked exception. Create a superclass 'Vehicle' with a method 'display()' that prints "Vehicle method" and does not declare any exception. Then create a subclass 'Car' that overrides 'display()' but attempts to declare a checked exception 'IOException'. Show that this causes a compilation error. (Note: The program should illustrate the rule; you may comment out the erroneous code to show the correct version.)
Show answer & explanation
Answer:
import java.io.*;

class Vehicle {
    void display() {
        System.out.println("Vehicle method");
    }
}

class Car extends Vehicle {
    // Uncommenting the following line will cause a compilation error:
    // void display() throws IOException {
    //     System.out.println("Car method");
    // }
    
    // Correct version without checked exception
    void display() {
        System.out.println("Car method");
    }
}

public class TestExceptionChild {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.display();
    }
}
Explanation: 1. The superclass Vehicle defines display() without any throws clause. 2. The subclass Car attempts to override display() and declare a checked exception IOException. This is not allowed because the subclass method cannot add checked exceptions not declared by the superclass method. 3. The compiler will report an error if the throws clause is uncommented. 4. The correct version omits the throws clause, and the program runs successfully, printing "Car method" due to dynamic method dispatch.
Q24.Medium
Write a Java program to demonstrate that when a subclass overrides a method, it can declare the same exception as the superclass method. Create a class `Animal` with a method `sound()` that throws `Exception` and prints "Animal makes a sound". Then create a subclass `Dog` that overrides `sound()` to also throw `Exception` and prints "Dog barks". In the main method, create a `Dog` object and call `sound()` inside a try-catch block that catches `Exception` and prints "Caught: " followed by the exception message. Use appropriate exception messages.
Show answer & explanation
Answer:
class Animal {
    void sound() throws Exception {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() throws Exception {
        System.out.println("Dog barks");
        throw new Exception("Dog is upset");
    }
}

public class TestExceptionChild3 {
    public static void main(String[] args) {
        Dog d = new Dog();
        try {
            d.sound();
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Explanation: 1. Define a superclass `Animal` with method `sound()` that declares `throws Exception` and prints "Animal makes a sound". 2. Define a subclass `Dog` that overrides `sound()` and also declares `throws Exception`. This is allowed because the overriding method throws the same checked exception. 3. In `Dog.sound()`, print "Dog barks" and then throw a new `Exception` with message "Dog is upset". 4. In the main method, create a `Dog` object and call `sound()` inside a try block. 5. Catch `Exception` and print "Caught: " followed by the exception message. 6. The output will be: "Dog barks" then "Caught: Dog is upset".
Q25.Medium
Write a Java program to demonstrate that when a subclass overrides a method, it can declare a subclass exception (a more specific checked exception) than the one declared by the superclass method. Create a class `Vehicle` with a method `start()` that throws `Exception` and prints "Vehicle started". Then create a subclass `Car` that overrides `start()` to throw `RuntimeException` (a subclass of Exception) and prints "Car started". In the main method, create a `Car` object and call `start()` inside a try-catch block that catches `Exception` and prints "Caught: " followed by the exception message. Use appropriate exception messages.
Show answer & explanation
Answer:
class Vehicle {
    void start() throws Exception {
        System.out.println("Vehicle started");
    }
}

class Car extends Vehicle {
    @Override
    void start() throws RuntimeException {
        System.out.println("Car started");
        throw new RuntimeException("Car engine failed");
    }
}

public class TestExceptionChild4 {
    public static void main(String[] args) {
        Car c = new Car();
        try {
            c.start();
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Explanation: 1. Define a superclass `Vehicle` with method `start()` that declares `throws Exception` and prints "Vehicle started". 2. Define a subclass `Car` that overrides `start()` but declares `throws RuntimeException` (a subclass of Exception). This is allowed because the overriding method can throw a narrower checked exception. 3. In `Car.start()`, print "Car started" and then throw a new `RuntimeException` with message "Car engine failed". 4. In the main method, create a `Car` object and call `start()` inside a try block. 5. Catch `Exception` (which also catches RuntimeException) and print "Caught: " followed by the exception message. 6. The output will be: "Car started" then "Caught: Car engine failed".

Exception Handling with finally

Q26.Easy
Write a Java program named TryCatchFinallyDemo.java. Inside the try block, print "Inside try block" and then attempt to compute 40/0, printing the result. Catch the ArithmeticException, print "Exception handled" and then print the exception object. Add a finally block that prints "finally block always runs". After the try-catch-finally, print "remaining code executes".
Show answer & explanation
Answer:
public class TryCatchFinallyDemo {
    public static void main(String args[]) {
        try {
            System.out.println("Inside try block");
            int result = 40 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Exception handled");
            System.out.println(e);
        } finally {
            System.out.println("finally block always runs");
        }
        System.out.println("remaining code executes");
    }
}
Explanation: 1) The try block prints "Inside try block". 2) The statement int result = 40 / 0; throws an ArithmeticException (divide by zero). 3) Control jumps to the catch block for ArithmeticException, which prints "Exception handled" and then the exception object (e.g., java.lang.ArithmeticException: / by zero). 4) The finally block always executes, printing "finally block always runs". 5) After the try-catch-finally, the program continues and prints "remaining code executes".
Q27.Easy
Write a Java program that demonstrates the case where an exception occurs inside a try block and is handled by the matching catch block, the finally block still executes, and then the rest of the program continues normally. In the try block, print "Entering try block" and then attempt to compute the value of 48 divided by 0 (store it in an int variable and print it). Catch ArithmeticException, print "Arithmetic exception caught" and print the exception object. In the finally block print "finally block runs always". After the try-catch-finally, print "remaining code executes...". Name the class FinallyDemoHandled.
Show answer & explanation
Answer:
public class FinallyDemoHandled {
    public static void main(String args[]) {
        try {
            System.out.println("Entering try block");
            int result = 48 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic exception caught");
            System.out.println(e);
        } finally {
            System.out.println("finally block runs always");
        }
        System.out.println("remaining code executes...");
    }
}
Explanation: 1) The try block prints 'Entering try block'. 2) The statement int result = 48 / 0; throws an ArithmeticException (divide by zero), so the print of result is skipped. 3) The catch(ArithmeticException e) matches, so it prints 'Arithmetic exception caught' and then prints the exception object (java.lang.ArithmeticException: / by zero). 4) The finally block always runs, printing 'finally block runs always'. 5) Since the exception was handled, control continues after the try-catch-finally and prints 'remaining code executes...'.
Q28.Medium
Write a Java program that demonstrates the case where an exception occurs inside a try block but the catch block does NOT match the exception type, so the exception is not handled. In the try block, print "Entering try block" and then attempt to compute 36 divided by 0 (store it in an int variable and print it). Provide a catch block for NullPointerException that prints the exception object. Add a finally block that prints "finally block runs always". After the try-catch-finally, print "remaining code executes...". Name the class FinallyDemoUnhandled.
Show answer & explanation
Answer:
public class FinallyDemoUnhandled {
    public static void main(String args[]) {
        try {
            System.out.println("Entering try block");
            int result = 36 / 0;
            System.out.println(result);
        } catch (NullPointerException e) {
            System.out.println(e);
        } finally {
            System.out.println("finally block runs always");
        }
        System.out.println("remaining code executes...");
    }
}
Explanation: 1) The try block prints 'Entering try block'. 2) The statement int result = 36 / 0; throws an ArithmeticException (divide by zero). 3) The catch block only accepts NullPointerException, so it does not match and the exception is not handled. 4) The finally block still executes, printing 'finally block runs always'. 5) Because the exception is unhandled, the JVM terminates the program abnormally after the finally block, so 'remaining code executes...' is never printed.

File Handling

Q29.Easy
Write a Java program that creates a new file named "myNotes.txt" in the current directory. If the file is created successfully, print "File created successfully!"; otherwise, print "File already exists." Handle any IO exceptions by printing the exception message.
Show answer & explanation
Answer:
import java.io.*;

public class FileCreationDemo {
    public static void main(String[] args) {
        try {
            File file = new File("myNotes.txt");
            if (file.createNewFile()) {
                System.out.println("File created successfully!");
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
Explanation: 1. Import java.io.* for File and IOException. 2. Create a File object with the name "myNotes.txt". 3. Call createNewFile(): returns true if file was created, false if it already existed. 4. Print appropriate message based on the return value. 5. Catch IOException and print the error message.
Q30.Easy
Write a Java program that lists all file and directory names in the folder "C:\\Users\\Amit\\Documents" using the File class. The program should print each name on a new line.
Show answer & explanation
Answer:
import java.io.*;
public class FolderLister {
    public static void main(String[] args) {
        File folder = new File("C:\\Users\\Amit\\Documents");
        String[] names = folder.list();
        if (names != null) {
            for (String name : names) {
                System.out.println(name);
            }
        }
    }
}
Explanation: 1. Import java.io.* to use File class. 2. Create a File object pointing to the folder path. 3. Call list() to get an array of names (returns null if not a directory). 4. Check for null to avoid NullPointerException. 5. Loop through the array and print each name.
Q31.Medium
Write a Java program that creates a new file named "myFile.txt" in the current directory, prints its path, then obtains its canonical file, checks if it exists, and prints the absolute path and existence status. Handle any exceptions.
Show answer & explanation
Answer:
import java.io.*;
public class FileDemo {
    public static void main(String[] args) {
        try {
            File file = new File("myFile.txt");
            file.createNewFile();
            System.out.println(file);
            File canonicalFile = file.getCanonicalFile();
            System.out.println(canonicalFile);
            boolean exists = canonicalFile.exists();
            String path = canonicalFile.getAbsolutePath();
            System.out.println(exists);
            if (exists) {
                System.out.print(path + " Exists? " + exists);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Explanation: 1. Create a File object for "myFile.txt". 2. Call createNewFile() to create an empty file (returns true if created, false if already exists). 3. Print the File object (calls toString(), showing path). 4. Get canonical file using getCanonicalFile() and print it. 5. Check existence with exists() and store boolean. 6. Get absolute path with getAbsolutePath(). 7. Print boolean, then if true, print path and existence message. 8. Catch any exception and print stack trace.

Instance Initializer Block

Q32.Easy
Write a Java program that demonstrates an instance initializer block. Create a class named `Train` with an integer field `coaches`. The instance initializer block should set `coaches` to 24 (simulating a computation before the constructor runs). The constructor should print "coaches is " followed by the value of `coaches`. In `main`, create two `Train` objects to show that the initializer block runs for each object.
Show answer & explanation
Answer:
class Train {
    int coaches;

    Train() {
        System.out.println("coaches is " + coaches);
    }

    {
        coaches = 24;
    }

    public static void main(String args[]) {
        Train t1 = new Train();
        Train t2 = new Train();
    }
}
Explanation: 1. The class `Train` declares an int field `coaches`. 2. The instance initializer block `{ coaches = 24; }` runs automatically each time an object is created, before the constructor body. 3. The constructor prints "coaches is " plus the current value of `coaches`. 4. In `main`, `new Train()` first runs the initializer block (coaches becomes 24), then the constructor prints "coaches is 24". 5. Creating a second object repeats the same process, so the output is "coaches is 24" printed twice.
Q33.Easy
Write a Java program with a class 'Bike' having an int field 'speed', a constructor that prints "constructor is invoked", and an instance initializer block that prints "instance initializer block invoked". In the main method, create two Bike objects. Show which runs first: the instance initializer block or the constructor.
Show answer & explanation
Answer:
class Bike {
    int speed;

    Bike() {
        System.out.println("constructor is invoked");
    }

    {
        System.out.println("instance initializer block invoked");
    }

    public static void main(String[] args) {
        Bike b1 = new Bike();
        Bike b2 = new Bike();
    }
}
Explanation: 1. For each 'new Bike()', the instance initializer block runs before the constructor body. 2. So for b1: 'instance initializer block invoked' prints, then 'constructor is invoked'. 3. The same order repeats for b2. 4. Total output: instance initializer block invoked, constructor is invoked, instance initializer block invoked, constructor is invoked.
Q34.Medium
Write a Java program with a parent class 'Vehicle' whose constructor prints "Vehicle constructor called", and a child class 'Car' that extends Vehicle. The Car class should have an instance initializer block that prints "Car initializer block called", and a constructor that calls super() and then prints "Car constructor called". In the main method, create one Car object. Show that the instance initializer block runs after the parent constructor (super()) but before the child constructor body completes.
Show answer & explanation
Answer:
class Vehicle {
    Vehicle() {
        System.out.println("Vehicle constructor called");
    }
}

class Car extends Vehicle {
    Car() {
        super();
        System.out.println("Car constructor called");
    }

    {
        System.out.println("Car initializer block called");
    }

    public static void main(String[] args) {
        Car c = new Car();
    }
}
Explanation: 1. When 'new Car()' runs, the JVM first invokes the parent constructor via super(), so 'Vehicle constructor called' prints first. 2. After super() returns, the instance initializer block of Car executes, printing 'Car initializer block called'. 3. Then the remaining body of the Car constructor executes, printing 'Car constructor called'. 4. Output order: Vehicle constructor called, Car initializer block called, Car constructor called.
Q35.Medium
Write a Java program that demonstrates an instance initializer block. Create a parent class P with a constructor that prints "parent constructor called" and an instance block that prints "parent instance block". Create a child class C that extends P, with an instance block printing "child instance block" and a constructor printing "child constructor called". In main, create one object of class C.
Show answer & explanation
Answer:
class P {
    {
        System.out.println("parent instance block");
    }
    P() {
        System.out.println("parent constructor called");
    }
}

class C extends P {
    {
        System.out.println("child instance block");
    }
    C() {
        System.out.println("child constructor called");
    }
}

public class InstanceBlockDemo {
    public static void main(String args[]) {
        new C();
    }
}
Explanation: 1) When new C() runs, the parent class P is initialized first. 2) Inside P, the instance initializer block runs before the parent constructor, so "parent instance block" prints, then "parent constructor called". 3) Then the child class C's instance block runs, printing "child instance block". 4) Finally the child constructor body runs, printing "child constructor called". 5) Output order: parent instance block, parent constructor called, child instance block, child constructor called.

Interfaces

Q36.Easy
Write a Java program to demonstrate an interface with a single method. Create an interface named 'Greetable' with a method 'void greet()'. Implement this interface in a class named 'Greeter'. The greet() method should print "Namaste". In the main method, create an object of Greeter and call greet().
Show answer & explanation
Answer:
interface Greetable {
    void greet();
}

class Greeter implements Greetable {
    public void greet() {
        System.out.println("Namaste");
    }

    public static void main(String[] args) {
        Greeter obj = new Greeter();
        obj.greet();
    }
}
Explanation: 1. Define an interface 'Greetable' with a method 'void greet()'. 2. Create a class 'Greeter' that implements 'Greetable'. 3. Provide the implementation of 'greet()' to print "Namaste". 4. In the main method, instantiate 'Greeter' and call 'greet()'. 5. The program outputs "Namaste".
Q37.Easy
Write a Java program that demonstrates an interface for shapes. Define an interface Shape with a single method void draw(). Create two classes, Square and Triangle, that implement Shape; Square's draw() prints "drawing square" and Triangle's draw() prints "drawing triangle". In the main method, create a Shape reference pointing to a Triangle object and call draw(). Name the file ShapeDemo.java.
Show answer & explanation
Answer:
interface Shape {
    void draw();
}

class Square implements Shape {
    public void draw() {
        System.out.println("drawing square");
    }
}

class Triangle implements Shape {
    public void draw() {
        System.out.println("drawing triangle");
    }
}

class ShapeDemo {
    public static void main(String[] args) {
        Shape s = new Triangle();
        s.draw();
    }
}
Explanation: 1) Declare interface Shape with method void draw(). 2) Square implements Shape and prints "drawing square"; Triangle implements Shape and prints "drawing triangle". 3) In main, a Shape reference s holds a new Triangle object. 4) Calling s.draw() runs Triangle's implementation (dynamic dispatch). 5) Output: drawing triangle
Q38.Easy
Write a Java program that demonstrates an interface for banks. Define an interface LoanBank with a method float interestRate(). Create two classes, HDFC and ICICI, that implement LoanBank and return interest rates of 8.5f and 9.25f respectively. In a main method, create a LoanBank reference pointing to an HDFC object and print "Rate: " followed by the interest rate. Name the file BankDemo.java.
Show answer & explanation
Answer:
interface LoanBank {
    float interestRate();
}

class HDFC implements LoanBank {
    public float interestRate() {
        return 8.5f;
    }
}

class ICICI implements LoanBank {
    public float interestRate() {
        return 9.25f;
    }
}

class BankDemo {
    public static void main(String[] args) {
        LoanBank b = new HDFC();
        System.out.println("Rate: " + b.interestRate());
    }
}
Explanation: 1) Declare interface LoanBank with method float interestRate(). 2) HDFC implements LoanBank and returns 8.5f; ICICI implements it and returns 9.25f. 3) In main, a LoanBank reference b holds a new HDFC object (runtime polymorphism). 4) Calling b.interestRate() invokes HDFC's version, returning 8.5. 5) Output: Rate: 8.5

Method Overloading

Q39.Easy
Write a Java program to demonstrate method overloading with type promotion when an exact match is found. Create a class named 'OverloadDemo' with two methods: 'calculate(int x, int y)' that prints "int method called" and 'calculate(long x, long y)' that prints "long method called". In the main method, create an object and call 'calculate(15, 25)'. What is the output?
Show answer & explanation
Answer:
class OverloadDemo {
    void calculate(int x, int y) {
        System.out.println("int method called");
    }
    void calculate(long x, long y) {
        System.out.println("long method called");
    }
    public static void main(String[] args) {
        OverloadDemo obj = new OverloadDemo();
        obj.calculate(15, 25);
    }
}
Explanation: 1. The class OverloadDemo has two overloaded methods: calculate(int, int) and calculate(long, long). 2. In main, we call obj.calculate(15, 25) with two int arguments. 3. Java first looks for an exact match: calculate(int, int) matches exactly. 4. Since an exact match is found, type promotion is not performed; the int version is invoked. 5. The program prints "int method called".
Q40.Medium
Write a Java program that demonstrates overloading the main() method. Create a class named DemoMain with three overloaded main methods: one taking a String[] argument (prints "main with String[]"), one taking a single String argument (prints "main with String"), and one with no arguments (prints "main without args"). The JVM should invoke only the String[] version when the program runs.
Show answer & explanation
Answer:
public class DemoMain {
    public static void main(String[] args) {
        System.out.println("main with String[]");
    }
    public static void main(String args) {
        System.out.println("main with String");
    }
    public static void main() {
        System.out.println("main without args");
    }
}
Explanation: 1) Java allows method overloading, so a class can have multiple main methods with different parameter lists. 2) The JVM always looks for the exact signature public static void main(String[] args) as the entry point. 3) When the program runs, only the String[] version executes and prints "main with String[]". 4) The other overloaded main methods are valid methods but are not called by the JVM automatically. 5) If two methods had the same name and same parameter types (differing only in return type), the compiler would give an error, which is better than a runtime error.
Q41.Medium
Write a Java program to demonstrate method overloading with type promotion. Create a class named 'OverloadPromotion' with two methods: 'add(int a, long b)' that prints the sum a+b, and 'add(int a, int b, int c)' that prints the sum a+b+c. In the main method, create an object and call 'add(10, 20)' and 'add(10, 20, 30)'. What is the output?
Show answer & explanation
Answer:
class OverloadPromotion {
    void add(int a, long b) {
        System.out.println(a + b);
    }
    void add(int a, int b, int c) {
        System.out.println(a + b + c);
    }
    public static void main(String[] args) {
        OverloadPromotion obj = new OverloadPromotion();
        obj.add(10, 20);
        obj.add(10, 20, 30);
    }
}
Explanation: 1. The class OverloadPromotion has two overloaded methods: add(int, long) and add(int, int, int). 2. First call: obj.add(10, 20). The arguments are int and int. There is no exact match for add(int, int). Java tries to find a compatible method by type promotion. The method add(int, long) is applicable because the second int can be promoted to long. So it is invoked, printing 10+20=30. 3. Second call: obj.add(10, 20, 30). This matches add(int, int, int) exactly, so it prints 10+20+30=60. 4. Output: first line 30, second line 60.

Method Overriding

Q42.Easy
Write a Java program to demonstrate method overriding. Create a superclass 'Shape' with a method 'draw()' that prints "Drawing shape". Create a subclass 'Circle' that overrides 'draw()' to print "Drawing circle". In the main method, create an instance of Circle and call draw().
Show answer & explanation
Answer:
class Shape {
    void draw() {
        System.out.println("Drawing shape");
    }
}

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

public class OverridingExample {
    public static void main(String[] args) {
        Circle c = new Circle();
        c.draw();
    }
}
Explanation: 1. Shape class defines draw() method. 2. Circle class extends Shape and overrides draw() with its own implementation. 3. In main, we create a Circle object and call draw(). 4. The overridden method in Circle is executed, printing "Drawing circle".
Q43.Easy
Write a Java program that demonstrates why method overriding is needed. Create a parent class named Appliance with a method start() that prints "Appliance is starting". Create a child class named Fan that extends Appliance but does NOT override start(). In the main method, create a Fan object and call start() on it. Show that the parent class version of the method runs even though the object is of the child class.
Show answer & explanation
Answer:
class Appliance {
    void start() {
        System.out.println("Appliance is starting");
    }
}

class Fan extends Appliance {
    public static void main(String[] args) {
        Fan obj = new Fan();
        obj.start();
    }
}
Explanation: 1. Appliance defines start() printing "Appliance is starting". 2. Fan extends Appliance but does not define its own start(), so it inherits the parent version. 3. In main, a Fan object is created and start() is called. 4. Since Fan has no override, Java runs Appliance's start(), printing "Appliance is starting". 5. This shows that without overriding, the child object still uses the parent's behaviour.
Q44.Easy
Write a Java program to illustrate method overriding. Create a parent class Vehicle with a method run() that prints "Vehicle is running". Create a child class Car that extends Vehicle and overrides run() to print "Car is running safely". In the main method, create a Car object and call run().
Show answer & explanation
Answer:
class Vehicle {
    void run() { System.out.println("Vehicle is running"); }
}

class Car extends Vehicle {
    void run() { System.out.println("Car is running safely"); }

    public static void main(String[] args) {
        Car obj = new Car();
        obj.run();
    }
}
Explanation: 1) Vehicle defines run() printing "Vehicle is running". 2) Car extends Vehicle (IS-A relationship) and defines run() with the same name and no parameters, so it overrides the parent method. 3) main creates a Car object and calls run(); the child's version executes. 4) Output: Car is running safely.
Q45.Easy
Write a Java program that demonstrates method overriding in a real banking scenario. Create a parent class Bank with a method getRateOfInterest() that returns 0. Create three child classes — HDFC, PNB and BOI — that each override getRateOfInterest() to return 6, 7 and 8 respectively. In the main method, create one object of each child class and print the rate of interest of each bank.
Show answer & explanation
Answer:
class Bank {
    int getRateOfInterest() { return 0; }
}

class HDFC extends Bank {
    int getRateOfInterest() { return 6; }
}

class PNB extends Bank {
    int getRateOfInterest() { return 7; }
}

class BOI extends Bank {
    int getRateOfInterest() { return 8; }
}

public class BankDemo {
    public static void main(String[] args) {
        Bank b1 = new HDFC();
        Bank b2 = new PNB();
        Bank b3 = new BOI();
        System.out.println("HDFC rate of interest: " + b1.getRateOfInterest());
        System.out.println("PNB rate of interest: " + b2.getRateOfInterest());
        System.out.println("BOI rate of interest: " + b3.getRateOfInterest());
    }
}
Explanation: 1) Bank declares getRateOfInterest() returning 0. 2) Each child (HDFC, PNB, BOI) extends Bank and overrides the method with its own rate (6, 7, 8). 3) In main, parent-type references point to child objects, so the overridden method is chosen at runtime (runtime polymorphism). 4) Output: HDFC 6, PNB 7, BOI 8.

Nested Interface

Q46.Medium
Write a Java program that demonstrates a nested interface. Define an outer interface called 'Shape' with a method 'draw()' and a nested interface 'Details' with a method 'info()'. Create a class 'Circle' that implements both interfaces. In the main method, create a Circle object, call draw() and info(), and also demonstrate that the nested interface can be implemented separately by creating an anonymous class that implements Shape.Details and calls info().
Show answer & explanation
Answer:
interface Shape {
    void draw();
    interface Details {
        void info();
    }
}

class Circle implements Shape, Shape.Details {
    public void draw() {
        System.out.println("Drawing a circle");
    }
    public void info() {
        System.out.println("Circle details: radius = 5");
    }
}

public class NestedInterfaceDemo {
    public static void main(String[] args) {
        Circle c = new Circle();
        c.draw();
        c.info();
        
        Shape.Details d = new Shape.Details() {
            public void info() {
                System.out.println("Anonymous details");
            }
        };
        d.info();
    }
}
Explanation: 1. Define interface Shape with method draw() and nested interface Details with method info(). 2. Class Circle implements both Shape and Shape.Details, providing implementations for draw() and info(). 3. In main, create Circle object and call draw() and info(). 4. Create an anonymous class implementing Shape.Details and call info() to show nested interface can be implemented separately.
Q47.Medium
Write a Java program that demonstrates a nested interface declared inside another interface. Define an interface 'Showable' with a method 'show()' and a nested interface 'Message' with a method 'msg()'. Then create a class 'NestedInterfaceDemo' that implements 'Showable.Message' and provides an implementation of 'msg()' that prints "Hello from nested interface!". In the main method, create an instance of 'NestedInterfaceDemo' and call 'msg()'.
Show answer & explanation
Answer:
interface Showable {
    void show();
    interface Message {
        void msg();
    }
}

class NestedInterfaceDemo implements Showable.Message {
    public void msg() {
        System.out.println("Hello from nested interface!");
    }
    public static void main(String[] args) {
        NestedInterfaceDemo obj = new NestedInterfaceDemo();
        obj.msg();
    }
}
Explanation: 1. Define interface Showable with method show() and nested interface Message with method msg(). 2. Create class NestedInterfaceDemo that implements Showable.Message and provides msg() printing the message. 3. In main, instantiate NestedInterfaceDemo and call msg(), which prints the message.
Q48.Medium
Write a Java program that demonstrates a nested interface declared inside a class. Define a class 'Outer' that contains an interface 'Greetable' with a method 'greet()'. Then create another class 'GreetingDemo' that implements 'Outer.Greetable' and provides an implementation of 'greet()' that prints "Namaste from nested interface!". In the main method, create an instance of 'GreetingDemo' and call 'greet()'.
Show answer & explanation
Answer:
class Outer {
    interface Greetable {
        void greet();
    }
}

class GreetingDemo implements Outer.Greetable {
    public void greet() {
        System.out.println("Namaste from nested interface!");
    }
}

public class NestedInterfaceDemo {
    public static void main(String[] args) {
        GreetingDemo demo = new GreetingDemo();
        demo.greet();
    }
}
Explanation: 1. Define class Outer with a nested interface Greetable containing method greet(). 2. Create class GreetingDemo that implements Outer.Greetable and provides the greet() method printing the message. 3. In main, instantiate GreetingDemo and call greet(), which prints the message.

Recursion

Q49.Easy
Write a Java program that demonstrates infinite recursion by defining a recursive method that prints "Ram Ram" and then calls itself indefinitely. Include a main method that invokes this recursive method.
Show answer & explanation
Answer:
public class InfiniteRecursion {
    static void chant() {
        System.out.println("Ram Ram");
        chant();
    }
    public static void main(String[] args) {
        chant();
    }
}
Explanation: 1. Define a class InfiniteRecursion. 2. Define a static method chant() that prints "Ram Ram" and then calls itself. 3. Because there is no termination condition, the method will recurse infinitely (until StackOverflowError). 4. In main(), call chant() to start the infinite recursion. 5. The program will continuously print "Ram Ram" until the stack overflows.
Q50.Easy
Write a Java program that uses recursion to print the message "Namaste" exactly 4 times, each time followed by the count number (e.g., "Namaste 1", "Namaste 2", etc.). Use a static counter variable to limit the recursion.
Show answer & explanation
Answer:
public class RecursionCount {
    static int count = 0;
    static void greet() {
        count++;
        if (count <= 4) {
            System.out.println("Namaste " + count);
            greet();
        }
    }
    public static void main(String[] args) {
        greet();
    }
}
Explanation: 1. Define a class RecursionCount with a static integer count initialized to 0. 2. Define a static method greet() that increments count. 3. Inside greet(), check if count <= 4; if true, print "Namaste " + count and then call greet() recursively. 4. The recursion stops when count becomes 5 because the condition fails. 5. In main(), call greet() to start the recursion. 6. Output: Namaste 1, Namaste 2, Namaste 3, Namaste 4.
Q51.Easy
Write a Java program that computes the factorial of 7 using a recursive method and prints the result.
Show answer & explanation
Answer:
public class FactorialRecursion {
    static int factorial(int n) {
        if (n == 1)
            return 1;
        else
            return (n * factorial(n - 1));
    }

    public static void main(String[] args) {
        System.out.println("Factorial of 7 is: " + factorial(7));
    }
}
Explanation: 1) The method factorial(n) has a base case: when n == 1 it returns 1. 2) Otherwise it returns n * factorial(n-1), calling itself with a smaller value. 3) For n=7 the calls unfold as 7*6*5*4*3*2*1. 4) The base case factorial(1)=1 stops the recursion. 5) Multiplying back gives 5040, so the program prints "Factorial of 7 is: 5040".
Q52.Medium
Write a Java program that prints the first 12 terms of the Fibonacci series using recursion. The series starts with 0 and 1.
Show answer & explanation
Answer:
public class FibonacciRecursion {
    static int a = 0, b = 1, c = 0;

    static void printFibo(int count) {
        if (count > 0) {
            c = a + b;
            a = b;
            b = c;
            System.out.print(" " + c);
            printFibo(count - 1);
        }
    }

    public static void main(String[] args) {
        int count = 12;
        System.out.print(a + " " + b);
        printFibo(count - 2);
    }
}
Explanation: 1) Two static variables a=0 and b=1 hold the first two terms; c stores the next term. 2) main prints the first two terms (0 and 1). 3) printFibo(count-2) is called with 10, because 2 terms are already printed. 4) In each recursive call, c = a + b, then a and b are shifted forward (a=b, b=c), and c is printed. 5) The call recurses with count-1 until count becomes 0, so exactly 10 more terms are printed, giving 12 terms in total.

Runtime Polymorphism

Q53.Medium
Write a Java program to demonstrate runtime polymorphism. Create a class Vehicle with a method move() that prints "Vehicle is moving". Create a subclass Car that extends Vehicle and overrides move() to print "Car is driving on the road". In the main method, create an object of Car and assign it to a Vehicle reference. Call move() using that reference. What is the output?
Show answer & explanation
Answer:
class Vehicle {
    void move() {
        System.out.println("Vehicle is moving");
    }
}

class Car extends Vehicle {
    @Override
    void move() {
        System.out.println("Car is driving on the road");
    }

    public static void main(String[] args) {
        Vehicle v = new Car(); // upcasting
        v.move();
    }
}
Explanation: 1. Define a parent class Vehicle with a method move() that prints "Vehicle is moving". 2. Define a child class Car that extends Vehicle and overrides move() to print "Car is driving on the road". 3. In main, create a Car object and assign it to a Vehicle reference (upcasting). 4. Call move() using the Vehicle reference. At runtime, the JVM sees the actual object is Car, so Car's move() is invoked. 5. Output: Car is driving on the road.
Q54.Medium
Write a Java program that demonstrates runtime polymorphism using a base class 'Bank' with a method 'getRateOfInterest()' and subclasses 'HDFC', 'Kotak', and 'PNB' that override the method to return different interest rates: HDFC gives 7.5%, Kotak gives 6.8%, and PNB gives 8.2%. In the main method, create a 'Bank' reference and assign it to each subclass object, then print the rate of interest for each bank. The output should be:
HDFC Rate of Interest: 7.5
Kotak Rate of Interest: 6.8
PNB Rate of Interest: 8.2
Show answer & explanation
Answer:
class Bank {
    float getRateOfInterest() {
        return 0;
    }
}

class HDFC extends Bank {
    float getRateOfInterest() {
        return 7.5f;
    }
}

class Kotak extends Bank {
    float getRateOfInterest() {
        return 6.8f;
    }
}

class PNB extends Bank {
    float getRateOfInterest() {
        return 8.2f;
    }
}

public class TestPolymorphism {
    public static void main(String[] args) {
        Bank b;
        b = new HDFC();
        System.out.println("HDFC Rate of Interest: " + b.getRateOfInterest());
        b = new Kotak();
        System.out.println("Kotak Rate of Interest: " + b.getRateOfInterest());
        b = new PNB();
        System.out.println("PNB Rate of Interest: " + b.getRateOfInterest());
    }
}
Explanation: 1. Define a base class 'Bank' with a method 'getRateOfInterest()' that returns 0. 2. Create subclasses 'HDFC', 'Kotak', and 'PNB' that extend 'Bank' and override 'getRateOfInterest()' to return 7.5f, 6.8f, and 8.2f respectively. 3. In the main method, declare a 'Bank' reference 'b'. 4. Assign 'b' to a new 'HDFC' object and call 'b.getRateOfInterest()' – this invokes the overridden method in 'HDFC', returning 7.5, which is printed. 5. Similarly, assign 'b' to a new 'Kotak' and call the method, then to a new 'PNB' and call the method. 6. The output shows the rate of interest for each bank, demonstrating runtime polymorphism.
Q55.Medium
Write a Java program that demonstrates runtime polymorphism using a base class 'Vehicle' with a method 'move()' and subclasses 'Car', 'Bike', and 'Truck' that override 'move()'. In the main method, create a 'Vehicle' reference and assign it to each subclass object, then call 'move()' on each. The output should be:
Car is moving
Bike is moving
Truck is moving
Show answer & explanation
Answer:
class Vehicle {
    void move() {
        System.out.println("Vehicle is moving");
    }
}

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

class Bike extends Vehicle {
    void move() {
        System.out.println("Bike is moving");
    }
}

class Truck extends Vehicle {
    void move() {
        System.out.println("Truck is moving");
    }
}

public class TestPolymorphism {
    public static void main(String[] args) {
        Vehicle v;
        v = new Car();
        v.move();
        v = new Bike();
        v.move();
        v = new Truck();
        v.move();
    }
}
Explanation: 1. Define a base class 'Vehicle' with a method 'move()' that prints 'Vehicle is moving'. 2. Create subclasses 'Car', 'Bike', and 'Truck' that extend 'Vehicle' and override 'move()' to print their specific messages. 3. In the main method, declare a 'Vehicle' reference 'v'. 4. Assign 'v' to a new 'Car' object and call 'v.move()' – this invokes the overridden method in 'Car', printing 'Car is moving'. 5. Similarly, assign 'v' to a new 'Bike' and call 'v.move()', then to a new 'Truck' and call 'v.move()'. 6. The output shows the polymorphic behavior: the method executed depends on the actual object type, not the reference type.
Q56.Medium
Write a Java program that demonstrates runtime polymorphism with multilevel inheritance. Create a class LivingThing with a method breathe() that prints "LivingThing breathes". Create a class Plant that extends LivingThing and overrides breathe() to print "Plant breathes through leaves". Create a class Tree that extends Plant and overrides breathe() to print "Tree breathes through roots". In the main method of Tree, create three references: LivingThing l1 = new LivingThing(); LivingThing l2 = new Plant(); LivingThing l3 = new Tree(); then call breathe() on each. What is the output?
Show answer & explanation
Answer:
class LivingThing {
    void breathe() {
        System.out.println("LivingThing breathes");
    }
}

class Plant extends LivingThing {
    void breathe() {
        System.out.println("Plant breathes through leaves");
    }
}

class Tree extends Plant {
    void breathe() {
        System.out.println("Tree breathes through roots");
    }
    public static void main(String[] args) {
        LivingThing l1 = new LivingThing();
        LivingThing l2 = new Plant();
        LivingThing l3 = new Tree();
        l1.breathe();
        l2.breathe();
        l3.breathe();
    }
}
Explanation: 1. The program defines a superclass LivingThing with a breathe() method that prints "LivingThing breathes". 2. Plant extends LivingThing and overrides breathe() to print "Plant breathes through leaves". 3. Tree extends Plant and overrides breathe() to print "Tree breathes through roots". 4. In main, three LivingThing references are created: l1 refers to a LivingThing object, l2 to a Plant object, and l3 to a Tree object. 5. When l1.breathe() is called, it invokes LivingThing's breathe() method, printing "LivingThing breathes". 6. When l2.breathe() is called, dynamic method dispatch calls Plant's overridden breathe(), printing "Plant breathes through leaves". 7. When l3.breathe() is called, dynamic method dispatch calls Tree's overridden breathe(), printing "Tree breathes through roots". 8. Thus, the output is three lines: "LivingThing breathes", "Plant breathes through leaves", and "Tree breathes through roots".
Q57.Medium
Write a Java program that demonstrates runtime polymorphism with multilevel inheritance. Create a class Vehicle with a method move() that prints "Vehicle is moving". Create a class Car that extends Vehicle and overrides move() to print "Car is driving". Create a class SportsCar that extends Car. In the main method of SportsCar, create a Vehicle reference pointing to a SportsCar object and call move(). What is the output?
Show answer & explanation
Answer:
class Vehicle {
    void move() {
        System.out.println("Vehicle is moving");
    }
}

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

class SportsCar extends Car {
    public static void main(String[] args) {
        Vehicle v = new SportsCar();
        v.move();
    }
}
Explanation: 1. The program defines a superclass Vehicle with a move() method that prints "Vehicle is moving". 2. Car extends Vehicle and overrides move() to print "Car is driving". 3. SportsCar extends Car but does not override move(), so it inherits Car's move() method. 4. In main, a Vehicle reference v is assigned a new SportsCar object. 5. When v.move() is called, Java uses dynamic method dispatch to call the most specific overridden method available in the object's class hierarchy. 6. Since SportsCar does not override move(), the method from its immediate superclass Car is called. 7. Therefore, the output is "Car is driving".

Static Variables

Q58.Easy
Write a Java program that shows the memory advantage of a static variable. Create a class named Learner with fields: int id, String fullName, and a static String institute set to "Sunrise Academy". In the main method, create two Learner objects (id 101 with name "Aarav", and id 102 with name "Diya"), assign only id and fullName for each, and print each learner's id, fullName and institute. The institute value must be stored once as a static field shared by all objects.
Show answer & explanation
Answer:
class Learner {
    int id;
    String fullName;
    static String institute = "Sunrise Academy";

    public static void main(String[] args) {
        Learner l1 = new Learner();
        l1.id = 101;
        l1.fullName = "Aarav";

        Learner l2 = new Learner();
        l2.id = 102;
        l2.fullName = "Diya";

        System.out.println(l1.id + " " + l1.fullName + " " + Learner.institute);
        System.out.println(l2.id + " " + l2.fullName + " " + Learner.institute);
    }
}
Explanation: 1. The field 'institute' is declared static, so only one copy exists in memory and is shared by all Learner objects. 2. Each object stores only its own id and fullName, saving memory compared to storing the institute name in every object. 3. Two objects l1 and l2 are created and given their own id and fullName values. 4. The static field is accessed through the class name (Learner.institute) and printed with each object's data. 5. Output shows both learners sharing the same institute value.
Q59.Easy
Write a Java program to demonstrate a static variable. Create a class named Learner with an instance variable rollNo, an instance variable name, and a static variable instituteName set to "Sunrise Academy". The constructor should take rollNo and name as parameters. Add a display() method that prints rollNo, name and instituteName. In the main method, create two Learner objects: (101, "Rohit") and (102, "Meera"), then call display() on both. Show that the single static variable is shared by all objects.
Show answer & explanation
Answer:
class Learner {
    int rollNo;                 // instance variable
    String name;                // instance variable
    static String instituteName = "Sunrise Academy"; // static variable, shared by all objects

    Learner(int r, String n) {
        rollNo = r;
        name = n;
    }

    void display() {
        System.out.println(rollNo + " " + name + " " + instituteName);
    }
}

public class TestStaticVariable {
    public static void main(String args[]) {
        Learner l1 = new Learner(101, "Rohit");
        Learner l2 = new Learner(102, "Meera");
        l1.display();
        l2.display();
    }
}
Explanation: 1) 'rollNo' and 'name' are instance variables, so each Learner object stores its own values. 2) 'instituteName' is static, so only one copy exists in memory and it is shared by every object of Learner. 3) l1 is created with rollNo 101 and name Rohit; l2 with rollNo 102 and name Meera. 4) l1.display() prints: 101 Rohit Sunrise Academy. 5) l2.display() prints: 102 Meera Sunrise Academy — the same static value appears for both objects, showing it is shared.
Q60.Easy
Write a Java program that uses a static variable as a counter. Create a class named Visitor with a static int field total initialized to 0. In the constructor, increment total and print its value. In the main method, create three Visitor objects one after another and show that the counter retains its value across objects.
Show answer & explanation
Answer:
class Visitor {
    static int total = 0;

    Visitor() {
        total++;
        System.out.println(total);
    }

    public static void main(String[] args) {
        Visitor v1 = new Visitor();
        Visitor v2 = new Visitor();
        Visitor v3 = new Visitor();
    }
}
Explanation: 1) The static field total gets memory only once for the whole class, not per object. 2) Creating v1 runs the constructor: total becomes 1 and prints 1. 3) Creating v2 runs the constructor again on the same shared variable: total becomes 2 and prints 2. 4) Creating v3 makes total 3 and prints 3. 5) Because total is static, each object's constructor modifies the same copy, so the output is 1, 2, 3 on separate lines.

String Methods

Q61.Easy
Write a Java program named StringBlankCheckExample.java that demonstrates the String isEmpty() method. Create two strings: one empty string and one containing the text "chennai". Print the result of calling isEmpty() on each string.
Show answer & explanation
Answer:
public class StringBlankCheckExample {
    public static void main(String[] args) {
        String s1 = "";
        String s2 = "chennai";

        System.out.println(s1.isEmpty());
        System.out.println(s2.isEmpty());
    }
}
Explanation: 1. Declare s1 as an empty string "" and s2 as "chennai". 2. s1.isEmpty() returns true because its length is 0. 3. s2.isEmpty() returns false because it has 7 characters. 4. The program prints true on the first line and false on the second line.
Q62.Easy
Write a Java program that checks whether a string starts with an empty string. Use the string "New Delhi" and the startsWith method. If it does, print "The string starts with the empty string." otherwise print "The string does not start with the empty string."
Show answer & explanation
Answer:
public class StartsWithExample {
    public static void main(String[] args) {
        String str = "New Delhi";
        if (str.startsWith("")) {
            System.out.println("The string starts with the empty string.");
        } else {
            System.out.println("The string does not start with the empty string.");
        }
    }
}
Explanation: 1. Declare a string variable 'str' and assign it the value "New Delhi". 2. Use the startsWith method with an empty string argument: str.startsWith(""). 3. In Java, every string starts with an empty string, so this returns true. 4. The if condition is true, so the program prints "The string starts with the empty string."
Q63.Easy
Write a Java program that stores the string "namaste duniya" in a variable, converts it to uppercase using the toUpperCase() method, and prints the result.
Show answer & explanation
Answer:
public class UpperDemo {
    public static void main(String[] args) {
        String s = "namaste duniya";
        String upper = s.toUpperCase();
        System.out.println(upper);
    }
}
Explanation: 1) Create a class UpperDemo with a main method. 2) Declare a String variable s and assign "namaste duniya". 3) Call s.toUpperCase() which returns a new string with all letters in uppercase; store it in upper. 4) Print upper using System.out.println, which outputs NAMASTE DUNIYA.
Q64.Easy
Write a Java program that demonstrates the String trim() method. Create a class named TrimDemo.java. In main(), declare a String s = "   namaste india   ". First print s concatenated with "welcome" (without trim), then print s.trim() concatenated with "welcome" (with trim).
Show answer & explanation
Answer:
public class TrimDemo {
    public static void main(String[] args) {
        String s = "   namaste india   ";
        System.out.println(s + "welcome");
        System.out.println(s.trim() + "welcome");
    }
}
Explanation: 1) Declare s with leading and trailing spaces: " namaste india ". 2) s + "welcome" keeps the spaces, so output is ' namaste india welcome'. 3) s.trim() removes leading and trailing whitespace, giving "namaste india". 4) Concatenating with "welcome" gives 'namaste indiwelcome'... precisely 'namaste indiawelcome'. 5) So the second line prints without the surrounding spaces.
Q65.Easy
Write a Java program to demonstrate the behavior of compareTo() when one of the strings is empty. Create three strings: s1 = "Java", s2 = "", and s3 = "Programming". Print the results of s1.compareTo(s2) and s2.compareTo(s3). Observe that comparing with an empty string returns the length of the non-empty string (with sign depending on order). Name the file EmptyStringCompare.java.
Show answer & explanation
Answer:
public class EmptyStringCompare {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = "";
        String s3 = "Programming";
        System.out.println(s1.compareTo(s2));
        System.out.println(s2.compareTo(s3));
    }
}
Explanation: 1. s1 = "Java" (length 4), s2 = "" (empty), s3 = "Programming" (length 11). 2. s1.compareTo(s2): since s2 is empty, returns length of s1 = 4. 3. s2.compareTo(s3): since s2 is empty, returns - (length of s3) = -11. 4. Output: first line 4, second line -11.
Q66.Easy
Write a Java program to check whether the compareTo() method is case-sensitive. Create two strings: one in uppercase and one in lowercase, both containing the same letters in the same order. Compare them using compareTo() and print the result. If the output is 0, the method is not case-sensitive; otherwise, it is case-sensitive. Name the file CaseSensitiveCompare.java.
Show answer & explanation
Answer:
public class CaseSensitiveCompare {
    public static void main(String[] args) {
        String str1 = "WELCOME TO INDIA";
        String str2 = "welcome to india";
        System.out.println(str1.compareTo(str2));
    }
}
Explanation: 1. Create a string str1 in uppercase: "WELCOME TO INDIA". 2. Create a string str2 in lowercase: "welcome to india". 3. Use str1.compareTo(str2) to compare them lexicographically. 4. Since 'W' (87) and 'w' (119) have different Unicode values, the result is negative (87 - 119 = -32). 5. Print the result. A non-zero output indicates that compareTo() is case-sensitive.
Q67.Easy
Write a Java program: Java String contains() Method Example. FileName: ContainsExample.java
Show answer & explanation
Answer:
public class ContainsExample {
    public static void main(String[] args) {
        String sentence = "India is a beautiful country";
        System.out.println(sentence.contains("is a"));
        System.out.println(sentence.contains("beautiful"));
        System.out.println(sentence.contains("hello"));
    }
}
Explanation: 1. Define a class ContainsExample with a main method. 2. Create a string variable sentence with value "India is a beautiful country". 3. Use sentence.contains("is a") to check if the substring "is a" is present. It returns true, so print true. 4. Use sentence.contains("beautiful") to check if "beautiful" is present. It returns true, so print true. 5. Use sentence.contains("hello") to check if "hello" is present. It returns false, so print false. 6. The program demonstrates the contains() method of the String class.
Q68.Easy
Write a Java program that demonstrates the String toUpperCase() and toLowerCase() methods. Create a String variable holding the name "Rohit", print its uppercase form, then its lowercase form, and finally print the original string to show it is unchanged.
Show answer & explanation
Answer:
public class StringCaseDemo
{
    public static void main(String[] args)
    {
        String name = "Rohit";
        System.out.println(name.toUpperCase()); // ROHIT
        System.out.println(name.toLowerCase()); // rohit
        System.out.println(name);              // Rohit (original unchanged)
    }
}
Explanation: 1) Declare a String variable name = "Rohit". 2) name.toUpperCase() returns a new string "ROHIT" and prints it. 3) name.toLowerCase() returns a new string "rohit" and prints it. 4) Printing name again shows "Rohit" because String is immutable — the methods return new strings and do not modify the original.

String charAt()

Q69.Easy
Write a Java program that demonstrates the charAt() method. Create a String variable named 'city' and initialize it with "Mumbai". Use charAt() to retrieve the character at index 3 and print it. Also, demonstrate that accessing an invalid index throws StringIndexOutOfBoundsException by attempting to access index 10 inside a try-catch block and printing an appropriate message.
Show answer & explanation
Answer:
public class CharAtDemo {
    public static void main(String[] args) {
        String city = "Mumbai";
        char ch = city.charAt(3);
        System.out.println(ch);
        try {
            char invalid = city.charAt(10);
            System.out.println(invalid);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Index out of bounds: " + e.getMessage());
        }
    }
}
Explanation: 1. The program defines a class CharAtDemo with a main method. 2. It creates a String variable 'city' and assigns it the value "Mumbai". 3. It calls city.charAt(3), which returns the character at index 3 (0-based). In "Mumbai", index 0 is 'M', 1 is 'u', 2 is 'm', 3 is 'b', so it prints 'b'. 4. Then it attempts to access index 10, which is beyond the string length (6), so charAt throws StringIndexOutOfBoundsException. 5. The try-catch block catches the exception and prints a message indicating the index is out of bounds.
Q70.Easy
Write a Java program that prints the first and last characters of a string using the charAt() method. Use the string "Bharat is my country" and print the first character as: Character at 0 index is: <char> and the last character as: Character at last index is: <char>. Save the program in a file named FirstLastChar.java.
Show answer & explanation
Answer:
public class FirstLastChar {
    public static void main(String[] args) {
        String str = "Bharat is my country";
        int strLength = str.length();
        System.out.println("Character at 0 index is: " + str.charAt(0));
        System.out.println("Character at last index is: " + str.charAt(strLength - 1));
    }
}
Explanation: 1) Store the text in a String variable str. 2) Find its length with str.length() and save it in strLength. 3) The first character is at index 0, so print str.charAt(0). 4) The last character is at index strLength-1, so print str.charAt(strLength-1). 5) This prints the first and last characters of the string.
Q71.Easy
Write a Java program that prints the characters located at odd indices of a string using the charAt() method. Use the string "India is a great nation" and print each odd-index character in the format: Char at <index> place <character>. Save the program in a file named OddIndexChars.java.
Show answer & explanation
Answer:
public class OddIndexChars {
    public static void main(String[] args) {
        String str = "India is a great nation";
        for (int i = 0; i <= str.length() - 1; i++) {
            if (i % 2 != 0) {
                System.out.println("Char at " + i + " place " + str.charAt(i));
            }
        }
    }
}
Explanation: 1) Store the text in a String variable str. 2) Loop i from 0 to str.length()-1 so every index is visited. 3) Check if i % 2 != 0, i.e. the index is odd. 4) For odd indices, print the index and str.charAt(i). 5) Even indices are skipped, so only odd-position characters are printed.

String concat() method

Q72.Easy
Write a Java program that demonstrates the String concat() method by joining multiple string objects. Create three strings: "Namaste", "Bharat", and "Readers". First concatenate the first two strings and print the result. Then concatenate all three strings in a chain and print that result. Name the class ConcatDemo.
Show answer & explanation
Answer:
public class ConcatDemo {
    public static void main(String[] args) {
        String str1 = "Namaste";
        String str2 = "Bharat";
        String str3 = "Readers";
        // Concatenating two strings
        String str4 = str1.concat(str2);
        System.out.println(str4);
        // Concatenating multiple strings in a chain
        String str5 = str1.concat(str2).concat(str3);
        System.out.println(str5);
    }
}
Explanation: 1) Declare three String variables str1="Namaste", str2="Bharat", str3="Readers". 2) str1.concat(str2) returns a new string "NamasteBharat" and stores it in str4; print str4. 3) str1.concat(str2) gives "NamasteBharat", then .concat(str3) appends "Readers" giving "NamasteBharatReaders"; store in str5 and print it. 4) Output: first line NamasteBharat, second line NamasteBharatReaders.
Q73.Easy
Write a Java program that uses the concat() method to add a string at the beginning of another string. Create a string variable holding "Festival", then build a new string by calling concat() on the literal "Diwali is my " with the variable as argument, and print the result. Name the class ConcatBeginning.
Show answer & explanation
Answer:
public class ConcatBeginning
{
    public static void main(String[] args)
    {
        String str = "Festival";
        String s = "Diwali is my ".concat(str);
        System.out.println(s);
    }
}
Explanation: 1) Declare String str = "Festival". 2) The concat() method appends its argument to the string that invokes it, so to put text in front we invoke concat() on the prefix literal: "Diwali is my ".concat(str). 3) This returns a new string "Diwali is my Festival" (strings are immutable, the original is unchanged). 4) Store it in s and print it with System.out.println(s).
Q74.Easy
Write a Java program that demonstrates string concatenation using the concat() method. Create two strings, "Rohit " and "Sharma", join them with concat(), and print the result.
Show answer & explanation
Answer:
class TestConcatMethod {
 public static void main(String args[]) {
   String s1 = "Rohit ";
   String s2 = "Sharma";
   String s3 = s1.concat(s2);
   System.out.println(s3);
 }
}
Explanation: 1) Declare s1 = "Rohit " (note the trailing space) and s2 = "Sharma". 2) Call s1.concat(s2), which appends s2 to the end of s1 and returns a new string. 3) Store the result in s3, giving "Rohit Sharma". 4) Print s3, so the output is: Rohit Sharma.

String equals() method

Q75.Easy
Write a Java program that demonstrates comparing strings by content using the equals() method. Create four strings: s1 = "Rohit", s2 = "Rohit", s3 = new String("Rohit"), and s4 = "Kiran". Print the results of s1.equals(s2), s1.equals(s3), and s1.equals(s4) on separate lines.
Show answer & explanation
Answer:
public class StringEqualsDemo {
    public static void main(String[] args) {
        String s1 = "Rohit";
        String s2 = "Rohit";
        String s3 = new String("Rohit");
        String s4 = "Kiran";
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
        System.out.println(s1.equals(s4));
    }
}
Explanation: 1) s1 and s2 both refer to the literal "Rohit", so equals() compares content and returns true. 2) s3 is created with new String("Rohit"); it is a different object but has the same content, so s1.equals(s3) returns true. 3) s4 is "Kiran", which differs in content from "Rohit", so s1.equals(s4) returns false. 4) The program prints true, true, false on three separate lines.
Q76.Easy
Write a Java program that checks if a specific string is present in an ArrayList of strings using the equals() method. The list should contain: "Amit", "Priya", "Rahul", "Sneha". The string to search for is "Priya". If found, print "Priya is present".
Show answer & explanation
Answer:
import java.util.ArrayList;
public class EqualsExample3 {
    public static void main(String[] args) {
        String str1 = "Priya";
        ArrayList<String> list = new ArrayList<>();
        list.add("Amit");
        list.add("Priya");
        list.add("Rahul");
        list.add("Sneha");
        for (String str : list) {
            if (str.equals(str1)) {
                System.out.println("Priya is present");
            }
        }
    }
}
Explanation: 1. Create a string variable str1 with value "Priya". 2. Create an ArrayList of strings and add the four names. 3. Iterate over each string in the list using a for-each loop. 4. For each string, compare it with str1 using equals(). If they are equal, print "Priya is present". 5. Since "Priya" is in the list, the message is printed once.
Q77.Medium
Write a Java program that demonstrates the equals() method by comparing strings with objects of different types (Character, Integer, Double, Boolean) and then converting those objects to strings to show equality. Use the following values: String str = "b"; String str1 = "456"; String str2 = "78.12"; String str3 = "true"; Character c = new Character('b'); Integer i = new Integer(456); Double d = new Double(78.12); Boolean b = new Boolean(true). Print the results of str.equals(c), str1.equals(i), str2.equals(d), str3.equals(b), and then print the results after converting c, i, d, and b to strings using toString().
Show answer & explanation
Answer:
public class EqualsExample4 {
    public static void main(String[] args) {
        String str = "b";
        String str1 = "456";
        String str2 = "78.12";
        String str3 = "true";
        Character c = new Character('b');
        Integer i = new Integer(456);
        Double d = new Double(78.12);
        Boolean b = new Boolean(true);
        System.out.println(str.equals(c));
        System.out.println(str1.equals(i));
        System.out.println(str2.equals(d));
        System.out.println(str3.equals(b));
        System.out.println(str.equals(c.toString()));
        System.out.println(str1.equals(i.toString()));
        System.out.println(str2.equals(d.toString()));
        System.out.println(str3.equals(b.toString()));
    }
}
Explanation: 1. Create strings and wrapper objects with the given values. 2. Call equals() on each string, passing the wrapper object. Since the argument is not a String, equals() returns false. 3. Print these results: false, false, false, false. 4. Convert each wrapper object to a string using toString(). 5. Call equals() again with the string representation. Now the argument is a String with the same content, so equals() returns true. 6. Print these results: true, true, true, true.

String length() method

Q78.Easy
Write a Java program that uses the String length() method. Create two strings: one holding "hyderabad" and another holding "java". Print "string length is: " followed by the length of the first string, and then print "string length is: " followed by the length of the second string. Name the file LengthDemo.java.
Show answer & explanation
Answer:
public class LengthDemo {
    public static void main(String args[]) {
        String s1 = "hyderabad";
        String s2 = "java";
        System.out.println("string length is: " + s1.length());
        System.out.println("string length is: " + s2.length());
    }
}
Explanation: 1) Declare s1 = "hyderabad". Counting its characters h-y-d-e-r-a-b-a-d gives 9, so s1.length() is 9. 2) Declare s2 = "java". Counting j-a-v-a gives 4, so s2.length() is 4. 3) The first println prints: string length is: 9. 4) The second println prints: string length is: 4. 5) length() simply returns the total number of characters in the string.
Q79.Easy
Write a Java program that uses the String length() method to check whether a string is empty or not. Create a string variable holding the value "Bengaluru", and if its length is greater than 0, print "String is not empty and length is: " followed by its length. Then reassign the same variable to an empty string "", and if its length equals 0, print "String is empty now: " followed by its length. Name the file EmptyCheck.java.
Show answer & explanation
Answer:
public class EmptyCheck {
    public static void main(String[] args) {
        String city = "Bengaluru";
        if (city.length() > 0) {
            System.out.println("String is not empty and length is: " + city.length());
        }
        city = "";
        if (city.length() == 0) {
            System.out.println("String is empty now: " + city.length());
        }
    }
}
Explanation: 1) Declare a String variable city and assign "Bengaluru". 2) length() returns the number of characters, so city.length() is 9, which is > 0. 3) Hence the first if-block prints: String is not empty and length is: 9. 4) Reassign city to the empty string ""; its length is now 0. 5) The second if-block (length()==0) is true, so it prints: String is empty now: 0. 6) This shows length() can be used to test whether a string is empty.
Q80.Easy
Write a Java program that stores the name of an Indian city in a String variable and prints the number of characters in it using the String length() method. Use the city name "Chennai". The class should be named CityNameLength.
Show answer & explanation
Answer:
public class CityNameLength
{
    public static void main(String[] args)
    {
        String city = "Chennai";
        System.out.println(city.length());
    }
}
Explanation: 1) Declare a String variable city and assign it the value "Chennai". 2) The String class provides the length() method, which returns the number of characters in the string. 3) "Chennai" has 7 characters (C-h-e-n-n-a-i), so city.length() returns 7. 4) System.out.println prints that value, giving output 7.

This keyword

Q81.Easy
Write a Java program that demonstrates returning 'this' from a method. Create a class named Greeter with a method getGreeter() that returns 'this', and a method greet() that prints "Namaste India". In main(), call new Greeter().getGreeter().greet() so the message is printed.
Show answer & explanation
Answer:
class Greeter {
    Greeter getGreeter() {
        return this;
    }
    void greet() {
        System.out.println("Namaste India");
    }
}
class MainTest {
    public static void main(String args[]) {
        new Greeter().getGreeter().greet();
    }
}
Explanation: 1. getGreeter() has return type Greeter and returns 'this', the current object. 2. new Greeter() creates an object and getGreeter() returns that same object. 3. Because the returned value is a Greeter, we can immediately call .greet() on it (method chaining). 4. greet() prints "Namaste India". 5. Output: Namaste India.
Q82.Easy
Write a Java program that proves the 'this' keyword refers to the current class instance. Create a class named Student with a method show() that prints 'this'. In main(), create a Student object, print the object reference, then call show(). Both printed values must be the same reference ID.
Show answer & explanation
Answer:
class Student {
    void show() {
        System.out.println(this); // prints the same reference ID
    }
    public static void main(String args[]) {
        Student s = new Student();
        System.out.println(s); // prints the reference ID
        s.show();
    }
}
Explanation: 1. The class Student has a method show() that prints 'this', i.e., the reference of the object on which it is called. 2. In main(), we create one object s = new Student(). 3. System.out.println(s) prints the reference ID of s. 4. s.show() calls show() on the same object, so 'this' inside show() is the same reference. 5. Both lines print identical output like Student@1b6d3586, proving this == current object reference.
Q83.Easy
Write a Java program that stores a bank account holder's account number, name and balance using a constructor, where the constructor parameters have the SAME names as the instance variables, so the 'this' keyword must be used to resolve the shadowing. Print the details using a display() method.
Show answer & explanation
Answer:
class Account {
    long accNo;
    String holderName;
    double balance;

    Account(long accNo, String holderName, double balance) {
        this.accNo = accNo;
        this.holderName = holderName;
        this.balance = balance;
    }

    void display() {
        System.out.println(accNo + " " + holderName + " " + balance);
    }

    public static void main(String[] args) {
        Account a = new Account(20231001L, "Meera", 7500.50);
        a.display();
    }
}
Explanation: 1) The class Account has instance variables accNo, holderName, balance. 2) The constructor parameters use the SAME names, so inside the constructor the parameter shadows the field. 3) Writing accNo = accNo would just assign the parameter to itself; to reach the object's field we use this.accNo = accNo, this.holderName = holderName, this.balance = balance. 4) display() prints the stored values. 5) main() creates Account(20231001L, "Meera", 7500.50) and calls display(), giving output: 20231001 Meera 7500.5
Q84.Easy
Write a Java program that stores an employee's ID, name and salary using a constructor, where the constructor parameters have DIFFERENT names from the instance variables, so the 'this' keyword is not required. Print the details using a display() method.
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;
    double salary;

    Employee(int id, String nm, double sal) {
        empId = id;
        empName = nm;
        salary = sal;
    }

    void display() {
        System.out.println(empId + " " + empName + " " + salary);
    }

    public static void main(String[] args) {
        Employee e = new Employee(101, "Ravi", 45000.0);
        e.display();
    }
}
Explanation: 1) The class Employee has instance variables empId, empName, salary. 2) The constructor parameters are named id, nm, sal — different from the field names. 3) Because the names differ, there is no shadowing, so we can directly write empId = id; empName = nm; salary = sal; without using 'this'. 4) display() prints the three values. 5) main() creates an Employee(101, "Ravi", 45000.0) and calls display(), giving output: 101 Ravi 45000.0

Thread Interruption

Q85.Medium
Write a Java program that demonstrates the interrupt() method. Create a thread that sleeps for 5 milliseconds in a loop 100 times, and catch InterruptedException to print a message. After the loop, print the thread name and that it has finished executing. Use a custom thread class named MyThread that extends Thread and starts in its constructor. The thread should be part of a ThreadGroup named 'GroupA'. After starting the thread, interrupt it from the main thread after a short delay. FileName: InterruptDemo.java
Show answer & explanation
Answer:
public class InterruptDemo {
    public static void main(String[] args) {
        ThreadGroup group = new ThreadGroup("GroupA");
        MyThread t = new MyThread("Worker", group);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
    }
}

class MyThread extends Thread {
    MyThread(String name, ThreadGroup group) {
        super(group, name);
        start();
    }

    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException caught: " + e);
            }
        }
        System.out.println(Thread.currentThread().getName() + " thread has finished executing");
    }
}
Explanation: 1. Create a ThreadGroup named 'GroupA'. 2. Create a MyThread object with name 'Worker' and the group; its constructor calls start(). 3. In run(), loop 100 times, each time sleeping 5 ms inside a try-catch for InterruptedException. 4. If interrupted during sleep, the catch prints the exception message. 5. After the loop, print the thread's name and that it has finished. 6. In main, after starting the thread, sleep 10 ms then call interrupt() on it, causing an InterruptedException in the thread.
Q86.Medium
Write a Java program that demonstrates interrupting a thread which is sleeping. The thread should sleep for 1500 milliseconds and then print "work done". In the main method, start the thread and immediately interrupt it. Inside the run method, catch the InterruptedException and rethrow it as a RuntimeException with the message "Thread was interrupted: " followed by the exception. The program should compile and run, showing the propagated exception.
Show answer & explanation
Answer:
class InterruptDemo extends Thread {
    public void run() {
        try {
            Thread.sleep(1500);
            System.out.println("work done");
        } catch (InterruptedException e) {
            throw new RuntimeException("Thread was interrupted: " + e);
        }
    }

    public static void main(String[] args) {
        InterruptDemo t = new InterruptDemo();
        t.start();
        try {
            t.interrupt();
        } catch (Exception e) {
            System.out.println("Exception handled " + e);
        }
    }
}
Explanation: 1. The class InterruptDemo extends Thread and overrides run(). 2. Inside run(), the thread sleeps for 1500 ms; if interrupted during sleep, an InterruptedException is thrown. 3. The catch block wraps the InterruptedException in a RuntimeException with a descriptive message, propagating it (so the thread terminates). 4. In main(), a new InterruptDemo object is created and started. 5. Immediately after starting, interrupt() is called on the thread, causing the sleep to be interrupted. 6. The RuntimeException propagates out of run(), and the thread stops; the main thread's try-catch around interrupt() does not catch this exception because it occurs in the child thread.
Q87.Medium
Write a Java program that demonstrates interrupting a thread which does NOT stop working. In run(), the thread calls Thread.sleep(1500) and then prints "work done". If an InterruptedException occurs, catch it and print "Interrupted caught: " followed by the exception. After the try-catch, always print "thread continues running". In main, start the thread and immediately call interrupt() on it. Name the class HandleInterruptDemo.
Show answer & explanation
Answer:
class HandleInterruptDemo extends Thread {
    public void run() {
        try {
            Thread.sleep(1500);
            System.out.println("work done");
        } catch (InterruptedException e) {
            System.out.println("Interrupted caught: " + e);
        }
        System.out.println("thread continues running");
    }

    public static void main(String args[]) {
        HandleInterruptDemo t1 = new HandleInterruptDemo();
        t1.start();
        t1.interrupt();
    }
}
Explanation: 1) Class HandleInterruptDemo extends Thread and overrides run(). 2) Inside run(), the thread calls Thread.sleep(1500), so it enters the sleeping (timed waiting) state. 3) In main, t1.start() begins the thread and t1.interrupt() is called almost immediately. 4) Because the thread is sleeping, interrupt() causes sleep() to throw InterruptedException, which is caught; the catch block prints "Interrupted caught: " plus the exception. 5) The sleep is broken early, so "work done" is NOT printed, but execution continues after the catch and prints "thread continues running". 6) This shows that handling the exception lets the thread keep working instead of stopping.
Q88.Medium
Write a Java program that demonstrates interrupting a thread which is NOT in sleeping or waiting state. The thread should print the numbers 1 to 4 in its run() method. In main, start the thread and immediately call interrupt() on it. Since the thread is not sleeping or waiting, the interrupt only sets the interrupted flag to true (it does not throw an exception), and the thread continues printing normally. Name the class FlagInterruptDemo.
Show answer & explanation
Answer:
class FlagInterruptDemo extends Thread {
    public void run() {
        for (int i = 1; i <= 4; i++) {
            System.out.println(i);
        }
    }

    public static void main(String args[]) {
        FlagInterruptDemo t1 = new FlagInterruptDemo();
        t1.start();
        t1.interrupt();
    }
}
Explanation: 1) Class FlagInterruptDemo extends Thread and overrides run() to print 1 to 4. 2) In main, a thread object t1 is created and started with start(). 3) interrupt() is called on t1. Because t1 is not sleeping or waiting, no InterruptedException is thrown; only the interrupted status flag is set to true. 4) The run() loop does not check the flag, so it simply prints 1, 2, 3, 4 normally. 5) This shows that interrupt() alone does not stop a running thread; the programmer must check the flag to stop it.

Other questions

Q89.Easy
Write a Java program that demonstrates a final variable. Declare a final integer variable called 'marks' initialized to 72 inside a class 'FinalMarksDemo'. Write a method 'update()' that attempts to reassign marks to 90 (this should cause a compile-time error, so keep it commented out with a note). In main, create an object and print the value of marks.
Show answer & explanation
Answer:
public class FinalMarksDemo {
    // declaring final variable
    final int marks = 72;

    void update() {
        // reassigning value to marks variable
        // gives compile time error
        // marks = 90;
        System.out.println("Marks: " + marks);
    }

    public static void main(String[] args) {
        FinalMarksDemo obj = new FinalMarksDemo();
        obj.update();
    }
}
Explanation: 1. 'final int marks = 72;' declares a final variable, so it can be assigned only once. 2. Any attempt to reassign (marks = 90) inside update() would give a compile-time error, so it is commented out. 3. main() creates an object of FinalMarksDemo and calls update(). 4. update() prints the value 72, which is the only value marks can hold.
Q90.Easy
Write a Java program that demonstrates a final variable. Declare a final int variable named maxMarks with value 80 inside a class named Student. In a method called update(), try to assign 95 to maxMarks. Create an object of Student in main and call update(). (The program will fail to compile because a final variable cannot be reassigned.)
Show answer & explanation
Answer:
class Student {
    final int maxMarks = 80; // final variable
    void update() {
        maxMarks = 95; // compile-time error: cannot assign a value to final variable
    }
    public static void main(String args[]) {
        Student obj = new Student();
        obj.update();
    }
}
Explanation: 1) 'final int maxMarks = 80;' makes maxMarks a constant. 2) Inside update(), 'maxMarks = 95;' tries to change it. 3) Java forbids reassigning a final variable, so the compiler reports an error. 4) main() creates a Student object and calls update(), but compilation fails before running. 5) Hence the program shows that a final variable's value can never be changed once assigned.
Q91.Easy
Write a Java program that creates the String str = "Learning Java is fun!", creates a char array of size 30, and sets srcBeginIndex = 9, srcEndIndex = 9, dstBeginIndex = 3. It calls str.getChars(srcBeginIndex, srcEndIndex, chArr, dstBeginIndex) inside a try-catch, prints the char array, and then prints the line "The getChars() method prints nothing as start and end indices are equal."
Show answer & explanation
Answer:
public class StringGetCharsDemo {
    public static void main(String[] args) {
        String str = "Learning Java is fun!";
        char[] chArr = new char[30];
        int srcBeginIndex = 9;
        int srcEndIndex = 9;
        int dstBeginIndex = 3;
        try {
            str.getChars(srcBeginIndex, srcEndIndex, chArr, dstBeginIndex);
            System.out.println(chArr);
        } catch (Exception excpn) {
            System.out.println(excpn);
        }
        System.out.println("The getChars() method prints nothing as start and end indices are equal.");
    }
}
Explanation: 1. A char array of size 30 is created; all elements are initially the null character '\u0000'. 2. getChars copies characters from index srcBeginIndex up to srcEndIndex - 1. 3. Here srcBeginIndex = srcEndIndex = 9, so the range is empty (9 to 8) and nothing is copied. 4. Printing the char array shows only blank/null characters, so the output appears empty. 5. The final println confirms that equal start and end indices cause getChars() to copy nothing.
Q92.Easy
Write a Java program to demonstrate that an instance variable is NOT shared between objects. Create a class named Ticket with an instance variable named serial initialized to 0. In the constructor, increment serial and print it. In the main method, create three Ticket objects one after another. Show that each object prints 1, because each object gets its own copy of the instance variable.
Show answer & explanation
Answer:
class Ticket {
    int serial = 0; // instance variable: new memory for every object

    Ticket() {
        serial++; // increments only this object's copy
        System.out.println(serial);
    }

    public static void main(String args[]) {
        Ticket t1 = new Ticket();
        Ticket t2 = new Ticket();
        Ticket t3 = new Ticket();
    }
}
Explanation: 1) 'serial' is an instance variable, so every new Ticket object gets its own fresh copy initialized to 0. 2) When t1 is created, its constructor increments its own serial from 0 to 1 and prints 1. 3) When t2 is created, it gets a brand-new copy of serial = 0, increments it to 1 and prints 1. 4) t3 behaves the same way and prints 1. 5) Output is 1, 1, 1 — proving the instance variable is not shared between objects.
Q93.Easy
Write a Java program that demonstrates the use of a static method. Create a class named Employee with fields empId (int) and empName (String), and a static field company set to "Sunrise Tech". Add a static method changeCompany() that sets company to "Sunrise Infotech". Add a constructor to initialize empId and empName, and a display() method that prints empId, empName and company. In the main method, call Employee.changeCompany() without creating an object, then create three Employee objects (101, "Ravi"; 102, "Meera"; 103, "Anil") and call display() on each.
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;
    static String company = "Sunrise Tech";

    static void changeCompany() {
        company = "Sunrise Infotech";
    }

    Employee(int id, String name) {
        empId = id;
        empName = name;
    }

    void display() {
        System.out.println(empId + " " + empName + " " + company);
    }
}

public class TestStaticMethod {
    public static void main(String[] args) {
        Employee.changeCompany();
        Employee e1 = new Employee(101, "Ravi");
        Employee e2 = new Employee(102, "Meera");
        Employee e3 = new Employee(103, "Anil");
        e1.display();
        e2.display();
        e3.display();
    }
}
Explanation: 1) The static field company is shared by all Employee objects and starts as "Sunrise Tech". 2) The static method changeCompany() is called on the class itself (Employee.changeCompany()) before any object is created, so it works without an instance. 3) It updates the shared static field to "Sunrise Infotech". 4) Three objects are created with their own empId and empName values. 5) display() prints each object's own fields plus the shared company value, so all three lines show "Sunrise Infotech".
Q94.Easy
Write a Java program named Greeter.java that demonstrates a static method. The program should have a main method that calls a static method named greet() without creating any object of the class. The greet() method should print the line: Hello from a static method!
Show answer & explanation
Answer:
public class Greeter {
    public static void main(String[] args) {
        greet();
    }

    static void greet() {
        System.out.println("Hello from a static method!");
    }
}
Explanation: 1. Define a class Greeter with a main method (which is itself static). 2. Inside main, call greet() directly using the class name implicitly — no object is created. 3. Declare greet() with the static keyword so it belongs to the class, not to an instance. 4. greet() prints the required message. 5. Because greet() is static, the call from the static main method works without any object.
Q95.Easy
Write a Java program that uses a static method to compute the square of a given number. The static method square(int x) should return x*x, and main should call it for the number 7 and print the result.
Show answer & explanation
Answer:
class Calculator {
    static int square(int x) {
        return x * x;
    }

    public static void main(String[] args) {
        int result = Calculator.square(7);
        System.out.println(result);
    }
}
Explanation: 1) The method square is declared static, so it can be called using the class name without creating an object. 2) square(7) computes 7 * 7 = 49 and returns it. 3) main stores the returned value in result and prints it. 4) Output: 49.
Q96.Easy
Write a Java program with a class named Shop that has a static block printing "Shop class loaded" and a main method printing "Welcome to the shop". Show that the static block runs before the main method.
Show answer & explanation
Answer:
public class Shop {
    static {
        System.out.println("Shop class loaded");
    }
    public static void main(String[] args) {
        System.out.println("Welcome to the shop");
    }
}
Explanation: 1) The static block of class Shop is executed once when the class is loaded, before main() runs. 2) So the first output is "Shop class loaded". 3) Then the JVM calls main(), which prints "Welcome to the shop". 4) Final output order: Shop class loaded, then Welcome to the shop.
Q97.Easy
Write a Java program that demonstrates that references have a type. Declare a variable of a primitive type int named marks and assign it the value 45. Then declare a reference variable of type Student named s1 (do not assign an object to it). Print the value of marks and print whether s1 is null.
Show answer & explanation
Answer:
class Student {
}

class Main {
    public static void main(String[] args) {
        int marks = 45;
        Student s1;
        System.out.println("Marks: " + marks);
        s1 = null;
        System.out.println("Is s1 null? " + (s1 == null));
    }
}
Explanation: Step 1: int marks = 45; declares a primitive variable of type int and stores the value 45. Step 2: Student s1; declares a reference variable whose type is Student; it can refer only to Student objects (or null). Step 3: Assign s1 = null; so the reference points to no object. Step 4: Print marks, which outputs 45. Step 5: Check s1 == null, which is true, and print the result. Step 6: This shows variables have types: marks is primitive int, while s1 is a reference of type Student.
Q98.Easy
Write a Java program that demonstrates that an object has a type: an object is an instance of a particular Java class, but it is also an instance of its superclass. Create a superclass Vehicle and a subclass Car that extends Vehicle. In the main method, create a Car object and assign it to a Vehicle reference. Use the instanceof operator to check whether the object is an instance of Car and also an instance of Vehicle, and print the results.
Show answer & explanation
Answer:
class Vehicle {
}

class Car extends Vehicle {
    public static void main(String[] args) {
        Vehicle v = new Car();
        System.out.println("Is the object an instance of Car? " + (v instanceof Car));
        System.out.println("Is the object an instance of Vehicle? " + (v instanceof Vehicle));
    }
}
Explanation: Step 1: Define a superclass Vehicle with no members. Step 2: Define a subclass Car that extends Vehicle, so a Car object is also a Vehicle. Step 3: In main, create a Car object and store it in a Vehicle reference v (upcasting). Step 4: v instanceof Car is true because the actual object is a Car. Step 5: v instanceof Vehicle is also true because Car is a subclass of Vehicle, so every Car is a Vehicle. Step 6: The program prints true for both checks, showing an object is an instance of its class and of its superclass.
Q99.Easy
Write a Java program that demonstrates static binding (early binding). Create a class Fan with a private method spin() that prints "Fan is spinning...". In main, create a Fan object and call spin() from within the class so that the compiler fixes the method call at compile time.
Show answer & explanation
Answer:
class Fan {
    private void spin() {
        System.out.println("Fan is spinning...");
    }

    public static void main(String[] args) {
        Fan f = new Fan();
        f.spin();
    }
}
Explanation: 1) Fan declares a private method spin() that prints "Fan is spinning...". 2) Private methods cannot be overridden, so the compiler knows exactly which method is called. 3) In main, a Fan object f is created. 4) The call f.spin() is resolved by the compiler at compile time (early binding). 5) Running the program prints "Fan is spinning...". 6) Because the method type is fixed at compile time, this is static binding.
Q100.Easy
Write a Java program that demonstrates dynamic binding (late binding). Create a base class Vehicle with a method start() that prints "Vehicle is starting...", and a subclass Car that overrides start() to print "Car is starting with a key...". In main, assign a Car object to a Vehicle reference and call start() to show that the method is resolved at run-time.
Show answer & explanation
Answer:
class Vehicle {
    void start() {
        System.out.println("Vehicle is starting...");
    }
}

class Car extends Vehicle {
    @Override
    void start() {
        System.out.println("Car is starting with a key...");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.start();
    }
}
Explanation: 1) Vehicle defines start() printing "Vehicle is starting...". 2) Car extends Vehicle and overrides start() to print "Car is starting with a key...". 3) In main, a Car object is assigned to a Vehicle reference (upcasting). 4) The compiler only knows the reference type Vehicle, so the call v.start() cannot be fixed at compile time. 5) At run-time the JVM looks at the actual object (Car) and invokes Car's overridden start(), printing "Car is starting with a key...". 6) This run-time method resolution is dynamic (late) binding.
12345

Get In Touch

INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India

contact@intmatedtech.com

TestMyIndia All India Rank