Coding Questions Questions

Question Bank › Technical › Java › Coding Questions

12345

Other questions

Q301.Easy
Write a Java program that demonstrates the use of a break statement inside an inner loop. The program should have an outer loop iterating from 1 to 4 and an inner loop iterating from 1 to 4. When the outer loop variable is 3 and the inner loop variable is 2, break out of the inner loop only. Otherwise, print the values of the outer and inner loop variables separated by a space.
Show answer & explanation
Answer:
public class InnerBreakDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 4; j++) {
                if (i == 3 && j == 2) {
                    break;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}
Explanation: 1. The outer loop runs with i from 1 to 4. 2. The inner loop runs with j from 1 to 4. 3. Inside the inner loop, we check if i==3 and j==2. If true, 'break;' exits only the inner loop, and the outer loop continues with the next i. 4. Otherwise, we print i and j separated by a space. 5. Because the break only affects the inner loop, when i=3 and j=2, the inner loop terminates, and the outer loop proceeds to i=4. 6. The program prints all pairs (i,j) except (3,2) and any pairs after (3,2) in the inner loop for i=3 (i.e., (3,3) and (3,4) are skipped).
Q302.Easy
Write a Java program that reads the data of two files, source1.txt and source2.txt, and writes their combined content into a third file called merged.txt using SequenceInputStream. After copying all bytes, print "Done" to the console and close all the streams.
Show answer & explanation
Answer:
import java.io.*;

public class MergeFiles {
    public static void main(String[] args) throws Exception {
        FileInputStream fin1 = new FileInputStream("source1.txt");
        FileInputStream fin2 = new FileInputStream("source2.txt");
        FileOutputStream fout = new FileOutputStream("merged.txt");

        SequenceInputStream sis = new SequenceInputStream(fin1, fin2);

        int i;
        while ((i = sis.read()) != -1) {
            fout.write(i);
        }

        sis.close();
        fout.close();
        fin1.close();
        fin2.close();

        System.out.println("Done");
    }
}
Explanation: 1. Open FileInputStreams for source1.txt and source2.txt and a FileOutputStream for merged.txt. 2. Wrap the two input streams in a SequenceInputStream, which reads source1.txt fully and then source2.txt. 3. Loop with sis.read() until -1, writing each byte to fout so merged.txt contains the concatenation of both files. 4. Close the SequenceInputStream, the output stream and both input streams. 5. Print "Done" to confirm the copy finished.
Q303.Easy
Write a Java program that demonstrates throwing an unchecked exception. Create a class named VotingCheck with a static method verify(int age). If age is less than 18, throw a new ArithmeticException with the message "Citizen is not eligible to vote"; otherwise print "Citizen is eligible to vote!!". In main(), call verify(15) and then print "rest of the code...".
Show answer & explanation
Answer:
public class VotingCheck {
    // method to check voting eligibility
    public static void verify(int age) {
        if (age < 18) {
            // throw unchecked ArithmeticException if not eligible
            throw new ArithmeticException("Citizen is not eligible to vote");
        } else {
            System.out.println("Citizen is eligible to vote!!");
        }
    }

    // main method
    public static void main(String args[]) {
        // calling the method
        verify(15);
        System.out.println("rest of the code...");
    }
}
Explanation: 1. ArithmeticException is an unchecked exception, so verify() does not need a throws clause. 2. verify(15) receives age = 15, which is less than 18. 3. The if condition is true, so 'throw new ArithmeticException("Citizen is not eligible to vote")' is executed. 4. The exception propagates out of verify() to main(), where it is not caught, so the program terminates abnormally. 5. Because the exception is uncaught, the line printing "rest of the code..." is never reached.
Q304.Easy
Write a Java program where the `main` method is placed in a class different from the class being used. Create a class `Employee` with an `int` field `empId` and a `String` field `empName` (do not assign any values). In another class `TestEmployee` that contains the `main` method, create one `Employee` object and print its `empId` and `empName` on separate lines.
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;
}

class TestEmployee {
    public static void main(String args[]) {
        Employee e1 = new Employee();
        System.out.println(e1.empId);
        System.out.println(e1.empName);
    }
}
Explanation: 1. Class `Employee` defines instance fields `int empId` and `String empName` with no explicit initialization. 2. Class `TestEmployee` holds the `main` method, showing that the entry point can live in a different class from the class being used. 3. `new Employee()` creates an object; since no values are assigned, fields take default values: `empId` = 0 and `empName` = null. 4. `System.out.println(e1.empId);` prints `0`. 5. `System.out.println(e1.empName);` prints `null`. 6. If both classes are in one source file, the file should be named `TestEmployee.java` because that class contains `main`.
Q305.Easy
Write a Java program that demonstrates initializing an object through a reference variable. Create a class named `Book` with two fields: an `int` field `pages` and a `String` field `title`. In a separate class `TestBook` containing the `main` method, create one `Book` object, assign `pages = 250` and `title = "Wings of Fire"` using the reference variable, then print both members separated by a space.
Show answer & explanation
Answer:
class Book {
    int pages;
    String title;
}

class TestBook {
    public static void main(String args[]) {
        Book b1 = new Book();
        b1.pages = 250;
        b1.title = "Wings of Fire";
        System.out.println(b1.pages + " " + b1.title);
    }
}
Explanation: 1. The class `Book` declares two instance fields: `int pages` and `String title`; no values are set yet, so they hold defaults (0 and null). 2. In `main`, `new Book()` creates an object on the heap and its reference is stored in `b1`. 3. `b1.pages = 250;` stores 250 into the object's `pages` field through the reference variable. 4. `b1.title = "Wings of Fire";` stores the string into the object's `title` field. 5. `System.out.println(b1.pages + " " + b1.title);` reads both fields via the reference and prints `250 Wings of Fire`.
Q306.Easy
Write a Java program that demonstrates the use of an anonymous object. Create a class named FactorialCalc with a method computeFact(int n) that prints the factorial of n. In the main method, call computeFact(6) using an anonymous object (i.e., without storing the object in a reference variable).
Show answer & explanation
Answer:
class FactorialCalc {
    void computeFact(int n) {
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }
        System.out.println("factorial is " + fact);
    }

    public static void main(String args[]) {
        new FactorialCalc().computeFact(6); // calling method with anonymous object
    }
}
Explanation: 1. Define class FactorialCalc with method computeFact(int n). 2. Inside computeFact, initialize fact = 1 and loop i from 1 to n, multiplying fact by i each time. 3. Print the result as "factorial is " + fact. 4. In main, use 'new FactorialCalc().computeFact(6)' — the object is created and used immediately without a reference variable (anonymous object). 5. For n=6, fact = 1*2*3*4*5*6 = 720, so output is: factorial is 720.
Q307.Easy
Write a Java program that joins two strings using the + operator. Create the string "Virat" and the string " Kohli" and combine them into one string, then print it.
Show answer & explanation
Answer:
class TestConcatOperator {
 public static void main(String args[]) {
   String s = "Virat" + " Kohli";
   System.out.println(s);
 }
}
Explanation: 1) The + operator between two string literals performs string concatenation. 2) "Virat" + " Kohli" produces the new string "Virat Kohli". 3) This combined string is stored in variable s. 4) System.out.println(s) prints: Virat Kohli.
Q308.Easy
Write a Java program that concatenates two strings using the StringBuilder class and its append() method. Create a StringBuilder with "Vanakkam" and another with " India", append the second to the first, and print the resulting string. Name the class BuildGreet.
Show answer & explanation
Answer:
public class BuildGreet
{
    public static void main(String args[])
    {
        StringBuilder s1 = new StringBuilder("Vanakkam");  // String 1
        StringBuilder s2 = new StringBuilder(" India");    // String 2
        StringBuilder s = s1.append(s2);   // String 3 stores the result
        System.out.println(s.toString());  // Displays result
    }
}
Explanation: 1) Create s1 = "Vanakkam" and s2 = " India" as StringBuilder objects. 2) s1.append(s2) adds the contents of s2 to the end of s1; StringBuilder is mutable so s1 itself is modified. 3) append() returns the same StringBuilder object, so s refers to the updated s1. 4) The content is now "Vanakkam India" (the leading space in s2 is kept). 5) s.toString() converts it to a String and println prints: Vanakkam India
Q309.Easy
Write a Java program that concatenates two strings using the String.format() method with the %s format specifier. Create two String objects: one holding "Namaste" and another holding " Bharat", then use String.format("%s%s", ...) to join them and print the result. Name the class GreetFormat.
Show answer & explanation
Answer:
public class GreetFormat
{
    public static void main(String args[])
    {
        String s1 = new String("Namaste");   // String 1
        String s2 = new String(" Bharat");   // String 2
        String s = String.format("%s%s", s1, s2);  // String 3 stores the result
        System.out.println(s);   // Displays result
    }
}
Explanation: 1) Create s1 = "Namaste" and s2 = " Bharat" as String objects. 2) Call String.format("%s%s", s1, s2): each %s is replaced by the corresponding argument in order. 3) So the first %s becomes "Namaste" and the second %s becomes " Bharat". 4) The combined string is "Namaste Bharat" (the leading space in s2 is preserved). 5) Print it with System.out.println(s), which outputs: Namaste Bharat
Q310.Easy
Write a Java program that uses the String.join() method (Java 8+) to concatenate the strings "Ram" and "Lakshman" with a hyphen ("-") as the separator, and then print the resulting string. The program should output: Ram-Lakshman
Show answer & explanation
Answer:
public class JodhString {
    public static void main(String[] args) {
        String s1 = new String("Ram");
        String s2 = new String("Lakshman");
        String result = String.join("-", s1, s2);
        System.out.println(result);
    }
}
Explanation: 1. Create two String objects: s1 = "Ram" and s2 = "Lakshman". 2. Call String.join("-", s1, s2) which joins the strings with "-" as separator. 3. The method returns a new string "Ram-Lakshman". 4. Print the result, which outputs: Ram-Lakshman
Q311.Easy
Write a Java program that uses the StringJoiner class (Java 8+) to concatenate the strings "Namaste" and "Duniya" with a comma and a space as the delimiter, and then print the resulting string. The program should output: Namaste, Duniya
Show answer & explanation
Answer:
import java.util.StringJoiner;

public class DeshJoiner {
    public static void main(String[] args) {
        StringJoiner sj = new StringJoiner(", ");
        sj.add("Namaste");
        sj.add("Duniya");
        System.out.println(sj.toString());
    }
}
Explanation: 1. Import java.util.StringJoiner. 2. Create a StringJoiner object with delimiter ", ". 3. Add the strings "Namaste" and "Duniya" using the add() method. 4. The StringJoiner automatically inserts the delimiter between the added strings. 5. Convert to string using toString() and print, which outputs: Namaste, Duniya
Q312.Easy
Write a Java program that creates a List of Strings containing "red", "green", "blue" and uses the Collectors.joining() method (Java 8+) to join them into a single string separated by " - ". Print the resulting string.
Show answer & explanation
Answer:
import java.util.*;
import java.util.stream.Collectors;

public class JoinDemo {
    public static void main(String args[]) {
        List<String> colours = Arrays.asList("red", "green", "blue");
        String result = colours.stream().collect(Collectors.joining(" - "));
        System.out.println(result);
    }
}
Explanation: 1. Arrays.asList("red", "green", "blue") creates a fixed-size List of three strings. 2. colours.stream() converts the list into a Stream<String>. 3. collect(Collectors.joining(" - ")) concatenates the stream elements in order, inserting " - " between them. 4. The joined string is "red - green - blue". 5. System.out.println prints: red - green - blue.
Q313.Easy
Write a Java program where a parent class Vehicle has a String field named brand set to "Maruti", and a child class Car extends Vehicle and also declares a String field named brand set to "Hyundai". The child class should have a method showBrands() that prints the child's brand first and then the parent's brand using the super keyword. In main, create a Car object and call showBrands().
Show answer & explanation
Answer:
class Vehicle {
    String brand = "Maruti";
}

class Car extends Vehicle {
    String brand = "Hyundai";

    void showBrands() {
        System.out.println(brand);
        System.out.println(super.brand);
    }
}

public class TestSuperDemo {
    public static void main(String args[]) {
        Car c = new Car();
        c.showBrands();
    }
}
Explanation: 1. Vehicle declares field brand = "Maruti". 2. Car extends Vehicle and redeclares field brand = "Hyundai", hiding the parent field. 3. Inside showBrands(), plain 'brand' refers to Car's field, so it prints Hyundai. 4. 'super.brand' refers to the immediate parent Vehicle's field, so it prints Maruti. 5. main creates a Car object and calls showBrands(), giving output: Hyundai then Maruti.
Q314.Easy
Write a Java program that demonstrates using the super keyword to invoke a parent class method. Create a parent class Person with a method display() that prints "Person displays". Create a child class Student that extends Person and overrides display() to print "Student displays". Also add a method show() in Student that calls the parent's display() using super.display() and then calls the child's display(). In the main method, create a Student object and call show().
Show answer & explanation
Answer:
class Person {
    void display() {
        System.out.println("Person displays");
    }
}

class Student extends Person {
    @Override
    void display() {
        System.out.println("Student displays");
    }
    
    void show() {
        super.display();
        display();
    }
}

public class TestSuperMethod {
    public static void main(String[] args) {
        Student s = new Student();
        s.show();
    }
}
Explanation: 1. Define a parent class Person with a method display() that prints "Person displays". 2. Define a child class Student that extends Person and overrides display() to print "Student displays". 3. In Student, add a method show() that first calls super.display() to invoke the parent's version, then calls display() to invoke the child's overridden version. 4. In the main method, create a Student object and call show(). 5. Output: "Person displays" followed by "Student displays".
Q315.Easy
Write a Java program that demonstrates using the super keyword to invoke a parent class constructor. Create a parent class Vehicle with a constructor that prints "Vehicle is created". Create a child class Car that extends Vehicle, and its constructor should call the parent constructor using super() and then print "Car is created". In the main method, create an object of Car.
Show answer & explanation
Answer:
class Vehicle {
    Vehicle() {
        System.out.println("Vehicle is created");
    }
}

class Car extends Vehicle {
    Car() {
        super();
        System.out.println("Car is created");
    }
}

public class TestSuper {
    public static void main(String[] args) {
        Car c = new Car();
    }
}
Explanation: 1. Define a parent class Vehicle with a no-argument constructor that prints "Vehicle is created". 2. Define a child class Car that extends Vehicle. 3. In Car's constructor, use super() to explicitly call the parent class constructor, then print "Car is created". 4. In the main method, create a Car object, which triggers the constructor chain: first the parent constructor runs, then the child constructor. 5. Output: "Vehicle is created" followed by "Car is created".
Q316.Easy
Write a Java program to demonstrate that the compiler automatically inserts a call to super() in a constructor if there is no explicit call to super() or this(). Create a parent class 'LivingThing' with a no-argument constructor that prints "LivingThing created". Create a child class 'Human' that extends 'LivingThing' with a no-argument constructor that prints "Human created". In the main method, create an object of Human and observe the output.
Show answer & explanation
Answer:
class LivingThing {
    LivingThing() {
        System.out.println("LivingThing created");
    }
}

class Human extends LivingThing {
    Human() {
        System.out.println("Human created");
    }
}

public class TestSuperImplicit {
    public static void main(String[] args) {
        Human h = new Human();
    }
}
Explanation: 1. Define class LivingThing with a no-arg constructor that prints "LivingThing created". 2. Define class Human extending LivingThing with a no-arg constructor that prints "Human created". 3. The compiler automatically inserts super() as the first statement in Human's constructor. 4. When new Human() is executed, it first calls LivingThing's constructor, printing "LivingThing created", then prints "Human created". 5. Output: LivingThing created Human created
Q317.Easy
Write a Java program that shows how to write documentation comments for the javadoc tool. Create a class named `Calculator` in package `com.india` with a documentation comment describing the class. Add a method `square(int n)` that prints the square of `n`, and put a documentation comment above the method describing what it does.
Show answer & explanation
Answer:
package com.india;

/** This class is a user-defined class that contains one method square. */
public class Calculator {

    /** The square method prints the square of the given number */
    public static void square(int n) {
        System.out.println(n * n);
    }
}
Explanation: 1. The `package com.india;` statement places the class in a package, which javadoc records in the generated API document. 2. A documentation comment `/** ... */` placed just before the class declaration describes the class; javadoc uses it as the class description. 3. The method `square(int n)` computes `n * n` and prints it. 4. A documentation comment `/** ... */` placed just before the method describes the method; javadoc uses it as the method description. 5. Running `javadoc` on this file generates HTML API documentation containing both descriptions.
Q318.Easy
Write a Java program that uses Javadoc comments to document a class and its methods. The program should calculate the sum of two integers and print the result. Include appropriate Javadoc tags such as @author, @version, @since, @param, and @return. Use the class name 'Calculator' and the method name 'add'. The main method should create an object and call add(25, 35).
Show answer & explanation
Answer:
import java.io.*;

/**
 * <h2>Addition of numbers</h2>
 * This program demonstrates the use of Javadoc comments.
 * It adds two integers and prints the result.
 * <p>
 * <b>Note:</b> Comments improve code readability.
 *
 * @author Ravi
 * @version 1.0
 * @since 2023-01-01
 */
public class Calculator {
    /**
     * This method calculates the sum of two integers.
     * @param a This is the first parameter to add() method
     * @param b This is the second parameter to add() method
     * @return int This returns the sum of a and b
     */
    public int add(int a, int b) {
        return a + b;
    }
    /**
     * This is the main method which makes use of add() method.
     * @param args Unused
     * @see IOException
     */
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        int result = calc.add(25, 35);
        System.out.println("Sum of numbers: " + result);
    }
}
Explanation: 1. The class and method are documented with Javadoc comments (/** ... */). 2. Tags like @author, @version, @since, @param, @return provide structured documentation. 3. The add method takes two integers and returns their sum. 4. In main, an object is created and add(25,35) is called, returning 60. 5. The result is printed as 'Sum of numbers: 60'.
Q319.Easy
Write a Java program that uses a for loop to print the numbers 1 to 15, but skips printing the number 9 by using the continue statement. Name the class SkipNineFor.
Show answer & explanation
Answer:
public class SkipNineFor {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i == 9) {
                continue;
            }
            System.out.println(i);
        }
    }
}
Explanation: 1) The for loop runs i from 1 to 15. 2) When i == 9, continue skips the rest of the body, so 9 is not printed. 3) The loop's update step (i++) still runs automatically, so no infinite loop. 4) Output: 1,2,3,4,5,6,7,8,10,11,12,13,14,15.
Q320.Easy
Write a Java program that uses a while loop to print the numbers 1 to 12, but skips printing the number 7 by using the continue statement. Name the class SkipSevenWhile.
Show answer & explanation
Answer:
public class SkipSevenWhile {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 12) {
            if (i == 7) {
                i++;
                continue;
            }
            System.out.println(i);
            i++;
        }
    }
}
Explanation: 1) Start i at 1 and loop while i <= 12. 2) Inside the loop, check if i == 7; if so, increment i to 8 and use continue to skip the print. 3) Otherwise print i, then increment i. 4) The loop prints 1,2,3,4,5,6,8,9,10,11,12 (7 is skipped). 5) Incrementing before continue prevents an infinite loop.
Q321.Easy
Write a Java program where a class named MyTask extends Thread and overrides run() to print "task running...". In main, create a MyTask object and call its run() method directly (not start()). Explain that run() executes on the current call stack instead of a new thread.
Show answer & explanation
Answer:
class MyTask extends Thread {
    public void run() {
        System.out.println("task running...");
    }
    public static void main(String args[]) {
        MyTask t1 = new MyTask();
        t1.run(); // runs on the main thread's call stack, no new thread
    }
}
Explanation: 1) MyTask extends Thread and overrides run(). 2) main() creates t1 and calls t1.run() directly. 3) Calling run() directly is a normal method call, so it executes on the main thread's existing call stack. 4) No new call stack (thread) is created; start() would have created one. 5) Output: 'task running...' printed by the main thread.
Q322.Easy
Write a Java program that demonstrates a final method. Create a class Scooter with a final method start() that prints "Scooter started". Create a subclass ElectricScooter that tries to define its own method with the same name start() — this should fail to compile because start() is final. To keep the program compiling, instead give ElectricScooter a different method charge() that prints "Charging battery", and in main create an ElectricScooter object and call start() and charge().
Show answer & explanation
Answer:
class Scooter {
    final void start() {
        System.out.println("Scooter started");
    }
}

class ElectricScooter extends Scooter {
    void charge() {
        System.out.println("Charging battery");
    }
}

public class Main {
    public static void main(String[] args) {
        ElectricScooter e = new ElectricScooter();
        e.start();
        e.charge();
    }
}
Explanation: 1) A method declared final cannot be overridden by a subclass. 2) Scooter declares 'final void start()', so ElectricScooter cannot redefine start(). 3) ElectricScooter extends Scooter and adds a new method charge() instead of overriding start(). 4) In main, an ElectricScooter object is created. 5) Calling e.start() uses the inherited final method and prints "Scooter started". 6) Calling e.charge() prints "Charging battery". If ElectricScooter tried to override start(), compilation would fail.
Q323.Easy
Write a Java program that demonstrates a final class. Create a final class named Vehicle with a method showType() that prints "This is a vehicle". Then create a class Car (which cannot extend Vehicle because Vehicle is final) that has its own method showBrand() printing "Maruti Suzuki". In the main method, create an object of Car and call both showBrand() and, using a Vehicle object, call showType().
Show answer & explanation
Answer:
final class Vehicle {
    void showType() {
        System.out.println("This is a vehicle");
    }
}

class Car {
    void showBrand() {
        System.out.println("Maruti Suzuki");
    }
}

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.showBrand();
        Vehicle v = new Vehicle();
        v.showType();
    }
}
Explanation: 1) A class declared with the final keyword cannot be extended by any other class. 2) Here Vehicle is declared final, so no class can write 'class Car extends Vehicle'. 3) Car is a separate independent class with its own method showBrand(). 4) In main, we create a Car object and call showBrand(), which prints "Maruti Suzuki". 5) We create a Vehicle object and call showType(), which prints "This is a vehicle". 6) If you tried 'class Car extends Vehicle', the compiler would give an error because Vehicle is final.
Q324.Easy
Write a Java program to demonstrate that a final method is inherited but cannot be overridden. Create a class Vehicle with a final method run() that prints "Vehicle is running". Then create a subclass Car that extends Vehicle. In the main method of Car, create an object of Car and call the run() method.
Show answer & explanation
Answer:
class Vehicle {
    final void run() {
        System.out.println("Vehicle is running");
    }
}

class Car extends Vehicle {
    public static void main(String[] args) {
        Car c = new Car();
        c.run();
    }
}
Explanation: 1. Vehicle class defines a final method run(). 2. Car extends Vehicle, so it inherits the run() method. 3. The main method in Car creates a Car object and calls run(), which prints "Vehicle is running". 4. Since run() is final, Car cannot override it; if attempted, it would cause a compile-time error.
Q325.Easy
Write a Java program to demonstrate a blank final variable. Create a class Employee with fields id (int), name (String), and a final field aadhaarNumber (String) that is not initialized at declaration. Initialize aadhaarNumber in the constructor. In the main method, create an Employee object with id 101, name "Ramesh", and aadhaarNumber "1234-5678-9012", then print the details.
Show answer & explanation
Answer:
class Employee {
    int id;
    String name;
    final String aadhaarNumber;

    Employee(int id, String name, String aadhaarNumber) {
        this.id = id;
        this.name = name;
        this.aadhaarNumber = aadhaarNumber;
    }

    void display() {
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
        System.out.println("Aadhaar Number: " + aadhaarNumber);
    }

    public static void main(String[] args) {
        Employee emp = new Employee(101, "Ramesh", "1234-5678-9012");
        emp.display();
    }
}
Explanation: 1. The class Employee has a final field aadhaarNumber that is not initialized at declaration (blank final variable). 2. The constructor initializes aadhaarNumber along with id and name. 3. Once initialized, aadhaarNumber cannot be changed. 4. The display method prints the employee details. 5. The main method creates an Employee object and calls display, which outputs the details.
Q326.Easy
Write a Java program that shows a blank final variable being initialized in a constructor. Create a class 'Car' with a final int variable 'topSpeed' that is not initialized at declaration; initialize it to 120 inside the constructor and print it. In main, create one Car object.
Show answer & explanation
Answer:
class Car {
    final int topSpeed; // blank final variable

    Car() {
        topSpeed = 120;
        System.out.println(topSpeed);
    }

    public static void main(String args[]) {
        new Car();
    }
}
Explanation: 1) 'final int topSpeed;' is a blank final variable because it has no value at declaration. 2) A blank final instance variable can be initialized only inside a constructor (or initializer block). 3) The constructor sets topSpeed = 120 and prints it, so output is 120. 4) Creating 'new Car()' in main triggers the constructor, producing the output.
Q327.Easy
Write a Java program that demonstrates the use of a final parameter. Create a class FinalParameterDemo with a method cube that takes a final int parameter n and returns n*n*n. In the main method, create an object and call cube(4), then print the result. Also, show what happens if you try to modify n inside the method (comment out the modification).
Show answer & explanation
Answer:
public class FinalParameterDemo {
    int cube(final int n) {
        // n = n + 2; // This would cause a compile-time error: cannot assign a value to final variable n
        return n * n * n;
    }
    public static void main(String[] args) {
        FinalParameterDemo demo = new FinalParameterDemo();
        int result = demo.cube(4);
        System.out.println("Cube of 4 is: " + result);
    }
}
Explanation: 1. The method cube declares its parameter as final, meaning its value cannot be changed inside the method. 2. The statement n = n + 2; is commented out because it would cause a compile-time error. 3. The method returns n * n * n, which computes the cube of the parameter. 4. In main, we create an object and call cube(4), which returns 64. 5. The program prints 'Cube of 4 is: 64'.
Q328.Easy
Write a Java program that creates a ByteArrayInputStream from the byte array {65, 66, 67, 68} and reads it byte by byte, printing each byte's numeric value and its corresponding character, until the end of the stream is reached.
Show answer & explanation
Answer:
import java.io.*;
public class ByteArrayReadExample {
    public static void main(String[] args) throws IOException {
        byte[] data = { 65, 66, 67, 68 };
        ByteArrayInputStream stream = new ByteArrayInputStream(data);
        int value = 0;
        while ((value = stream.read()) != -1) {
            char ch = (char) value;
            System.out.println("Byte value is: " + value + "; Character is: " + ch);
        }
    }
}
Explanation: 1. A byte array data = {65, 66, 67, 68} is created. 2. new ByteArrayInputStream(data) wraps this array so it can be read as an input stream. 3. stream.read() returns the next byte as an int, or -1 when the stream ends; the while loop continues until -1. 4. Each value is cast to char, so 65->A, 66->B, 67->C, 68->D. 5. The program prints each byte value with its character, e.g. "Byte value is: 65; Character is: A".
Q329.Easy
Write a Java program that receives exactly one command-line argument (a student's name) and prints it in the format: "The student name is: <name>". The program should read the first argument passed from the command prompt.
Show answer & explanation
Answer:
public class StudentArgExample {
    public static void main(String[] args) {
        System.out.println("The student name is: " + args[0]);
    }
}
Explanation: 1. The class StudentArgExample has a main method that accepts String[] args, which holds command-line arguments. 2. args[0] refers to the first argument typed after the class name at the command prompt. 3. The program concatenates the label "The student name is: " with args[0] and prints it using System.out.println. 4. Run it as: java StudentArgExample Rohan — output: The student name is: Rohan.
Q330.Easy
Write a Java program that accepts any number of command-line arguments and prints each one on a separate line using a for loop that traverses the args array. For example, if run as `java Demo Delhi Mumbai Chennai`, it should print Delhi, Mumbai and Chennai each on its own line.
Show answer & explanation
Answer:
public class Demo {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}
Explanation: 1) The main method receives all command-line values in the String array args. 2) args.length gives the number of arguments passed. 3) The for loop starts at index 0 and runs while i < args.length, so it visits every argument. 4) Inside the loop, args[i] is printed with System.out.println, so each argument appears on its own line.
Q331.Easy
Write a Java program that shows the usage of the join() method. Create a class named TaskRunner that extends Thread and overrides run() to loop j from 0 to 1 (i.e., j < 2). Inside the loop, sleep the thread for 400 milliseconds inside a try-catch, then print the current thread name using Thread.currentThread().getName(), and finally print the value of j. In main, create two threads t1 and t2 of type TaskRunner, start both, call join() on each inside try-catch blocks, and then print "Both threads have finished". Name the file JoinDemo.java.
Show answer & explanation
Answer:
public class JoinDemo {
    static class TaskRunner extends Thread {
        public void run() {
            for (int j = 0; j < 2; j++) {
                try {
                    Thread.sleep(400);
                    System.out.println("The current thread name is: " + Thread.currentThread().getName());
                } catch (Exception e) {
                    System.out.println("The exception has been caught: " + e);
                }
                System.out.println(j);
            }
        }
    }

    public static void main(String[] args) {
        TaskRunner t1 = new TaskRunner();
        TaskRunner t2 = new TaskRunner();
        t1.start();
        t2.start();
        try {
            t1.join();
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        try {
            t2.join();
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        System.out.println("Both threads have finished");
    }
}
Explanation: 1) TaskRunner extends Thread and overrides run(). 2) In run(), the loop runs for j = 0 and j = 1. 3) Each iteration sleeps 400 ms, prints the current thread's name, then prints j. 4) In main, two TaskRunner threads t1 and t2 are created and started, so they run concurrently. 5) main calls t1.join() then t2.join(), so main waits until both threads complete. 6) Only after both finish does main print "Both threads have finished".
Q332.Easy
Write a Java program named JoinWaitDemo.java that creates three threads of the same class. Each thread's run() method prints the numbers 1 to 3, pausing 300 milliseconds before each number. In main, start the first thread and call join() on it with no timeout (handling InterruptedException), then start the second and third threads.
Show answer & explanation
Answer:
class JoinWaitDemo extends Thread {
    public void run() {
        for (int i = 1; i <= 3; i++) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
            System.out.println(i);
        }
    }

    public static void main(String args[]) {
        JoinWaitDemo t1 = new JoinWaitDemo();
        JoinWaitDemo t2 = new JoinWaitDemo();
        JoinWaitDemo t3 = new JoinWaitDemo();
        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
        t2.start();
        t3.start();
    }
}
Explanation: 1. JoinWaitDemo extends Thread and overrides run(). 2. run() loops i = 1 to 3, sleeping 300 ms before each print, so a thread takes about 900 ms to finish. 3. main creates t1, t2, t3 and starts t1. 4. t1.join() with no argument makes main wait until t1 has completely finished (all of 1,2,3 printed). 5. Only after t1 dies does main start t2 and t3, so t2 and t3 run concurrently after t1 completes.
Q333.Easy
Write a Java program that demonstrates the use of a predefined (built-in) method. Use the Math.max() method from the Java class library to find the larger of the two numbers 15 and 22, and print the result to the console in the format: The larger number is: <result>
Show answer & explanation
Answer:
public class MaxDemo
{
    public static void main(String[] args)
    {
        // using the predefined max() method of the Math class
        System.out.print("The larger number is: " + Math.max(15, 22));
    }
}
Explanation: Step 1: Create a class MaxDemo with a main method. Step 2: Math is a predefined class in java.lang; Math.max(a, b) is a predefined method that returns the greater of two values. Step 3: Call Math.max(15, 22). Since 22 > 15, it returns 22. Step 4: Concatenate the returned value with the string "The larger number is: " and print it using System.out.print. Step 5: Output is: The larger number is: 22
Q334.Easy
Write a Java program named PosNeg.java that reads an integer from the user and calls a user-defined method checkSign(int n) to print whether the number is positive or negative. For example, if the user enters 27 the output should be '27 is positive', and if the user enters -14 the output should be '-14 is negative'.
Show answer & explanation
Answer:
import java.util.Scanner;

public class PosNeg {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = scan.nextInt();
        checkSign(num);
    }

    public static void checkSign(int n) {
        if (n >= 0)
            System.out.println(n + " is positive");
        else
            System.out.println(n + " is negative");
    }
}
Explanation: 1. Create a Scanner object to read input from the user. 2. Read an integer num from the console. 3. Call the user-defined method checkSign(num); control transfers to that method. 4. Inside checkSign, test whether n >= 0: if true print 'n is positive', otherwise print 'n is negative'. 5. Control returns to main after the method finishes, and the program ends.
Q335.Easy
Write a Java program that demonstrates an instance method. Create a class Calculator with an instance (non-static) method multiply(int a, int b) that stores the product in a field and returns it. In main, create an object of Calculator and print the result of multiplying 14 and 6 by invoking the instance method.
Show answer & explanation
Answer:
public class Calculator {
    int result;

    // instance method (no static keyword)
    public int multiply(int a, int b) {
        result = a * b;
        return result;
    }

    public static void main(String[] args) {
        // creating an object of the class
        Calculator obj = new Calculator();
        // invoking the instance method
        System.out.println("The product is: " + obj.multiply(14, 6));
    }
}
Explanation: 1) multiply() has no static keyword, so it is an instance method and needs an object to be called. 2) In main, 'new Calculator()' creates the object obj. 3) obj.multiply(14, 6) computes 14 * 6 = 84, stores it in the field result and returns it. 4) The returned value 84 is printed as 'The product is: 84'.
Q336.Easy
Write a Java program that demonstrates accessor (getter) and mutator (setter) methods. Create a class named Employee with private fields empId (int) and empName (String). Provide getEmpId(), setEmpId(int), getEmpName(), setEmpName(String) methods, and a display() method that prints the employee id and name. In main, create an Employee object, set empId to 104 and empName to "Rohan", then call display().
Show answer & explanation
Answer:
public class Employee {
    private int empId;
    private String empName;

    public int getEmpId() {          // accessor method
        return empId;
    }

    public void setEmpId(int empId) { // mutator method
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public void display() {
        System.out.println("Employee id: " + empId);
        System.out.println("Employee name: " + empName);
    }

    public static void main(String[] args) {
        Employee e = new Employee();
        e.setEmpId(104);
        e.setEmpName("Rohan");
        e.display();
    }
}
Explanation: 1) The class Employee keeps its data private (empId, empName) so it cannot be changed directly from outside. 2) Accessor methods getEmpId() and getEmpName() return the private values. 3) Mutator methods setEmpId() and setEmpName() assign new values using 'this' to refer to the object's fields. 4) In main an Employee object is created, the setters store 104 and "Rohan", and display() prints them.
Q337.Easy
Write a Java program in a file ShapeDemo.java that declares an abstract class Shape containing an abstract method void draw(); then create a subclass Circle that implements draw() to print "Drawing a circle". In main(), create a Shape reference pointing to a Circle object and call draw().
Show answer & explanation
Answer:
abstract class Shape {
    abstract void draw();
}

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

public class ShapeDemo {
    public static void main(String args[]) {
        Shape obj = new Circle();
        obj.draw();
    }
}
Explanation: 1) Shape is declared abstract and contains the abstract method draw() with no body. 2) ShapeDemo extends Shape and provides the implementation of draw(), printing "Drawing a circle". 3) An abstract class cannot be instantiated directly, so we create a Shape reference that points to a ShapeDemo object (upcasting). 4) Calling obj.draw() invokes the overridden method at runtime (dynamic dispatch), printing "Drawing a circle".
Q338.Easy
Write a Java program named ThreadNamingDemo.java that creates two threads by extending the Thread class. Print the default names of both threads, start both threads (each thread's run() should print "working..."), then rename the first thread to "Ravi Kumar" using setName() and print its new name.
Show answer & explanation
Answer:
class ThreadNamingDemo extends Thread {
    public void run() {
        System.out.println("working...");
    }
    public static void main(String args[]) {
        ThreadNamingDemo t1 = new ThreadNamingDemo();
        ThreadNamingDemo t2 = new ThreadNamingDemo();
        System.out.println("Name of t1: " + t1.getName());
        System.out.println("Name of t2: " + t2.getName());

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

        t1.setName("Ravi Kumar");
        System.out.println("After changing name of t1: " + t1.getName());
    }
}
Explanation: 1) The class ThreadNamingDemo extends Thread, so each object is a thread. 2) run() simply prints "working..."; it executes when start() is called. 3) Two thread objects t1 and t2 are created; before starting, getName() returns the default names Thread-0 and Thread-1. 4) t1.start() and t2.start() launch both threads, so "working..." is printed (order may vary). 5) t1.setName("Ravi Kumar") changes t1's name, and getName() then prints "Ravi Kumar".
Q339.Easy
Write a Java program named WorkerNameDemo.java that sets a thread's name at the time of creation without using setName(). Create a class WorkerName that extends Thread, with a constructor WorkerName(String threadName) that passes the name to the superclass constructor using super(threadName). Override run() to print "The worker thread is running....". In main(), create a WorkerName object with the name "ReportThread" and start it.
Show answer & explanation
Answer:
class WorkerName extends Thread {
    WorkerName(String threadName) {
        super(threadName);
    }
    public void run() {
        System.out.println("The worker thread is running....");
    }
}

public class WorkerNameDemo {
    public static void main(String args[]) {
        WorkerName t = new WorkerName("ReportThread");
        t.start();
    }
}
Explanation: 1) WorkerName extends Thread, so it inherits thread behaviour. 2) Its constructor takes a String and calls super(threadName), which invokes Thread(String name) and sets the thread's name at creation time — no setName() needed. 3) run() is overridden to print the message when the thread executes. 4) In main(), new WorkerName("ReportThread") creates the thread already named ReportThread. 5) t.start() begins execution and run() prints "The worker thread is running....".
Q340.Easy
Write a Java program named ThreadInfoDemo.java that demonstrates the Thread.currentThread() method. Create a class ThreadInfoDemo that extends Thread and overrides run() to print the name of the currently executing thread using Thread.currentThread().getName(). In main(), create two ThreadInfoDemo objects and start both threads.
Show answer & explanation
Answer:
class ThreadInfoDemo extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String args[]) {
        ThreadInfoDemo t1 = new ThreadInfoDemo();
        ThreadInfoDemo t2 = new ThreadInfoDemo();
        t1.start();
        t2.start();
    }
}
Explanation: 1) ThreadInfoDemo extends Thread so each object is itself a thread. 2) run() calls Thread.currentThread() to get the reference of the thread that is currently executing, then getName() prints its name. 3) In main(), two objects t1 and t2 are created; they are not yet running. 4) Calling t1.start() and t2.start() launches two new threads; the JVM assigns default names Thread-0 and Thread-1. 5) Each thread executes run() and prints its own name, so the output is Thread-0 and Thread-1 (order may vary).
Q341.Easy
Write a Java program that demonstrates thread priorities. Create a class named PriorityCheck that extends Thread and overrides run() to print "Running in run method". In main, create three threads t1, t2, t3 of this class. First print the default priority of t1, t2 and t3. Then set the priorities: t1 to 7, t2 to 2 and t3 to 9. Finally print the priority of each thread again.
Show answer & explanation
Answer:
public class PriorityCheck extends Thread {
    public void run() {
        System.out.println("Running in run method");
    }

    public static void main(String[] args) {
        PriorityCheck t1 = new PriorityCheck();
        PriorityCheck t2 = new PriorityCheck();
        PriorityCheck t3 = new PriorityCheck();

        System.out.println("Default priority of t1: " + t1.getPriority());
        System.out.println("Default priority of t2: " + t2.getPriority());
        System.out.println("Default priority of t3: " + t3.getPriority());

        t1.setPriority(7);
        t2.setPriority(2);
        t3.setPriority(9);

        System.out.println("Priority of t1: " + t1.getPriority());
        System.out.println("Priority of t2: " + t2.getPriority());
        System.out.println("Priority of t3: " + t3.getPriority());
    }
}
Explanation: 1. Each new thread inherits the default priority NORM_PRIORITY = 5, so the first three prints show 5, 5, 5. 2. setPriority(7), setPriority(2) and setPriority(9) are all within the valid range 1 to 10, so no exception occurs. 3. getPriority() then returns the newly assigned values 7, 2 and 9 respectively. 4. The run() method is defined but start() is never called, so "Running in run method" is not printed.
Q342.Easy
Write a Java program that demonstrates the String substring() method. Take the string "ViratKohli", print the original string, print the substring starting from index 5, and print the substring from index 0 to 5. Name the class SubstringDemo.
Show answer & explanation
Answer:
public class SubstringDemo{
 public static void main(String args[]){
 String s="ViratKohli";
 System.out.println("Original String: " + s);
 System.out.println("Substring starting from index 5: " + s.substring(5)); //Kohli
 System.out.println("Substring starting from index 0 to 5: " + s.substring(0,5)); //Virat
 }
}
Explanation: 1) Store "ViratKohli" in s (indices: V=0,i=1,r=2,a=3,t=4,K=5,o=6,h=7,l=8,i=9). 2) s.substring(5) returns characters from index 5 to the end → "Kohli". 3) s.substring(0,5) returns characters from index 0 up to but not including index 5 → "Virat". 4) Print the original string and both substrings.
Q343.Easy
Write a Java program that uses the String.split() method to break a sentence into parts. Take the sentence "Ravi, My friend is Arjun" and split it using a dot (".") as the delimiter (regular expression), then print the resulting array using Arrays.toString(). Name the class SplitDemo.
Show answer & explanation
Answer:
import java.util.*;

public class SplitDemo
{
    public static void main(String args[])
    {
        String text = new String("Ravi, My friend is Arjun");
        /* Splits the sentence by the delimiter passed as an argument */
        String[] parts = text.split("\\.");
        System.out.println(Arrays.toString(parts));
    }
}
Explanation: 1) Create a String text holding the sentence. 2) Call text.split("\\.") — the argument is a regular expression where \\. means a literal dot. Since the sentence has no dot, no split occurs. 3) The result is an array with one element: the whole sentence. 4) Arrays.toString() prints the array as [Ravi, My friend is Arjun].
Q344.Easy
Write a Java program that creates a class named `Train` with a no-argument constructor. The constructor should print the message "Train is ready". In the main method, create one object of the Train class so the constructor is invoked.
Show answer & explanation
Answer:
class Train {
    Train() {
        System.out.println("Train is ready");
    }

    public static void main(String args[]) {
        Train t = new Train();
    }
}
Explanation: 1. The class Train defines an explicit no-argument constructor Train(). 2. Inside the constructor, a message 'Train is ready' is printed. 3. In main, the statement 'Train t = new Train();' creates an object. 4. Object creation automatically invokes the no-arg constructor, so the message is printed once. 5. Output: Train is ready.
Q345.Easy
Write a Java program that demonstrates a default constructor displaying default values. Create a class named `CricketPlayer` with fields `runs` (int) and `playerName` (String). Do not assign any values to these fields. Create two objects of the class and display their field values to show the default values provided by Java.
Show answer & explanation
Answer:
class CricketPlayer {
    int runs;
    String playerName;

    void display() {
        System.out.println(runs + " " + playerName);
    }

    public static void main(String args[]) {
        CricketPlayer p1 = new CricketPlayer();
        CricketPlayer p2 = new CricketPlayer();
        p1.display();
        p2.display();
    }
}
Explanation: 1. The class CricketPlayer has two fields: int runs and String playerName, with no explicit constructor. 2. Java supplies a default no-arg constructor automatically, which initializes fields to their default values: int becomes 0 and String (object reference) becomes null. 3. In main, two objects p1 and p2 are created using the default constructor. 4. Calling display() on each prints '0 null' because runs is 0 and playerName is null. 5. This shows the purpose of the default constructor: giving default values like 0 and null.
Q346.Easy
Write a Java program that demonstrates a parameterized constructor. Create a class named Book with fields bookId (int) and title (String). Define a constructor that takes two parameters and assigns them to the fields. Add a display() method that prints bookId and title separated by a space. In main, create two Book objects: one with (101, "Wings of Fire") and another with (102, "Discovery of India"), then call display() on both.
Show answer & explanation
Answer:
class Book {
    int bookId;
    String title;

    // parameterized constructor
    Book(int id, String t) {
        bookId = id;
        title = t;
    }

    void display() {
        System.out.println(bookId + " " + title);
    }

    public static void main(String args[]) {
        Book b1 = new Book(101, "Wings of Fire");
        Book b2 = new Book(102, "Discovery of India");
        b1.display();
        b2.display();
    }
}
Explanation: 1) The class Book has two fields: bookId and title. 2) The constructor Book(int id, String t) is parameterized: it receives values at object creation and assigns them to the fields. 3) In main, new Book(101, "Wings of Fire") creates b1 with bookId=101 and title="Wings of Fire". 4) new Book(102, "Discovery of India") creates b2 with bookId=102 and title="Discovery of India". 5) b1.display() prints "101 Wings of Fire" and b2.display() prints "102 Discovery of India", showing that each object holds its own values passed through the constructor.
Q347.Easy
Write a Java program that demonstrates constructor overloading. Create a class named Employee with fields empId (int), empName (String) and salary (int). Provide a two-argument constructor that sets empId and empName, and a three-argument constructor that sets empId, empName and salary. Add a display() method that prints the three fields separated by spaces. In main, create one Employee using the two-argument constructor with values (501, "Rohit") and another using the three-argument constructor with values (502, "Sneha", 45000), then call display() on both.
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;
    int salary;

    // two-argument constructor
    Employee(int id, String name) {
        empId = id;
        empName = name;
    }

    // three-argument constructor
    Employee(int id, String name, int sal) {
        empId = id;
        empName = name;
        salary = sal;
    }

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

    public static void main(String args[]) {
        Employee e1 = new Employee(501, "Rohit");
        Employee e2 = new Employee(502, "Sneha", 45000);
        e1.display();
        e2.display();
    }
}
Explanation: 1) The class Employee declares three fields: empId, empName and salary. 2) Two constructors with different parameter lists are defined: Employee(int, String) and Employee(int, String, int). This is constructor overloading; the compiler picks the right one based on the arguments passed. 3) The two-argument constructor sets only empId and empName, so salary keeps its default value 0. 4) The three-argument constructor sets all three fields. 5) In main, e1 is created with (501, "Rohit") so salary stays 0; e2 is created with (502, "Sneha", 45000). 6) display() prints "501 Rohit 0" for e1 and "502 Sneha 45000" for e2.
Q348.Easy
Write a Java program to copy the values of one object into another using a constructor (similar to a copy constructor). Create a class Book with fields bookId (int) and title (String). Provide a parameterized constructor to initialize these fields and another constructor that takes a Book object and copies its field values. In the main method, create a Book object b1 with id 301 and title "Java Basics", then create b2 using the copy constructor with b1. Display the details of both objects.
Show answer & explanation
Answer:
class Book {
    int bookId;
    String title;

    Book(int id, String t) {
        bookId = id;
        title = t;
    }

    Book(Book b) {
        bookId = b.bookId;
        title = b.title;
    }

    void display() {
        System.out.println(bookId + " " + title);
    }

    public static void main(String[] args) {
        Book b1 = new Book(301, "Java Basics");
        Book b2 = new Book(b1);
        b1.display();
        b2.display();
    }
}
Explanation: 1. Define class Book with fields bookId and title. 2. Add a parameterized constructor to initialize these fields. 3. Add a copy constructor that takes a Book object and copies its fields to the new object. 4. In main, create b1 using the parameterized constructor with id 301 and title "Java Basics". 5. Create b2 using the copy constructor, passing b1. 6. Call display() on both objects to print their details.
Q349.Easy
Write a Java program to copy the values of one object into another by assigning the fields directly, without using a constructor. Create a class Employee with fields empId (int) and empName (String). Provide a parameterized constructor to initialize these fields and a no-argument constructor. In the main method, create an Employee object e1 with id 201 and name "Rahul", and another Employee object e2 using the no-argument constructor. Then copy the values from e1 to e2 by assigning each field individually. Finally, display the details of both objects.
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;

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

    Employee() {}

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

    public static void main(String[] args) {
        Employee e1 = new Employee(201, "Rahul");
        Employee e2 = new Employee();
        e2.empId = e1.empId;
        e2.empName = e1.empName;
        e1.display();
        e2.display();
    }
}
Explanation: 1. Define class Employee with fields empId and empName. 2. Add a parameterized constructor to initialize these fields and a no-argument constructor. 3. In main, create e1 using the parameterized constructor with id 201 and name "Rahul". 4. Create e2 using the no-argument constructor. 5. Copy each field from e1 to e2: e2.empId = e1.empId; e2.empName = e1.empName;. 6. Call display() on both objects to print their details.
Q350.Easy
Write a Java program (file: WorkerThread.java) that demonstrates a simple daemon thread. Create a class WorkerThread extending Thread whose run() checks Thread.currentThread().isDaemon() and prints "daemon thread work" if true, otherwise "user thread work". In main, create three WorkerThread objects, mark only the first one as a daemon using setDaemon(true), then start all three.
Show answer & explanation
Answer:
public class WorkerThread extends Thread {
    public void run() {
        if (Thread.currentThread().isDaemon()) {
            System.out.println("daemon thread work");
        } else {
            System.out.println("user thread work");
        }
    }

    public static void main(String[] args) {
        WorkerThread t1 = new WorkerThread();
        WorkerThread t2 = new WorkerThread();
        WorkerThread t3 = new WorkerThread();

        t1.setDaemon(true); // t1 becomes a daemon thread

        t1.start();
        t2.start();
        t3.start();
    }
}
Explanation: 1) WorkerThread extends Thread and overrides run(). 2) Inside run(), isDaemon() tells whether the currently executing thread is a daemon; it prints the matching message. 3) In main, three threads t1, t2, t3 are created. 4) setDaemon(true) is called on t1 before it is started, so t1 is a daemon thread; t2 and t3 remain user threads. 5) All three are started: t1 prints "daemon thread work", while t2 and t3 print "user thread work".
Q351.Easy
Write a Java program that demonstrates the use of single-line comments. Declare an integer variable named total with value 250 and print it. Add a single-line comment (starting with //) on the declaration line explaining the variable, and another single-line comment on the print line describing what is being printed.
Show answer & explanation
Answer:
public class SingleCommentDemo {
    public static void main(String[] args) {
        int total = 250; // total is a variable with value 250
        System.out.println(total);  // printing the variable total
    }
}
Explanation: 1) The class SingleCommentDemo contains the main method. 2) int total = 250; declares an integer variable total and assigns 250; the text after // on that line is a single-line comment and is ignored by the compiler. 3) System.out.println(total); prints the value 250; the trailing // comment is also ignored. 4) Single-line comments start with // and extend to the end of that line only. 5) Output: 250
Q352.Easy
Write a Java program that demonstrates the use of multi-line comments. Declare an integer variable named marks with value 85 and print it. Also, inside a multi-line comment (between /* and */), write code that would declare two double variables (for example price = 45.5 and tax = 3.2) and print their sum, so that this commented code is NOT executed. The program should print only the value of marks.
Show answer & explanation
Answer:
public class CommentDemo {
    public static void main(String[] args) {
        /* Let's declare and
           print a variable in Java. */
        int marks = 85;
        System.out.println(marks);
        /* double price = 45.5;
           double tax = 3.2;
           System.out.println(price + tax); */
    }
}
Explanation: 1) The class CommentDemo contains the main method. 2) The text between /* and */ is a multi-line comment and is ignored by the Java compiler. 3) int marks = 85; declares an integer variable and assigns 85. 4) System.out.println(marks); prints 85. 5) The second /* ... */ block contains declarations and a print statement, but since it is commented out, it is never executed. 6) Output: 85
Q353.Easy
Write a Java program that demonstrates the String trim() method. Create a String holding the value "  Anjali  " (with leading and trailing spaces). Print the original string, then print the string after calling trim(). Name the class StringTrimDemo.
Show answer & explanation
Answer:
public class StringTrimDemo
{
public static void main(String ar[])
{
String s="  Anjali  ";
System.out.println(s);//  Anjali  
System.out.println(s.trim());//Anjali
}
}
Explanation: 1) Declare a String s = " Anjali " which has two spaces before and after the word. 2) Printing s shows the spaces: " Anjali ". 3) s.trim() returns a new string with leading and trailing whitespace removed, giving "Anjali". 4) Printing s.trim() therefore shows Anjali without surrounding spaces.
Q354.Easy
Write a Java program that demonstrates the String startsWith() and endsWith() methods. Create a String holding the value "Rohit". Print whether it starts with "Ro" and whether it ends with "t". Name the class StringCheck.
Show answer & explanation
Answer:
public class StringCheck
{
public static void main(String ar[])
{
String s="Rohit";
System.out.println(s.startsWith("Ro"));//true
System.out.println(s.endsWith("t"));//true
}
}
Explanation: 1) Declare a String s = "Rohit". 2) s.startsWith("Ro") checks the first two characters; "Rohit" begins with "Ro", so it prints true. 3) s.endsWith("t") checks the last character; "Rohit" ends with "t", so it prints true. 4) Both methods return boolean values that println displays as true/true.
Q355.Easy
Write a Java program that stores the name of an Indian river in a String variable and prints the characters at index 0 and index 2 using the String charAt() method. Use the river name "Ganga". The class should be named RiverCharAt.
Show answer & explanation
Answer:
public class RiverCharAt
{
    public static void main(String[] args)
    {
        String river = "Ganga";
        System.out.println(river.charAt(0));
        System.out.println(river.charAt(2));
    }
}
Explanation: 1) Declare a String variable river and assign it the value "Ganga". 2) charAt(index) returns the character at the given zero-based index. 3) Index 0 is the first character: 'G'. 4) Index 2 is the third character: 'n' (G=0, a=1, n=2). 5) The program prints G on one line and n on the next line.
Q356.Easy
Write a Java program that demonstrates the String.intern() method. Create a String object using the new keyword with the value "Rahul", then call intern() on it and store the result in another String variable. Print the interned string. The output should be Rahul.
Show answer & explanation
Answer:
public class StringInternDemo {
    public static void main(String[] args) {
        String name = new String("Rahul");
        String internedName = name.intern();
        System.out.println(internedName);
    }
}
Explanation: 1. Create a String object name using new String("Rahul"). 2. Call name.intern() to get a canonical representation from the string pool. 3. Store the result in internedName. 4. Print internedName, which outputs Rahul.
Q357.Easy
Write a Java program that demonstrates the String.valueOf() method. Convert an integer variable 'marks' with value 85 to a String using String.valueOf(), then concatenate the string "100" to it and print the result. The output should be 85100.
Show answer & explanation
Answer:
public class StringValueOfDemo {
    public static void main(String[] args) {
        int marks = 85;
        String strMarks = String.valueOf(marks);
        System.out.println(strMarks + "100");
    }
}
Explanation: 1. Declare an int variable marks and assign 85. 2. Use String.valueOf(marks) to convert the integer to a String. 3. Concatenate the string "100" to strMarks, resulting in "85100". 4. Print the concatenated string.
Q358.Easy
Write a Java program that demonstrates the String class replace() method. Create a String containing the sentence: "Delhi is the capital of India. Delhi is a busy city. Delhi has many monuments." Then use replace() to replace every occurrence of "Delhi" with "Mumbai" and print the resulting string. Name the class StringReplaceDemo.
Show answer & explanation
Answer:
public class StringReplaceDemo {
    public static void main(String[] args) {
        String s1 = "Delhi is the capital of India. Delhi is a busy city. Delhi has many monuments.";
        String replaced = s1.replace("Delhi", "Mumbai");
        System.out.println(replaced);
    }
}
Explanation: 1. Declare s1 with the given sentence containing "Delhi" three times. 2. Call s1.replace("Delhi", "Mumbai") — replace() returns a new string with all occurrences of the first sequence replaced by the second. 3. Store the returned string in replaced. 4. Print replaced, which outputs: "Mumbai is the capital of India. Mumbai is a busy city. Mumbai has many monuments."
Q359.Easy
Write a Java program that demonstrates the parameterless getBytes() method of the String class. Create a String variable holding the value "INDIA2024", convert it to a byte array using getBytes() (which uses the platform's default charset, UTF-8), and then print each byte value on its own line. Name the file StringBytesDemo.java and the class StringBytesDemo.
Show answer & explanation
Answer:
public class StringBytesDemo {
    public static void main(String[] args) {
        String s1 = "INDIA2024";
        byte[] barr = s1.getBytes();
        for (int i = 0; i < barr.length; i++) {
            System.out.println(barr[i]);
        }
    }
}
Explanation: 1. Declare a String s1 = "INDIA2024". 2. Call s1.getBytes() which encodes the string using the default charset (UTF-8) and returns a byte array. 3. Store the result in byte[] barr. 4. Loop i from 0 to barr.length-1. 5. Print each barr[i]; since all characters are ASCII, each byte equals its character code (e.g. 'I'=73, 'N'=78, ... '2'=50, '0'=48, '4'=52).
Q360.Easy
Write a Java program that takes the String "KOLKATA" and converts it into a byte array using the getBytes() method. Print each byte value on its own line, then reconstruct a String from that byte array using the String constructor and print the reconstructed String. Name the file ByteArrayRoundTrip.java.
Show answer & explanation
Answer:
public class ByteArrayRoundTrip {
    public static void main(String[] args) {
        String s1 = "KOLKATA";
        byte[] barr = s1.getBytes();
        for (int i = 0; i < barr.length; i++) {
            System.out.println(barr[i]);
        }
        // Getting string back
        String s2 = new String(barr);
        System.out.println(s2);
    }
}
Explanation: 1. Declare String s1 = "KOLKATA". 2. s1.getBytes() converts the string into a byte array using the platform's default charset; each ASCII letter becomes one byte equal to its character code (e.g. 'K' = 75, 'O' = 79). 3. A for loop runs from 0 to barr.length-1 and prints each byte value on a separate line. 4. new String(barr) builds a new String from the same bytes, giving back "KOLKATA". 5. Printing s2 shows the reconstructed string, demonstrating the round trip.
Q361.Easy
Write a Java program that demonstrates the append() method of the StringBuffer class. Create a StringBuffer initialized with "Namaste " and then append "Bharat" to it. Finally, print the modified StringBuffer. The program should be in a class named StringBufferAppendExample.
Show answer & explanation
Answer:
public class StringBufferAppendExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Namaste ");
        sb.append("Bharat");
        System.out.println(sb);
    }
}
Explanation: 1. Create a StringBuffer object sb initialized with the string "Namaste ". 2. Call the append() method on sb with the argument "Bharat". This modifies the original StringBuffer by adding "Bharat" at the end. 3. Print sb using System.out.println(), which outputs the modified string "Namaste Bharat".
Q362.Easy
Write a Java program that stores the prices of two items in integer variables — a notebook costing Rs 25 and a pen costing Rs 15 — adds them, and prints the total cost.
Show answer & explanation
Answer:
public class TotalCost {
    public static void main(String[] args) {
        int notebook = 25;
        int pen = 15;
        int total = notebook + pen;
        System.out.println(total);
    }
}
Explanation: 1) Declare an int variable notebook and assign 25. 2) Declare an int variable pen and assign 15. 3) Add them into an int variable total: 25 + 15 = 40. 4) Print total using System.out.println, which outputs 40.
Q363.Easy
Write a Java program that stores the number of mangoes 45 in an int variable, then assigns it to a double variable named weightInKg (implicit widening), and prints both values on separate lines.
Show answer & explanation
Answer:
public class MangoCount {
    public static void main(String[] args) {
        int mangoes = 45;
        double weightInKg = mangoes;
        System.out.println(mangoes);
        System.out.println(weightInKg);
    }
}
Explanation: 1) Declare int mangoes = 45. 2) Assign it to a double: double weightInKg = mangoes; This is widening (int to double), so Java converts it automatically with no cast needed. 3) System.out.println(mangoes) prints 45. 4) System.out.println(weightInKg) prints 45.0 because the value is now a double.
Q364.Easy
Write a Java program that stores the value 27.86 in a float variable named price, then explicitly narrows it to an int variable named rupees using typecasting, and prints both values on separate lines.
Show answer & explanation
Answer:
public class ShopBill {
    public static void main(String[] args) {
        float price = 27.86f;
        // int rupees = price; // compile-time error without cast
        int rupees = (int) price;
        System.out.println(price);
        System.out.println(rupees);
    }
}
Explanation: 1) A float literal needs the 'f' suffix, so we write 27.86f and store it in a float variable price. 2) Assigning a float directly to an int is a compile-time error because narrowing loses the fractional part, so an explicit cast (int) is required. 3) int rupees = (int) price; truncates the decimal part, giving 27. 4) System.out.println(price) prints 27.86 and System.out.println(rupees) prints 27.
Q365.Easy
Write a Java program that adds two byte variables and stores the result in a byte variable using an explicit cast. Use the values 20 and 30, then print the result.
Show answer & explanation
Answer:
public class ByteAddDemo {
    public static void main(String[] args) {
        byte x = 20;
        byte y = 30;
        // byte z = x + y; // Compile-time error: x + y is promoted to int
        byte z = (byte)(x + y);
        System.out.println(z);
    }
}
Explanation: 1) Declare two byte variables x=20 and y=30. 2) In Java, adding two bytes promotes the result to int, so 'byte z = x + y;' would not compile. 3) Apply an explicit cast (byte)(x + y) to narrow the int result back to byte. 4) 20 + 30 = 50, which fits in a byte, so z = 50. 5) Print z, which outputs 50.
Q366.Easy
Write a Java program demonstrating runtime polymorphism. Create a parent class Bird with a method sound() that prints "chirping...". Create three subclasses: Parrot (prints "squawking..."), Crow (prints "cawing...") and Owl (prints "hooting..."), each overriding sound(). In main, use a Bird reference to point to each subclass object in turn and call sound().
Show answer & explanation
Answer:
class Bird {
    void sound() { System.out.println("chirping..."); }
}

class Parrot extends Bird {
    void sound() { System.out.println("squawking..."); }
}

class Crow extends Bird {
    void sound() { System.out.println("cawing..."); }
}

class Owl extends Bird {
    void sound() { System.out.println("hooting..."); }
}

class TestPolymorphism {
    public static void main(String[] args) {
        Bird b;
        b = new Parrot();
        b.sound();
        b = new Crow();
        b.sound();
        b = new Owl();
        b.sound();
    }
}
Explanation: 1. Bird defines sound(); each subclass overrides it with its own message. 2. The reference variable b is of type Bird but points to different subclass objects. 3. Method calls are resolved at runtime based on the actual object type (dynamic dispatch). 4. So the output is: squawking..., cawing..., hooting... — one line per object.
Q367.Easy
Write a Java program that demonstrates an infinite do-while loop. Use a do-while loop with the condition true, and inside the loop print the message "infinite do-while loop". The program should run indefinitely.
Show answer & explanation
Answer:
public class InfiniteDoWhile {
    public static void main(String[] args) {
        do {
            System.out.println("infinite do-while loop");
        } while (true);
    }
}
Explanation: The do-while loop executes the block once, then checks the condition. Since the condition is true, it repeats forever. The program prints the message repeatedly without termination.
Q368.Medium
Write a Java program named CleanupDemo.java that creates an object, prints its hash code, sets the reference to null, requests garbage collection with System.gc(), and then prints a closing message. The class must override finalize() so that it prints "finalize() method invoked" when the object is collected.
Show answer & explanation
Answer:
public class CleanupDemo {
    public static void main(String[] args) {
        CleanupDemo item = new CleanupDemo();
        System.out.println("Hashcode is: " + item.hashCode());
        item = null;
        System.gc();
        System.out.println("Garbage collection request finished");
    }

    protected void finalize() {
        System.out.println("finalize() method invoked");
    }
}
Explanation: 1) The class CleanupDemo is defined with a main method and an overridden finalize() method. 2) In main, an object item is created and its hash code is printed using hashCode(). 3) The reference item is set to null, making the object eligible for garbage collection. 4) System.gc() requests the JVM to run the garbage collector; if the object is collected, finalize() runs and prints its message. 5) Finally, the program prints the closing message. Note that finalize() execution is not guaranteed at a fixed time, so the order of the finalize message may vary.
Q369.Medium
Write a Java program that demonstrates the rule: if a superclass method declares no exception, the subclass overridden method cannot declare a checked exception, but may declare an unchecked exception. Create a class `Shape` with a method `draw()` that declares no exception, and a subclass `Circle` whose overridden `draw()` declares `IOException` (a checked exception). Show that this causes a compile-time error. Name the file `ShapeTest.java`.
Show answer & explanation
Answer:
import java.io.*;

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

class Circle extends Shape {
    void draw() throws IOException {   // compile-time error: checked exception not allowed
        System.out.println("circle method");
    }
}

public class ShapeTest {
    public static void main(String[] args) {
        Shape s = new Circle();
        s.draw();
    }
}
Explanation: 1. Superclass `Shape.draw()` declares no exception. 2. The overriding method `Circle.draw()` declares `IOException`, which is a CHECKED exception. 3. Java's overriding rule: if the superclass method declares no exception, the overriding method cannot add a checked exception (it may only add unchecked exceptions like RuntimeException). 4. Because `IOException` is checked and not declared by the parent, the compiler reports an error: overridden method does not throw IOException. 5. To fix it, `Circle.draw()` should declare no exception, or declare an unchecked exception such as `RuntimeException`.
Q370.MediumAnswer under review
Write a Java program that demonstrates the rule: if a superclass method declares an exception, the subclass overridden method may declare the same exception or a subclass of it, but cannot declare a parent (broader) exception. Create a class `Vehicle` with a method `show()` that declares `ArithmeticException`, and a subclass `Car` whose overridden `show()` declares `RuntimeException` (a parent of ArithmeticException). Show that this causes a compile-time error. Name the file `VehicleTest.java`.
Show answer & explanation
Answer:
class Vehicle {
    void show() throws ArithmeticException {
        System.out.println("vehicle method");
    }
}

class Car extends Vehicle {
    void show() throws RuntimeException {   // compile-time error: parent exception
        System.out.println("car method");
    }
}

public class VehicleTest {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.show();
    }
}
Explanation: 1. Superclass `Vehicle.show()` declares `ArithmeticException`. 2. The overriding method `Car.show()` declares `RuntimeException`, which is a PARENT of `ArithmeticException`. 3. Java's overriding rule: the overriding method may declare the same exception or a narrower (subclass) exception, but never a broader parent exception. 4. Since `RuntimeException` is broader than `ArithmeticException`, the compiler reports an error: overridden method does not throw RuntimeException. 5. To fix it, `Car.show()` should declare `ArithmeticException` (same) or nothing (no exception).
Q371.Medium
Write a Java program that demonstrates method overriding where the subclass overridden method declares no exception. Create a parent class Vehicle with a method show() that declares 'throws Exception' and prints "Vehicle method". Create a child class Car that overrides show() without declaring any exception and prints "Car method". In main, create a Car object and call show() inside a try-catch block that catches Exception.
Show answer & explanation
Answer:
class Vehicle {
    void show() throws Exception {
        System.out.println("Vehicle method");
    }
}

class Car extends Vehicle {
    void show() {
        System.out.println("Car method");
    }
}

public class OverrideDemo {
    public static void main(String[] args) {
        try {
            Car c = new Car();
            c.show();
        } catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }
    }
}
Explanation: 1. Parent class Vehicle declares show() with 'throws Exception'. 2. Child class Car overrides show() but declares no exception — this is allowed because an overriding method may throw fewer or narrower checked exceptions than the parent. 3. In main, a Car object is created and show() is called inside try-catch. 4. Since Car's show() throws nothing, it simply prints "Car method" and no exception occurs. 5. Output: Car method.
Q372.Medium
Write a Java program that demonstrates the DataInputStream class. The program should read the contents of a file named notes.txt (located in the current working directory) and print each character followed by a hyphen '-'. Use FileInputStream wrapped in a DataInputStream, read all available bytes into a byte array, then loop through the array converting each byte to a char and printing it with a trailing '-'.
Show answer & explanation
Answer:
import java.io.*;

public class DataStreamDemo {
    public static void main(String[] args) throws IOException {
        InputStream input = new FileInputStream("notes.txt");
        DataInputStream din = new DataInputStream(input);
        int count = input.available();
        byte[] data = new byte[count];
        din.read(data);
        for (byte b : data) {
            char c = (char) b;
            System.out.print(c + "-");
        }
        din.close();
    }
}
Explanation: 1. FileInputStream opens notes.txt as a byte stream. 2. DataInputStream wraps the file stream so we can use its read() method. 3. input.available() gives the number of bytes that can be read; we create a byte array of that size. 4. din.read(data) fills the array with the file's bytes. 5. The for-each loop converts each byte to a char and prints it followed by '-', e.g. H-i- for a file containing 'Hi'.
Q373.Medium
Write a Java program that uses the String getChars() method to copy a substring into a character array and then prints the array. Use the string "hello india how r u" and copy characters from index 6 to 16 (exclusive) into a char array of size 10, starting at index 0 of the array.
Show answer & explanation
Answer:
public class StringGetCharsExample {
    public static void main(String[] args) {
        String str = "hello india how r u";
        char[] ch = new char[10];
        try {
            str.getChars(6, 16, ch, 0);
            System.out.println(ch);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}
Explanation: 1. The string is "hello india how r u". Its characters are at indices: 0:h,1:e,2:l,3:l,4:o,5:space,6:i,7:n,8:d,9:i,10:a,11:space,12:h,13:o,14:w,15:space,16:r,17:space,18:u. 2. getChars(6, 16, ch, 0) copies characters from index 6 up to index 15 (since end index is exclusive) into ch starting at index 0. 3. The characters from index 6 to 15 are: i, n, d, i, a, space, h, o, w, space. That's 10 characters. 4. These are stored in ch[0] to ch[9]. 5. Printing ch displays "india how " (with a trailing space).
Q374.Medium
Write a Java program that demonstrates the String getChars() method throwing an exception when the source range exceeds the string length. Use the string "Welcome to India" and attempt to copy characters from index 1 to 26 into a char array of size 20. Catch and print the exception.
Show answer & explanation
Answer:
public class StringGetCharsExample2 {
    public static void main(String[] args) {
        String str = "Welcome to India";
        char[] ch = new char[20];
        try {
            str.getChars(1, 26, ch, 0);
            System.out.println(ch);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Explanation: 1. Create a string "Welcome to India" which has length 16. 2. Create a char array of size 20. 3. Call getChars(1, 26, ch, 0). The source range is from index 1 to 25 (since end index is exclusive), but the string length is only 16, so the range exceeds the string length. 4. This causes a StringIndexOutOfBoundsException. 5. The catch block catches the exception and prints it, e.g., java.lang.StringIndexOutOfBoundsException: begin 1, end 26, length 16.
Q375.Medium
Write a Java program that demonstrates a thread pool using ExecutorService and Executors. Create a task class named PrintTask that implements Runnable, takes a String label in its constructor, prints the current thread's name with "(Start) label = <label>", sleeps for 1500 milliseconds, then prints the current thread's name with "(End)". In main, create a fixed thread pool of 3 threads, submit 5 PrintTask instances with labels "Alpha", "Beta", "Gamma", "Delta", "Epsilon", and shut down the executor.
Show answer & explanation
Answer:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class PrintTask implements Runnable {
    private String label;

    public PrintTask(String label) {
        this.label = label;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + " (Start) label = " + label);
        pause();
        System.out.println(Thread.currentThread().getName() + " (End)");
    }

    private void pause() {
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        String[] labels = {"Alpha", "Beta", "Gamma", "Delta", "Epsilon"};
        for (String label : labels) {
            pool.execute(new PrintTask(label));
        }
        pool.shutdown();
    }
}
Explanation: 1. PrintTask implements Runnable and stores a label passed to its constructor. 2. run() prints the worker thread's name with the start message, calls pause() to sleep 1500 ms, then prints the end message. 3. Executors.newFixedThreadPool(3) creates a pool with at most 3 worker threads. 4. The loop submits 5 PrintTask objects using pool.execute(); the pool reuses its 3 threads to run all 5 tasks. 5. pool.shutdown() stops accepting new tasks and lets already submitted tasks finish.
Q376.Medium
Write a Java program using a fixed thread pool of 2 threads. Create a Runnable task class named Job that takes a job name in its constructor. In run(), loop 3 times (j = 0 to 2): on the first iteration print "Start time for job: <name> = <time>", otherwise print "Running job: <name> = <time>", using SimpleDateFormat with pattern "hh : mm : ss"; then sleep 1000 ms. After the loop print "<name> is finished.". In main, create an ExecutorService with Executors.newFixedThreadPool(2) and submit three Job tasks named "Report", "Invoice" and "Audit", then shut down the executor.
Show answer & explanation
Answer:
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.text.SimpleDateFormat;

class Job implements Runnable {
    private String jobName;

    public Job(String str) {
        jobName = str;
    }

    public void run() {
        try {
            for (int j = 0; j <= 2; j++) {
                Date dt = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("hh : mm : ss");
                if (j == 0) {
                    System.out.println("Start time for job: " + jobName + " = " + sdf.format(dt));
                } else {
                    System.out.println("Running job: " + jobName + " = " + sdf.format(dt));
                }
                Thread.sleep(1000);
            }
            System.out.println(jobName + " is finished.");
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Job("Report"));
        executor.execute(new Job("Invoice"));
        executor.execute(new Job("Audit"));
        executor.shutdown();
    }
}
Explanation: 1. Executors.newFixedThreadPool(2) creates a pool with exactly 2 worker threads. 2. Three Job tasks are submitted; the first two run concurrently on the two threads, while the third waits in the queue until a thread becomes free. 3. Each Job's run() loops 3 times, printing a start message on j==0 and running messages afterwards, sleeping 1 second each iteration. 4. After the loop each job prints that it is finished. 5. executor.shutdown() stops accepting new tasks and lets submitted tasks complete.
Q377.Medium
Write a Java program that demonstrates the restriction that a static method cannot directly use a non-static (instance) data member. Create a class named Shop with a non-static integer field price = 250. In its main method (which is static), try to print price directly and show that this causes a compile-time error. Add a comment in the code explaining why the error occurs.
Show answer & explanation
Answer:
class Shop {
    int price = 250; // non-static (instance) variable

    public static void main(String[] args) {
        // ERROR: cannot access non-static variable 'price' from a static context
        // System.out.println(price); // uncommenting this line causes a compile-time error
        System.out.println("Cannot access non-static field price directly from static main");
    }
}
Explanation: 1) The field price is declared without static, so it belongs to each Shop object, not to the class. 2) The main method is static, meaning it runs without any Shop object being created. 3) A static context has no implicit object, so it cannot refer to instance members like price. 4) Writing System.out.println(price) inside main therefore gives a compile-time error ('non-static variable price cannot be referenced from a static context'). 5) To use price you would need to create an object, e.g. Shop s = new Shop(); then print s.price.
Q378.Medium
Write a Java program that demonstrates whether a class can run without a main() method using a static block. The program should print "startup block executed" from a static block and then exit the JVM before any main method is needed. (Note: this behaviour worked only up to JDK 1.6; from JDK 1.7 onward a main method is required.)
Show answer & explanation
Answer:
public class StartupDemo {
    static {
        System.out.println("startup block executed");
        System.exit(0);
    }

    public static void main(String[] args) {
    }
}
Explanation: 1) The class StartupDemo has no main method. 2) A static block runs automatically when the class is loaded by the JVM. 3) Inside the static block we print "startup block executed". 4) System.exit(0) terminates the JVM immediately, so the JVM never looks for a main method. 5) This trick worked only until JDK 1.6; from JDK 1.7 the JVM checks for main() first and throws an error, so the program would not run on modern JDKs.
Q379.Medium
Write a Java program that demonstrates the FilterOutputStream class. The program should create a file named "notes.txt" in the current directory, wrap a FileOutputStream in a FilterOutputStream, write the string "Hello Mumbai!" to the file using the write(byte[]) method, then flush and close the streams, and finally print "Done" to the console.
Show answer & explanation
Answer:
import java.io.*;

public class FilterDemo {
    public static void main(String[] args) throws IOException {
        File data = new File("notes.txt");
        FileOutputStream file = new FileOutputStream(data);
        FilterOutputStream filter = new FilterOutputStream(file);
        String s = "Hello Mumbai!";
        byte b[] = s.getBytes();
        filter.write(b);
        filter.flush();
        filter.close();
        file.close();
        System.out.println("Done");
    }
}
Explanation: 1) Create a File object for "notes.txt". 2) Open a FileOutputStream on that file. 3) Wrap it in a FilterOutputStream so writes pass through the filter. 4) Convert the string "Hello Mumbai!" to a byte array with getBytes(). 5) Call filter.write(b) to write all bytes to the file. 6) Call flush() to push any buffered data, then close() the filter and the underlying file stream. 7) Print "Done" to confirm success.
Q380.Medium
Write a Java program that demonstrates the String indexOf() method overloads. Use the String "java is a simple language" and: (a) find the index of the substring "is" and of the substring "simple"; (b) find the index of "is" searching from index 4; (c) find the index of the character 'a'. Print each result on its own line. FileName: IndexOfDemo.java
Show answer & explanation
Answer:
public class IndexOfDemo {
    public static void main(String[] args) {
        String s = "java is a simple language";
        int i1 = s.indexOf("is");
        int i2 = s.indexOf("simple");
        System.out.println(i1 + "  " + i2);
        int i3 = s.indexOf("is", 4);
        System.out.println(i3);
        int i4 = s.indexOf('a');
        System.out.println(i4);
    }
}
Explanation: Step 1: s = "java is a simple language". Index positions: j=0,a=1,v=2,a=3,' '=4,i=5,s=6,' '=7,a=8,' '=9,s=10,i=11,m=12,p=13,l=14,e=15,' '=16,l=17,a=18,n=19,g=20,u=21,a=22,g=23,e=24. Step 2: s.indexOf("is") finds "is" starting at index 5. Step 3: s.indexOf("simple") finds "simple" starting at index 10. Step 4: s.indexOf("is", 4) searches from index 4 onward; the first "is" at index 5 is still found, so result is 5. Step 5: s.indexOf('a') returns the first 'a', which is at index 1. Step 6: Output: line1 "5 10", line2 "5", line3 "1".
Q381.Medium
Write a Java program that creates an empty StringBuilder, prints its default capacity, appends "Namaste", prints the capacity, appends "India is a great country", prints the capacity, calls ensureCapacity(20) and prints the capacity, then calls ensureCapacity(80) and prints the capacity.
Show answer & explanation
Answer:
class CapacityDemo {
    public static void main(String args[]) {
        StringBuilder sb = new StringBuilder();
        System.out.println(sb.capacity());
        sb.append("Namaste");
        System.out.println(sb.capacity());
        sb.append("India is a great country");
        System.out.println(sb.capacity());
        sb.ensureCapacity(20);
        System.out.println(sb.capacity());
        sb.ensureCapacity(80);
        System.out.println(sb.capacity());
    }
}
Explanation: 1) new StringBuilder() has default capacity 16, so first print gives 16. 2) Appending "Namaste" (7 chars) fits within 16, capacity stays 16. 3) Appending "India is a great country" (23 chars) makes total length 30, which exceeds 16, so capacity becomes (16*2)+2 = 34; print 34. 4) ensureCapacity(20): 20 is less than current 34, so no change; print 34. 5) ensureCapacity(80): 80 is greater than 34, so capacity becomes (34*2)+2 = 70; print 70.
Q382.Medium
Write a Java program that shows downcasting is possible when the instanceof operator is used. Create a parent class Animal and a child class Dog extending Animal. In Dog, write a static method test(Animal a) that checks 'if (a instanceof Dog)', then casts a to Dog and prints "downcasting successful". In main, create an Animal reference pointing to a Dog object and call Dog.test with it.
Show answer & explanation
Answer:
class Animal { }

class Dog extends Animal {
    static void test(Animal a) {
        if (a instanceof Dog) {
            Dog d = (Dog) a; // downcasting after instanceof check
            System.out.println("downcasting successful");
        }
    }

    public static void main(String[] args) {
        Animal a = new Dog();
        Dog.test(a);
    }
}
Explanation: 1. Animal is the parent class and Dog extends it. 2. In main, 'Animal a = new Dog();' makes the actual object a Dog (upcasting). 3. Dog.test(a) first checks 'a instanceof Dog' — this is true because the real object is a Dog. 4. Inside the if-block, 'Dog d = (Dog) a;' performs the downcast safely, so no ClassCastException occurs. 5. The program prints "downcasting successful". Without the instanceof check, a wrong object type would throw ClassCastException at runtime.
Q383.Medium
Write a Java program that demonstrates downcasting a parent reference to a child type WITHOUT using the instanceof operator. Create a parent class Vehicle and a child class Car extending Vehicle. In Car, write a static method check(Vehicle v) that casts v to Car (downcasting) and then prints "downcasting done". In main, create a Vehicle reference pointing to a Car object and call Car.check with it.
Show answer & explanation
Answer:
class Vehicle { }

class Car extends Vehicle {
    static void check(Vehicle v) {
        Car c = (Car) v; // downcasting without instanceof
        System.out.println("downcasting done");
    }

    public static void main(String[] args) {
        Vehicle v = new Car();
        Car.check(v);
    }
}
Explanation: 1. Vehicle is the parent class and Car extends it, so a Car IS-A Vehicle. 2. In main, 'Vehicle v = new Car();' creates an upcast reference: the actual object is a Car. 3. Car.check(v) receives the Vehicle reference and does 'Car c = (Car) v;' — an explicit downcast. 4. Because the real object is a Car, the cast succeeds at runtime (no ClassCastException) even though instanceof is not used. 5. The method then prints "downcasting done".
Q384.Medium
Write a Java program that shows a real use of the instanceof keyword. Declare an interface Shape. Class Circle implements Shape and has a method drawCircle() that prints "Drawing circle". Class Square implements Shape and has a method drawSquare() that prints "Drawing square". In main, create one Circle and one Square, store them in a Shape array, and loop over the array: use instanceof to check the actual type and call the matching method.
Show answer & explanation
Answer:
interface Shape {}

class Circle implements Shape {
    public void drawCircle() { System.out.println("Drawing circle"); }
}

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

public class InstanceofDemo {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(), new Square() };
        for (Shape s : shapes) {
            if (s instanceof Circle) {
                ((Circle) s).drawCircle();
            } else if (s instanceof Square) {
                ((Square) s).drawSquare();
            }
        }
    }
}
Explanation: 1) Shape is a marker interface with no methods; Circle and Square both implement it. 2) Circle has drawCircle() and Square has drawSquare(), but the Shape reference type does not know these methods. 3) A Shape array holds one Circle and one Square object. 4) The for-each loop visits each element as a Shape reference. 5) instanceof checks the real object type: if it is a Circle, the reference is downcast and drawCircle() runs; if it is a Square, drawSquare() runs. 6) Output: "Drawing circle" then "Drawing square".
Q385.Medium
Write a Java program that creates a ThreadGroup named "TeamGroup", starts three threads named "alpha", "beta" and "gamma" inside that group (each thread prints its own name), then prints the thread group's name and lists the group's active threads. Save the program as TeamGroupDemo.java.
Show answer & explanation
Answer:
public class TeamGroupDemo implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        TeamGroupDemo job = new TeamGroupDemo();
        ThreadGroup tg = new ThreadGroup("TeamGroup");

        Thread t1 = new Thread(tg, job, "alpha");
        t1.start();
        Thread t2 = new Thread(tg, job, "beta");
        t2.start();
        Thread t3 = new Thread(tg, job, "gamma");
        t3.start();

        System.out.println("Thread Group Name: " + tg.getName());
        tg.list();
    }
}
Explanation: 1) The class implements Runnable so its run() method can be used by threads; run() prints the current thread's name. 2) In main, a ThreadGroup object tg is created with the name "TeamGroup". 3) Three Thread objects are created using the constructor Thread(ThreadGroup, Runnable, String), so each thread belongs to tg and gets the name alpha, beta or gamma. 4) start() is called on each thread, so each run() prints its own name (order may vary). 5) tg.getName() prints "Thread Group Name: TeamGroup". 6) tg.list() prints information about the threads in the group to standard output.
Q386.Medium
Write a Java program that demonstrates the ThreadGroup method isDestroyed(). Create a ThreadGroup named "KabaddiGroup", start two threads in it that each print a message after a short sleep, then destroy the group and print whether it is destroyed using isDestroyed(). FileName: IsDestroyedDemo.java
Show answer & explanation
Answer:
public class IsDestroyedDemo {
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup kabaddiGroup = new ThreadGroup("KabaddiGroup");
        WorkerThread t1 = new WorkerThread(kabaddiGroup, "Raider");
        WorkerThread t2 = new WorkerThread(kabaddiGroup, "Defender");
        t1.join();
        t2.join();
        kabaddiGroup.destroy();
        System.out.println("Is group destroyed? " + kabaddiGroup.isDestroyed());
    }
}

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

    public void run() {
        for (int j = 0; j < 50; j++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Interrupted: " + e);
            }
        }
        System.out.println(getName() + " thread has finished executing");
    }
}
Explanation: 1. A ThreadGroup KabaddiGroup is created. 2. Two WorkerThread objects join the group via super(group, name) and start running. 3. Each thread loops with Thread.sleep(5) for 50 iterations, then prints its finished message. 4. main sleeps 200 ms so the threads complete, then calls destroy() on the group. 5. isDestroyed() returns true after destroy(), so the program prints that the group is destroyed.
Q387.Medium
Write a Java program that demonstrates the ThreadGroup method activeCount(). Create a ThreadGroup named "CricketGroup". Create three threads in this group, each printing its name and sleeping briefly in a loop. After starting them, print the number of active threads in the group using activeCount(). FileName: ActiveCountDemo.java
Show answer & explanation
Answer:
public class ActiveCountDemo {
    public static void main(String[] args) {
        ThreadGroup cricketGroup = new ThreadGroup("CricketGroup");
        for (int i = 1; i <= 3; i++) {
            new PlayerThread(cricketGroup, "Player-" + i);
        }
        System.out.println("Active threads in group: " + cricketGroup.activeCount());
    }
}

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

    public void run() {
        for (int j = 0; j < 500; j++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Interrupted: " + e);
            }
        }
        System.out.println(getName() + " finished");
    }
}
Explanation: 1. A ThreadGroup called CricketGroup is created. 2. Three PlayerThread objects are created; each constructor calls super(group, name) so the thread belongs to the group, then start() begins it. 3. Each thread runs a loop with Thread.sleep(5) for 500 iterations, so they are still alive when activeCount() is called. 4. activeCount() returns the number of active threads in the group (3 here, since all three are still running). 5. The program prints the count, and later each thread prints its finished message.
Q388.Medium
Write a Java program that demonstrates the ThreadGroup activeGroupCount() method. Create a parent thread group "Warehouse" and two child thread groups "Packing" and "Dispatch" inside it, start one thread in each child group, and print the number of active subgroups of the parent group using activeGroupCount(). Use the file name ActiveGroupDemo.java.
Show answer & explanation
Answer:
class WorkThread extends Thread {
    WorkThread(String name, ThreadGroup grp) {
        super(grp, name);
        start();
    }
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Interrupted: " + e);
            }
        }
        System.out.println(Thread.currentThread().getName() + " finished");
    }
}

public class ActiveGroupDemo {
    public static void main(String[] args) {
        ThreadGroup parent = new ThreadGroup("Warehouse");
        ThreadGroup packing = new ThreadGroup(parent, "Packing");
        ThreadGroup dispatch = new ThreadGroup(parent, "Dispatch");
        WorkThread t1 = new WorkThread("Packer1", packing);
        WorkThread t2 = new WorkThread("Dispatcher1", dispatch);
        System.out.println("Active subgroups of Warehouse: " + parent.activeGroupCount());
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("Main interrupted: " + e);
        }
    }
}
Explanation: 1. WorkThread extends Thread and its constructor calls super(grp, name) to attach to a ThreadGroup, then start(). 2. run() sleeps 20 times for 5 ms and then prints the thread name. 3. main() creates parent group "Warehouse" and two child groups "Packing" and "Dispatch" using new ThreadGroup(parent, name). 4. One WorkThread is started in each child group. 5. parent.activeGroupCount() returns the number of active subgroups of Warehouse, which is 2, and it is printed. 6. join() is used so main waits for both threads to finish.
Q389.Medium
Write a Java program that demonstrates the ThreadGroup destroy() method. Create a thread group named "SalesTeam", start two threads in it that each sleep briefly in a loop, and after the threads finish, call destroy() on the thread group and print whether it is destroyed. Use the file name DestroyDemo.java.
Show answer & explanation
Answer:
class SalesThread extends Thread {
    SalesThread(String name, ThreadGroup grp) {
        super(grp, name);
        start();
    }
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Interrupted: " + e);
            }
        }
        System.out.println(Thread.currentThread().getName() + " finished");
    }
}

public class DestroyDemo {
    public static void main(String[] args) {
        ThreadGroup grp = new ThreadGroup("SalesTeam");
        SalesThread t1 = new SalesThread("AgentA", grp);
        SalesThread t2 = new SalesThread("AgentB", grp);
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("Main interrupted: " + e);
        }
        grp.destroy();
        System.out.println("Thread group destroyed successfully");
    }
}
Explanation: 1. SalesThread extends Thread and its constructor calls super(grp, name) to join the given ThreadGroup, then start(). 2. run() loops 20 times sleeping 5 ms each, then prints the thread name when finished. 3. main() creates a ThreadGroup named "SalesTeam" and two SalesThread objects in it. 4. main() calls join() on both threads so it waits until they finish executing. 5. Once no active threads remain in the group, grp.destroy() is called, which destroys the group and its subgroups. 6. Finally a message is printed confirming the group was destroyed.
Q390.Medium
Write a Java program that demonstrates the ThreadGroup method enumerate(). Create a ThreadGroup named "BatchGroup", start three threads in it (named "Task-1", "Task-2", "Task-3") that each sleep briefly and print a completion message, then use enumerate(Thread[]) to count and print how many threads of the group are currently active.
Show answer & explanation
Answer:
public class EnumerateDemo {
    public static void main(String[] args) {
        ThreadGroup batchGroup = new ThreadGroup("BatchGroup");

        Thread t1 = new Thread(batchGroup, new Job(), "Task-1");
        Thread t2 = new Thread(batchGroup, new Job(), "Task-2");
        Thread t3 = new Thread(batchGroup, new Job(), "Task-3");
        t1.start();
        t2.start();
        t3.start();

        Thread[] list = new Thread[batchGroup.activeCount() + 2];
        int count = batchGroup.enumerate(list);
        System.out.println("Threads enumerated in " + batchGroup.getName() + " = " + count);

        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            System.out.println("Interrupted: " + e);
        }
    }
}

class Job implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Exception encountered: " + e);
            }
        }
        System.out.println(Thread.currentThread().getName() + " thread has finished executing");
    }
}
Explanation: 1. A ThreadGroup "BatchGroup" is created and three threads Task-1, Task-2, Task-3 are created in it and started. 2. An array of Thread is allocated with size activeCount()+2 to be safe. 3. batchGroup.enumerate(list) copies the group's active threads into the array and returns the number copied; that count is printed. 4. main() then joins all three threads so the program waits for them to finish; each run() sleeps briefly and prints its completion message.
Q391.Medium
Write a Java program that demonstrates the ThreadGroup method getMaxPriority(). Create a ThreadGroup named "TeamGroup" with a maximum priority of 7, create two threads in that group (named "Worker-A" and "Worker-B") that each sleep briefly and then print a completion message, and finally print the maximum priority of the group.
Show answer & explanation
Answer:
public class MaxPriorityDemo {
    public static void main(String[] args) {
        ThreadGroup teamGroup = new ThreadGroup("TeamGroup");
        teamGroup.setMaxPriority(7);

        Thread t1 = new Thread(teamGroup, new Worker(), "Worker-A");
        Thread t2 = new Thread(teamGroup, new Worker(), "Worker-B");
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("Interrupted: " + e);
        }

        System.out.println("Maximum priority of " + teamGroup.getName() + " = " + teamGroup.getMaxPriority());
    }
}

class Worker implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Exception encountered: " + e);
            }
        }
        System.out.println(Thread.currentThread().getName() + " thread has finished executing");
    }
}
Explanation: 1. A ThreadGroup "TeamGroup" is created and its maximum priority is set to 7 using setMaxPriority(). 2. Two threads Worker-A and Worker-B are created inside that group using the Thread(ThreadGroup, Runnable, String) constructor and started. 3. Each thread's run() loops 5 times sleeping 5 ms, then prints its name with a completion message. 4. main() waits for both threads with join(), then calls teamGroup.getMaxPriority() and prints the value, which is 7.
Q392.Medium
Write a Java program that demonstrates the getParent() method of ThreadGroup. Create a parent ThreadGroup named 'ParentGroup' and a child ThreadGroup named 'ChildGroup' as its child. Create a thread named 'MyThread' in the child group that sleeps for 5 milliseconds in a loop 100 times, catching InterruptedException and printing a message. After the loop, print the thread name and that it has finished executing. In the main method, after starting the thread, print the parent group of the child group using getParent(). FileName: GetParentDemo.java
Show answer & explanation
Answer:
public class GetParentDemo {
    public static void main(String[] args) {
        ThreadGroup parent = new ThreadGroup("ParentGroup");
        ThreadGroup child = new ThreadGroup(parent, "ChildGroup");
        MyThread t = new MyThread("MyThread", child);
        System.out.println("Parent of ChildGroup: " + child.getParent().getName());
    }
}

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 parent ThreadGroup 'ParentGroup'. 2. Create a child ThreadGroup 'ChildGroup' with parent as its parent. 3. Create a MyThread named 'MyThread' in the child group; its constructor calls start(). 4. In run(), loop 100 times, sleeping 5 ms each time, catching InterruptedException and printing a message. 5. After the loop, print the thread's name and that it has finished. 6. In main, call child.getParent().getName() to print the parent group's name, which is 'ParentGroup'.
Q393.Medium
Write a Java program that illustrates the use of the isDaemon() method. Create a class 'WorkerThread' extending Thread whose constructor takes a thread name and a ThreadGroup, calls super(tgrp, tName) and then start(). Override run() to loop 100 times calling Thread.sleep(5) inside a try-catch for InterruptedException (printing "Exception encountered: " + e on catch), and after the loop print the current thread's name followed by " thread has finished executing". In main, create a ThreadGroup named "DemoGroup", create a WorkerThread named "worker-1" in that group, and print whether it is a daemon thread using isDaemon().
Show answer & explanation
Answer:
class WorkerThread extends Thread {
    WorkerThread(String tName, ThreadGroup tgrp) {
        super(tgrp, tName);
        start();
    }

    public void run() {
        for (int j = 0; j < 100; j++) {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Exception encountered: " + e);
            }
        }
        System.out.println(Thread.currentThread().getName() + " thread has finished executing");
    }
}

class IsDaemonExample {
    public static void main(String args[]) {
        ThreadGroup grp = new ThreadGroup("DemoGroup");
        WorkerThread t = new WorkerThread("worker-1", grp);
        System.out.println("Is worker-1 a daemon thread? " + t.isDaemon());
    }
}
Explanation: 1) WorkerThread extends Thread and its constructor calls super(tgrp, tName) to attach the thread to the given ThreadGroup with the given name, then start() begins execution. 2) run() loops 100 times, sleeping 5 ms each iteration inside a try-catch that handles InterruptedException. 3) After the loop it prints the thread's name and a completion message. 4) In main, a ThreadGroup "DemoGroup" is created and a WorkerThread "worker-1" is started in it. 5) isDaemon() returns false because threads created from a non-daemon main thread are non-daemon by default, so the program prints 'Is worker-1 a daemon thread? false'.
Q394.Medium
Write a Java program that shows the real use of the this() constructor call for constructor chaining. Create a class Employee with fields empId (int), empName (String), department (String) and salary (double). The 3-argument constructor should set empId, empName and department. The 4-argument constructor should reuse the 3-argument constructor by calling this(empId, empName, department) and then set salary. Include a display() method that prints all four fields, and a main method that creates one Employee with 3 arguments and one with 4 arguments and calls display() on both.
Show answer & explanation
Answer:
class Employee{
int empId;
String empName,department;
double salary;
Employee(int empId,String empName,String department){
this.empId=empId;
this.empName=empName;
this.department=department;
}
Employee(int empId,String empName,String department,double salary){
this(empId,empName,department);//reusing constructor
this.salary=salary;
}
void display(){System.out.println(empId+" "+empName+" "+department+" "+salary);}
}
class TestThis7{
public static void main(String args[]){
Employee e1=new Employee(201,"Ravi","Accounts");
Employee e2=new Employee(202,"Meera","Accounts",45000.0);
e1.display();
e2.display();
}}
Explanation: 1) The class Employee has four fields: empId, empName, department and salary. 2) The 3-argument constructor initialises empId, empName and department. 3) The 4-argument constructor starts with this(empId, empName, department); which calls the 3-argument constructor, so the common initialisation is reused (constructor chaining). 4) After the this() call, it sets this.salary = salary. 5) main creates e1 with 3 arguments (salary stays 0.0) and e2 with 4 arguments (salary 45000.0). 6) display() prints: 201 Ravi Accounts 0.0 and 202 Meera Accounts 45000.0.
Q395.Medium
Write a Java program that demonstrates the rule that a call to this() must be the first statement in a constructor. Create a class Employee with fields empId (int), empName (String), department (String) and salary (double). Provide a 3-argument constructor that sets empId, empName and department. Provide a 4-argument constructor that sets salary first and then tries to call this(empId, empName, department). Compile-time behaviour should be shown by placing the this() call after the salary assignment (which causes a compile-time error). Also include a display() method that prints all four fields, and a main method that creates Employee objects and calls display().
Show answer & explanation
Answer:
class Employee{
int empId;
String empName,department;
double salary;
Employee(int empId,String empName,String department){
this.empId=empId;
this.empName=empName;
this.department=department;
}
Employee(int empId,String empName,String department,double salary){
this.salary=salary;
this(empId,empName,department);//Compile-time error: this() must be first statement
}
void display(){System.out.println(empId+" "+empName+" "+department+" "+salary);}
}
class TestThis8{
public static void main(String args[]){
Employee e1=new Employee(201,"Ravi","Accounts");
Employee e2=new Employee(202,"Meera","Accounts",45000.0);
e1.display();
e2.display();
}}
Explanation: 1) The class Employee has four fields: empId, empName, department and salary. 2) The 3-argument constructor initialises empId, empName and department using this. 3) The 4-argument constructor first assigns this.salary = salary and then calls this(empId, empName, department). 4) Java requires a constructor call via this() to be the very first statement in a constructor, so this program does not compile (compile-time error). 5) To fix it, move this(empId, empName, department); to the first line and then assign this.salary = salary. 6) The main method creates two Employee objects and display() prints all four fields.
Q396.Medium
Write a Java program that demonstrates passing the 'this' keyword as an argument in a constructor call. Create a class named 'Customer' with an integer field 'custId' and a constructor that sets it. Create another class named 'Order' that holds a reference to a Customer object; its constructor takes a Customer object and assigns it to its field. In the Customer constructor, create an Order object by passing 'this' to the Order constructor. Add a method in Order named 'showCustomerId()' that prints the customer's id. In main, create a Customer with id 501 and call showCustomerId() on the order created inside it.
Show answer & explanation
Answer:
class Order {
    Customer cust;
    Order(Customer cust) {
        this.cust = cust;
    }
    void showCustomerId() {
        System.out.println(cust.custId);
    }
}

class Customer {
    int custId;
    Order order;
    Customer(int custId) {
        this.custId = custId;
        this.order = new Order(this);
    }
}

public class Main {
    public static void main(String[] args) {
        Customer c = new Customer(501);
        c.order.showCustomerId();
    }
}
Explanation: 1) The Customer constructor receives custId and stores it using this.custId. 2) Inside the constructor, 'this' refers to the current Customer object; it is passed to the Order constructor. 3) Order stores that reference in its field cust. 4) showCustomerId() reads cust.custId and prints it. 5) main creates Customer(501), so the Order holds that same object and prints 501.
Q397.Medium
Write a Java program that declares two short variables p = 5 and q = 5. First show that p = p + q causes a compile-time error (because the result of short + short is int), then fix it by using the compound assignment p += q and print the final value of p.
Show answer & explanation
Answer:
public class ShortAddDemo {
    public static void main(String[] args) {
        short p = 5;
        short q = 5;
        // p = p + q; // Compile-time error: 5 + 5 is int, cannot assign int to short
        p += q; // internally p = (short)(p + q), so this is fine
        System.out.println(p);
    }
}
Explanation: Step 1: short + short is promoted to int, so writing p = p + q tries to store an int into a short and fails to compile. Step 2: The compound assignment p += q performs an implicit narrowing cast, i.e. p = (short)(p + q). Step 3: p + q = 5 + 5 = 10, which fits in a short, so p becomes 10. Step 4: The program prints 10.
Q398.Medium
Write a Java program that demonstrates the difference between the signed right shift operator >> and the unsigned right shift operator >>> in Java. Print the results of 24>>2, 24>>>2, -24>>2 and -24>>>2.
Show answer & explanation
Answer:
public class ShiftOperatorDemo {
    public static void main(String[] args) {
        // For a positive number, >> and >>> behave the same
        System.out.println(24>>2);
        System.out.println(24>>>2);
        // For a negative number, >>> fills the sign bit (MSB) with 0
        System.out.println(-24>>2);
        System.out.println(-24>>>2);
    }
}
Explanation: 1) 24>>2 divides 24 by 2^2=4, giving 6. 2) 24>>>2 also gives 6 because for positive numbers the sign bit is already 0. 3) -24>>2 is an arithmetic shift: -24/4 = -6 (sign preserved). 4) -24>>>2 is a logical shift: the sign bit is filled with 0, so the 32-bit pattern of -24 (0xFFFFFFE8) becomes 0x3FFFFFFA = 1073741818. 5) Output: 6, 6, -6, 1073741818.
Q399.Medium
Write a Java program named LogicCheck.java that demonstrates the difference between the logical AND operator (&&) and the bitwise AND operator (&). Declare int x = 8, y = 3, z = 15. Print the result of (x < y && x++ < z), then print x. Next print the result of (x < y & x++ < z), then print x again.
Show answer & explanation
Answer:
public class LogicCheck {
    public static void main(String args[]) {
        int x = 8;
        int y = 3;
        int z = 15;
        System.out.println(x < y && x++ < z);
        System.out.println(x);
        System.out.println(x < y & x++ < z);
        System.out.println(x);
    }
}
Explanation: 1) x=8, y=3, z=15. First check x<y is 8<3 = false. 2) With && (short-circuit), since the left side is false, the right side x++<z is NOT evaluated, so x stays 8. Output: false then 8. 3) Next, x<y & x++<z uses bitwise &, which always evaluates both sides. x<y is false, but x++<z is still evaluated: 8<15 is true and x becomes 9. false & true = false. 4) So the program prints false, 8, false, 9.
Q400.Medium
Write a Java program named SpeedTest.java that compares the performance of string concatenation using the String class versus the StringBuffer class. Create two methods: one that starts with the string "Cricket" and appends "India" to it 8000 times using the + operator, and another that starts with a StringBuffer initialized to "Cricket" and appends "India" 8000 times using append(). In main(), measure and print the time taken (in milliseconds) by each method using System.currentTimeMillis().
Show answer & explanation
Answer:
public class SpeedTest {
    public static String concatWithString() {
        String s = "Cricket";
        for (int i = 0; i < 8000; i++) {
            s = s + "India";
        }
        return s;
    }
    public static String concatWithStringBuffer() {
        StringBuffer sb = new StringBuffer("Cricket");
        for (int i = 0; i < 8000; i++) {
            sb.append("India");
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        concatWithString();
        System.out.println("Time taken by Concating with String: " + (System.currentTimeMillis() - startTime) + "ms");
        startTime = System.currentTimeMillis();
        concatWithStringBuffer();
        System.out.println("Time taken by Concating with StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
    }
}
Explanation: 1) concatWithString() repeatedly does s = s + "India"; each + creates a brand-new String object, so 8000 new objects are created — slow. 2) concatWithStringBuffer() uses a single StringBuffer and calls append() 8000 times; the buffer grows internally without creating a new object each time — fast. 3) main() records the start time with System.currentTimeMillis(), runs each method, and prints the elapsed milliseconds. 4) Comparing the two printed times shows StringBuffer is much faster for repeated concatenation.
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