Coding Questions Questions

Question Bank › Technical › Java › Coding Questions

12345

Other questions

Q401.Medium
Write a Java program to demonstrate that the hashCode of a String changes after concatenation, while the hashCode of a StringBuffer remains the same after appending. Use the string "hello" and append "world".
Show answer & explanation
Answer:
public class HashCodeDemo {
    public static void main(String[] args) {
        System.out.println("Hashcode test of String:");
        String str = "hello";
        System.out.println(str.hashCode());
        str = str + "world";
        System.out.println(str.hashCode());

        System.out.println("Hashcode test of StringBuffer:");
        StringBuffer sb = new StringBuffer("hello");
        System.out.println(sb.hashCode());
        sb.append("world");
        System.out.println(sb.hashCode());
    }
}
Explanation: 1. Print a header for String hashcode test. 2. Create a String str with value "hello" and print its hashCode. 3. Concatenate "world" to str (this creates a new String object) and print the new hashCode; it will be different. 4. Print a header for StringBuffer hashcode test. 5. Create a StringBuffer sb with value "hello" and print its hashCode. 6. Append "world" to sb (modifies the same object) and print the hashCode again; it remains the same because StringBuffer does not override hashCode, so it uses the default Object.hashCode (identity-based).
Q402.Medium
Write a Java program that demonstrates the use of FilterInputStream. The program should read the contents of a file named "C:\\data\\input.txt" using a BufferedInputStream (which is a FilterInputStream) and print each character to the console.
Show answer & explanation
Answer:
import java.io.*;

public class FilterStreamDemo {
    public static void main(String[] args) {
        File file = new File("C:\\data\\input.txt");
        try (FileInputStream fileInputStream = new FileInputStream(file);
             FilterInputStream filterInputStream = new BufferedInputStream(fileInputStream)) {
            int ch;
            while ((ch = filterInputStream.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Explanation: 1. Import java.io.* for file I/O classes. 2. Create a File object pointing to "C:\\data\\input.txt". 3. Use try-with-resources to automatically close the streams. 4. Wrap a FileInputStream with a BufferedInputStream (which extends FilterInputStream) to add buffering. 5. Read bytes one by one using read() until it returns -1 (end of file). 6. Cast each byte to char and print it. 7. Catch IOException to handle any I/O errors.
Q403.Medium
Write a Java program that registers a shutdown hook using an anonymous inner class. The program should print "cleanup done for Mumbai server.." from the hook, and from the main thread print "Main is going to sleep... press ctrl+c to exit", then sleep for 2000 milliseconds. FileName: ServerShutdown.java
Show answer & explanation
Answer:
public class ServerShutdown{
public static void main(String[] args)throws Exception {

Runtime rt=Runtime.getRuntime();

rt.addShutdownHook(new Thread(){
public void run(){
    System.out.println("cleanup done for Mumbai server..");
    }
}
);

System.out.println("Main is going to sleep... press ctrl+c to exit");
try{Thread.sleep(2000);}catch (Exception e) {}
}
}
Explanation: Step 1: Obtain the Runtime object using Runtime.getRuntime(). Step 2: Register a shutdown hook with addShutdownHook(new Thread(){...}) where the anonymous Thread overrides run() to print the cleanup message. Step 3: The main thread prints the sleep message. Step 4: Thread.sleep(2000) pauses main for 2 seconds; when the JVM exits (e.g. ctrl+c), the hook's run() executes and prints the cleanup line.
Q404.Medium
Write a Java program named RemoveHookDemo.java that registers a shutdown hook thread which prints "Goodbye ...", prints a starting message, waits for 2 seconds, then removes the registered shutdown hook using removeShutdownHook(), and finally prints a terminating message.
Show answer & explanation
Answer:
public class RemoveHookDemo {

    static class Farewell extends Thread {
        public void run() {
            System.out.println("Goodbye ...");
        }
    }

    public static void main(String[] args) {
        try {
            Farewell fw = new Farewell();

            Runtime.getRuntime().addShutdownHook(fw);

            System.out.println("The program is starting ...");

            System.out.println("Waiting for 2 seconds ...");
            Thread.sleep(2000);

            Runtime.getRuntime().removeShutdownHook(fw);

            System.out.println("The program is ending ...");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Explanation: 1. The Farewell class extends Thread and overrides run() to print "Goodbye ...". 2. In main, an object fw of Farewell is created and registered as a shutdown hook via Runtime.getRuntime().addShutdownHook(fw). 3. The program prints the starting message, then sleeps 2 seconds using Thread.sleep(2000). 4. removeShutdownHook(fw) unregisters the hook, so it will not run at JVM exit. 5. The terminating message is printed; since the hook was removed, "Goodbye ..." is never printed.
Q405.Medium
Write a Java program to compare the performance of StringBuffer and StringBuilder. The program should measure the time taken to append the string "India" 20000 times to a StringBuffer initialized with "Bharat" and to a StringBuilder initialized with "Bharat". Print the time taken by each in milliseconds.
Show answer & explanation
Answer:
public class PerformanceTest {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer("Bharat");
        for (int i = 0; i < 20000; i++) {
            sb.append("India");
        }
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");

        startTime = System.currentTimeMillis();
        StringBuilder sb2 = new StringBuilder("Bharat");
        for (int i = 0; i < 20000; i++) {
            sb2.append("India");
        }
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
    }
}
Explanation: 1. Record the start time using System.currentTimeMillis(). 2. Create a StringBuffer initialized with "Bharat" and append "India" 20000 times in a loop. 3. Compute and print the elapsed time for StringBuffer. 4. Reset the start time, then create a StringBuilder initialized with "Bharat" and append "India" 20000 times. 5. Compute and print the elapsed time for StringBuilder. 6. The program shows that StringBuilder is generally faster because it is not synchronized.
Q406.Medium
Write a Java program that creates two threads using anonymous inner classes that implement Runnable. One thread should print "Hello from Thread A" and the other should print "Hello from Thread B". Start both threads.
Show answer & explanation
Answer:
public class MultiTaskDemo {
    public static void main(String[] args) {
        Runnable taskA = new Runnable() {
            public void run() {
                System.out.println("Hello from Thread A");
            }
        };
        Runnable taskB = new Runnable() {
            public void run() {
                System.out.println("Hello from Thread B");
            }
        };
        Thread t1 = new Thread(taskA);
        Thread t2 = new Thread(taskB);
        t1.start();
        t2.start();
    }
}
Explanation: 1. Two anonymous inner classes implement the Runnable interface. 2. Each overrides the run() method to print a specific message. 3. Two Thread objects are created, each taking one Runnable. 4. Calling start() on each thread begins execution, and the messages are printed.
Q407.Medium
Write a Java program that demonstrates that the String replaceAll() method throws a PatternSyntaxException when an improper (invalid) regular expression is supplied. Use the input string "Ravi likes cricket, Mumbai Indians is a strong team." and an invalid regex consisting of a single backslash. Print the original string, then call replaceAll() with that invalid regex and the replacement "Delhi ", and print the result. (The program is expected to throw PatternSyntaxException at runtime.)
Show answer & explanation
Answer:
public class ReplaceAllDemo
{
    public static void main(String[] args)
    {
        String str = "Ravi likes cricket, Mumbai Indians is a strong team.";
        System.out.println(str);

        String regex = "\\"; // invalid regular expression

        // invoking replaceAll() raises PatternSyntaxException
        str = str.replaceAll(regex, "Delhi ");

        System.out.println(str);
    }
}
Explanation: Step 1: Declare and print the input string "Ravi likes cricket, Mumbai Indians is a strong team.". Step 2: Set regex = "\\" which in Java source is a single backslash character — an invalid regular expression. Step 3: Call str.replaceAll(regex, "Delhi "); the regex engine tries to compile the single backslash and fails. Step 4: Java throws java.util.regex.PatternSyntaxException (unclosed/illegal escape), so the second println is never reached. Step 5: The program therefore prints the original string and then terminates with the exception.
Q408.Medium
Write a Java program that uses the replaceAll() method to insert a space before and after every character of a string. Take the input string "IncredibleIndia", print it, then replace every empty match (regex "") with a single space " " and print the modified string. Name the file ReplaceAllSpaceDemo.java and the class ReplaceAllSpaceDemo.
Show answer & explanation
Answer:
public class ReplaceAllSpaceDemo
{
    // main method
    public static void main(String[] args)
    {
        // input string
        String text = "IncredibleIndia";
        System.out.println(text);

        String regex = "";
        // adding a white space before and after every character of the input string
        text = text.replaceAll(regex, " ");

        System.out.println(text);
    }
}
Explanation: Step 1: Declare a String text with value "IncredibleIndia" and print it. Step 2: Set regex = "" (an empty regular expression). An empty regex matches the zero-width position before every character and at the end of the string. Step 3: Call text.replaceAll("", " "). Java inserts the replacement " " at every such empty match, i.e. before each character and once at the end. Step 4: So each character gets a space before it, and one extra space is added at the very end. Step 5: The printed result is " I n c r e d i b l e I n d i a " (a leading space, a space between every pair of characters, and a trailing space).
Q409.Medium
Write a Java program that demonstrates an abstract class with an abstract method. Create an abstract class 'Vehicle' that has one abstract method 'move'. Provide an implementation of this method in a subclass 'Car'. In the main method, create an object of 'Car' using a 'Vehicle' reference and call the 'move' method.
Show answer & explanation
Answer:
abstract class Vehicle {
    abstract void move();
}

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

public class Main {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.move();
    }
}
Explanation: 1. Define an abstract class 'Vehicle' with an abstract method 'move()' (no body). 2. Create a subclass 'Car' that extends 'Vehicle' and provides the implementation of 'move()' to print "Car is moving safely". 3. In the main method, instantiate 'Car' but assign it to a 'Vehicle' reference (polymorphism). 4. Call 'move()' on the reference, which invokes the overridden method in 'Car'. 5. The program compiles and runs, printing the message.
Q410.Medium
Write a Java program that shows the real scenario of an abstract class. Make Shape an abstract class with an abstract method draw(). Rectangle and Circle extend Shape and implement draw() printing "drawing rectangle" and "drawing circle" respectively. Add a factory method getShape(String type) that returns a new Rectangle when type is "rectangle" and a new Circle otherwise. In main, obtain a Shape from the factory using "circle" and call draw().
Show answer & explanation
Answer:
abstract class Shape {
    abstract void draw();
}

class Rectangle extends Shape {
    void draw() { System.out.println("drawing rectangle"); }
}

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

public class TestAbstraction1 {
    static Shape getShape(String type) {
        if (type.equals("rectangle")) {
            return new Rectangle();
        }
        return new Circle();
    }

    public static void main(String[] args) {
        Shape s = getShape("circle");
        s.draw();
    }
}
Explanation: 1) Shape is abstract with abstract method draw(), so the end user never needs to know the concrete class. 2) Rectangle and Circle extend Shape and provide their own draw() implementations. 3) The factory method getShape() returns a Rectangle for "rectangle" and a Circle otherwise, hiding object creation. 4) main calls getShape("circle"), so s refers to a Circle object. 5) s.draw() invokes Circle's draw(), printing "drawing circle".
Q411.Medium
Write a Java program showing that an abstract class can have a constructor, a data member, an abstract method and a non-abstract method. Create an abstract class Vehicle with a data member String model, a constructor that sets the model and prints "Vehicle created: <model>", an abstract method start(), and a non-abstract method changeGear() that prints "Gear changed". Then create a child class Car extending Vehicle whose constructor calls the parent constructor with model "Swift", and which implements start() to print "Car started safely". In main(), create a Car object and call start() and changeGear().
Show answer & explanation
Answer:
abstract class Vehicle {
    String model;
    Vehicle(String model) {
        this.model = model;
        System.out.println("Vehicle created: " + model);
    }
    abstract void start();
    void changeGear() {
        System.out.println("Gear changed");
    }
}

class Car extends Vehicle {
    Car() {
        super("Swift");
    }
    void start() {
        System.out.println("Car started safely");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.start();
        v.changeGear();
    }
}
Explanation: 1) The abstract class Vehicle holds a data member model, a constructor, an abstract method start() and a concrete method changeGear(). 2) The Car constructor calls super("Swift"), so the Vehicle constructor runs first and prints "Vehicle created: Swift". 3) Car implements start(), so the abstract method is satisfied and Car becomes concrete. 4) In main(), new Car() triggers the constructor chain and prints the creation message. 5) Calling v.start() runs Car's start() printing "Car started safely", and v.changeGear() runs the inherited method printing "Gear changed".
Q412.Medium
Write a Java program that demonstrates how an abstract class can provide partial implementation of an interface. Create an interface PaymentGateway with four methods: pay(), refund(), checkStatus() and cancel(). Then create an abstract class PartialGateway that implements PaymentGateway and provides the implementation of only pay() (print "Payment processed") and checkStatus() (print "Status checked"). Finally, create a concrete class UpiGateway extending PartialGateway that implements the remaining methods refund() (print "Refund done") and cancel() (print "Payment cancelled"). In main(), create a UpiGateway object and call all four methods.
Show answer & explanation
Answer:
interface PaymentGateway {
    void pay();
    void refund();
    void checkStatus();
    void cancel();
}

abstract class PartialGateway implements PaymentGateway {
    public void pay() {
        System.out.println("Payment processed");
    }
    public void checkStatus() {
        System.out.println("Status checked");
    }
}

class UpiGateway extends PartialGateway {
    public void refund() {
        System.out.println("Refund done");
    }
    public void cancel() {
        System.out.println("Payment cancelled");
    }
}

public class Main {
    public static void main(String[] args) {
        UpiGateway g = new UpiGateway();
        g.pay();
        g.refund();
        g.checkStatus();
        g.cancel();
    }
}
Explanation: 1) The interface PaymentGateway declares four abstract methods, so any implementing class must eventually define all four. 2) The abstract class PartialGateway implements the interface but only defines pay() and checkStatus(); it leaves refund() and cancel() unimplemented, which is allowed because the class is abstract. 3) The concrete class UpiGateway extends PartialGateway and supplies the two remaining methods refund() and cancel(), so all four methods are now implemented. 4) In main(), a UpiGateway object is created and all four methods are called, printing the four messages in order.
Q413.Medium
Write a Java program to demonstrate that Java does not support multiple inheritance with classes. Create two classes, X and Y, each with a method display() that prints different messages. Then create a class Z that attempts to extend both X and Y. Show the compile-time error by commenting the erroneous line and explaining why it occurs.
Show answer & explanation
Answer:
class X {
    void display() {
        System.out.println("Message from X");
    }
}

class Y {
    void display() {
        System.out.println("Message from Y");
    }
}

// Uncommenting the following line will cause a compile-time error
// class Z extends X, Y { }

public class MultipleInheritanceDemo {
    public static void main(String[] args) {
        System.out.println("Java does not support multiple inheritance with classes.");
        System.out.println("If class Z extended both X and Y, and both have display(), the compiler would not know which display() to call.");
    }
}
Explanation: 1. Class X and class Y each define a method display() with different implementations. 2. Java does not allow a class to extend more than one class, so 'class Z extends X, Y' is illegal and causes a compile-time error. 3. The error occurs because if Z inherited both X and Y, and both have display(), a call to display() on a Z object would be ambiguous. 4. To avoid such ambiguity, Java disallows multiple inheritance of classes. 5. The program demonstrates this by commenting out the erroneous line and printing an explanation.
Q414.Medium
Write a Java program using nested loops and the continue statement. The outer loop runs for i = 0 to 2 (inclusive). The inner loop runs for j = i to 5 (inclusive). If j equals 3, skip the rest of the inner loop body using continue; otherwise print the value of j.
Show answer & explanation
Answer:
public class SkipExample {
    public static void main(String[] args) {
        for (int i = 0; i <= 2; i++) {
            for (int j = i; j <= 5; j++) {
                if (j == 3) {
                    continue;
                }
                System.out.println(j);
            }
        }
    }
}
Explanation: 1) Outer loop i takes values 0, 1, 2. 2) For i = 0, inner j runs 0..5 but skips 3, so prints 0,1,2,4,5. 3) For i = 1, inner j runs 1..5 but skips 3, so prints 1,2,4,5. 4) For i = 2, inner j runs 2..5 but skips 3, so prints 2,4,5. 5) The continue statement jumps to the next iteration whenever j == 3, so 3 is never printed.
Q415.Medium
Write a Java program that demonstrates accessing a class from another package using its fully qualified name without importing it. Create a class named MessagePrinter in package 'mypack' with a method show() that prints 'Hello from mypack'. Then, create a class FullyQualifiedDemo in the default package that creates an object of mypack.MessagePrinter using the fully qualified name and calls its show() method.
Show answer & explanation
Answer:
// File: mypack/MessagePrinter.java
package mypack;

public class MessagePrinter {
    public void show() {
        System.out.println("Hello from mypack");
    }
}

// File: FullyQualifiedDemo.java
public class FullyQualifiedDemo {
    public static void main(String[] args) {
        mypack.MessagePrinter mp = new mypack.MessagePrinter();
        mp.show();
    }
}
Explanation: 1. The class MessagePrinter is defined in package 'mypack' with a show() method that prints the message. 2. The FullyQualifiedDemo class is in the default package and does not import MessagePrinter. 3. Instead, it uses the fully qualified name 'mypack.MessagePrinter' to declare and instantiate the object. 4. The show() method is called on the object, printing the message. 5. Compile both files with proper directory structure and run FullyQualifiedDemo to see the output.
Q416.Medium
Write a Java program that demonstrates the use of a subpackage. Create a class named Greeting inside a subpackage 'in.example.core' (which is a subpackage of 'in.example'). The class should have a main method that prints 'Namaste from subpackage'. Also, create a main class named SubpackageDemo in the default package that creates an object of Greeting and calls a method greet() which prints the same message. Ensure proper package declaration and import.
Show answer & explanation
Answer:
// File: in/example/core/Greeting.java
package in.example.core;

public class Greeting {
    public void greet() {
        System.out.println("Namaste from subpackage");
    }
    public static void main(String[] args) {
        System.out.println("Namaste from subpackage");
    }
}

// File: SubpackageDemo.java
import in.example.core.Greeting;

public class SubpackageDemo {
    public static void main(String[] args) {
        Greeting g = new Greeting();
        g.greet();
    }
}
Explanation: 1. The package 'in.example.core' is a subpackage of 'in.example'. The class Greeting is placed in this subpackage with the package declaration at the top. 2. Greeting has a method greet() that prints the message, and a main method for direct execution. 3. The SubpackageDemo class is in the default package and imports Greeting using its fully qualified name. 4. In SubpackageDemo's main, an object of Greeting is created and greet() is called, which prints the message. 5. Compile both files with appropriate directory structure and run SubpackageDemo to see the output.
Q417.Medium
Write a Java program with a class Calculator that has two static methods both named add(int a, int b) but with different return types: one returns int and the other returns double. In the main method, call Calculator.add(7, 5) and print the result. Explain what happens when you compile this program.
Show answer & explanation
Answer:
class Calculator {
    static int add(int a, int b) { return a + b; }
    static double add(int a, int b) { return a + b; }
}

class TestOverloading {
    public static void main(String[] args) {
        System.out.println(Calculator.add(7, 5));
    }
}
Explanation: 1) Method overloading requires different parameter lists (number, types, or order of parameters). 2) Here both add methods have identical parameters (int, int) and differ only in return type. 3) The compiler cannot decide which method to call when it sees Calculator.add(7, 5), causing ambiguity. 4) Therefore the program produces a compile-time error: 'method add(int,int) is already defined'. 5) Changing only the return type is not valid overloading in Java.
Q418.Medium
Write a Java program that demonstrates method overloading ambiguity due to type promotion. Create a class with two overloaded methods: one named 'calculate' that takes an int and a long, and another named 'calculate' that takes a long and an int. Both methods should print a distinct message. In the main method, call calculate(15, 15) and observe the compilation error. Explain why the ambiguity occurs.
Show answer & explanation
Answer:
class OverloadingAmbiguity {
    void calculate(int a, long b) {
        System.out.println("int-long method invoked");
    }
    void calculate(long a, int b) {
        System.out.println("long-int method invoked");
    }
    public static void main(String[] args) {
        OverloadingAmbiguity obj = new OverloadingAmbiguity();
        obj.calculate(15, 15); // Compilation error: ambiguous method call
    }
}
Explanation: 1. The class OverloadingAmbiguity has two overloaded methods: calculate(int, long) and calculate(long, int). 2. In main, we call calculate(15, 15) with two int arguments. 3. The compiler tries to find the most specific method. For the first argument (int), the first method matches exactly, but the second requires widening to long. For the second argument (int), the second method matches exactly, but the first requires widening to long. 4. Neither method is more specific than the other because each is better for one argument but worse for the other. 5. Therefore, the call is ambiguous, and the compiler reports an error: reference to calculate is ambiguous. 6. To fix, you can cast one argument to long, e.g., calculate(15L, 15) or calculate(15, 15L).
Q419.Medium
Write a Java program that counts the number of vowels in a string using the charAt() method. The program should store the vowels in an ArrayList<Character>, use a helper method isVowel(char c) that checks membership in that list, and a method countVowels(String s) that loops with charAt(). In main, test it on two strings: "Rahul is learning Java at Pune." and "An apple a day keeps the doctor away." and print each string followed by its vowel count. Name the class VowelCounter.
Show answer & explanation
Answer:
import java.util.*;

public class VowelCounter {
    ArrayList<Character> al;

    VowelCounter() {
        al = new ArrayList<Character>();
        al.add('A'); al.add('E');
        al.add('a'); al.add('e');
        al.add('I'); al.add('O');
        al.add('i'); al.add('o');
        al.add('U'); al.add('u');
    }

    private boolean isVowel(char c) {
        for (int i = 0; i < al.size(); i++) {
            if (c == al.get(i)) {
                return true;
            }
        }
        return false;
    }

    public int countVowels(String s) {
        int countVowel = 0;
        int size = s.length();
        for (int j = 0; j < size; j++) {
            char c = s.charAt(j);
            if (isVowel(c)) {
                countVowel = countVowel + 1;
            }
        }
        return countVowel;
    }

    public static void main(String[] args) {
        VowelCounter obj = new VowelCounter();

        String str = "Rahul is learning Java at Pune.";
        int noOfVowel = obj.countVowels(str);
        System.out.println("String: " + str);
        System.out.println("Total number of vowels in the string are: " + noOfVowel + "\n");

        str = "An apple a day keeps the doctor away.";
        System.out.println("String: " + str);
        noOfVowel = obj.countVowels(str);
        System.out.println("Total number of vowels in the string are: " + noOfVowel);
    }
}
Explanation: 1) The constructor fills an ArrayList with the ten vowel characters (both cases). 2) isVowel(c) loops over the list and returns true if c matches any stored vowel. 3) countVowels(s) walks the string index by index using s.charAt(j) and increments a counter whenever isVowel returns true. 4) main creates one object and calls countVowels on each test string, printing the string and the returned count. 5) For "Rahul is learning Java at Pune." the vowels are a,u,i,e,a,i,a,a,a,u,e = 10. 6) For "An apple a day keeps the doctor away." the vowels are A,a,e,a,a,e,e,e,o,o,a,a = 12.
Q420.Medium
Write a Java program that demonstrates converting a string to lowercase using different locales. The program should define a string with mixed case, convert it to lowercase using the English locale and the Turkish locale, and print both results. Use the string "HELLO WORLD from JAVA".
Show answer & explanation
Answer:
import java.util.Locale;

public class LocaleLowerExample {
    public static void main(String[] args) {
        String s = "HELLO WORLD from JAVA";
        String englishLower = s.toLowerCase(Locale.ENGLISH);
        System.out.println(englishLower);
        String turkishLower = s.toLowerCase(Locale.forLanguageTag("tr"));
        System.out.println(turkishLower);
    }
}
Explanation: 1. Import java.util.Locale for locale support. 2. Create a string with mixed case: "HELLO WORLD from JAVA". 3. Convert to lowercase using Locale.ENGLISH: toLowerCase(Locale.ENGLISH) gives "hello world from java". 4. Print the English lowercase result. 5. Convert to lowercase using Turkish locale: Locale.forLanguageTag("tr") creates a Turkish locale. 6. In Turkish, uppercase 'I' converts to 'ı' (dotless i), so "HELLO WORLD from JAVA" becomes "hello world from java" but note: the 'I' in "JAVA"? Actually 'JAVA' has no 'I', but 'from' has no uppercase I. However, the string has no uppercase 'I', so the Turkish result is the same as English: "hello world from java". But to illustrate the difference, we could include an 'I'. The original example had 'I' in "stRIng"? Actually original had "JAVATPOINT HELLO stRIng" which contains 'I' in "stRIng"? Let's check: "stRIng" has uppercase 'I'? It's 'R' and 'I'? Actually "stRIng": characters: s, t, R, I, n, g. So there is an uppercase 'I'. In Turkish, that 'I' becomes 'ı'. So to show the difference, we should include an uppercase 'I'. Our string "HELLO WORLD from JAVA" does not have an uppercase 'I'. So the output would be identical. To make the example meaningful, we should include a word with uppercase 'I', like "INDIA". Let's modify the string to "HELLO WORLD from INDIA". Then English lowercase: "hello world from india"; Turkish lowercase: "hello world from ındia" (with dotless ı). So we'll use that string. Revised answer: Use string "HELLO WORLD from INDIA". Then English: "hello world from india"; Turkish: "hello world from ındia". But the question says: Use the string "HELLO WORLD from JAVA". That string has no uppercase 'I', so the outputs are the same. That's fine; it still demonstrates the method. However, to show the locale effect, we could note that if there were an 'I', it would differ. But the program is correct as is. I'll keep the answer as above but with the given string. The explanation will mention that since there is no uppercase 'I', both outputs are the same, but the method is correctly used.
Q421.Medium
Write a Java program that uses CharArrayWriter to hold the text "Bharat is great" in memory, then writes that same text into four files named p.txt, q.txt, r.txt and s.txt in the current directory, closes all file writers, and finally prints "Done".
Show answer & explanation
Answer:
import java.io.CharArrayWriter;
import java.io.FileWriter;

public class CharArrayDemo {
    public static void main(String[] args) throws Exception {
        CharArrayWriter out = new CharArrayWriter();
        out.write("Bharat is great");
        FileWriter f1 = new FileWriter("p.txt");
        FileWriter f2 = new FileWriter("q.txt");
        FileWriter f3 = new FileWriter("r.txt");
        FileWriter f4 = new FileWriter("s.txt");
        out.writeTo(f1);
        out.writeTo(f2);
        out.writeTo(f3);
        out.writeTo(f4);
        f1.close();
        f2.close();
        f3.close();
        f4.close();
        System.out.println("Done");
    }
}
Explanation: 1) Import CharArrayWriter and FileWriter from java.io. 2) Create a CharArrayWriter object out; it keeps written characters in an internal buffer. 3) out.write("Bharat is great") stores the text in that buffer. 4) Create four FileWriter objects for p.txt, q.txt, r.txt and s.txt. 5) out.writeTo(f) copies the entire buffer contents to each file writer, so all four files get the same text. 6) Close each FileWriter to flush and release resources. 7) Print "Done" to confirm completion.
Q422.Medium
Write a Java program that takes the string "good morning" and converts it to upper case using two locales: Turkish (language tag "tr") and English (language tag "en"). Print the Turkish result first and then the English result, each on its own line.
Show answer & explanation
Answer:
import java.util.Locale;

public class UpperLocaleDemo {
    public static void main(String[] args) {
        String s = "good morning";
        String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
        String english = s.toUpperCase(Locale.forLanguageTag("en"));
        System.out.println(turkish);
        System.out.println(english);
    }
}
Explanation: 1. Import java.util.Locale. 2. Store the text "good morning" in a String variable. 3. Call toUpperCase with Locale.forLanguageTag("tr") to get the Turkish upper-case form (the letter i becomes a dotted capital İ in Turkish). 4. Call toUpperCase with Locale.forLanguageTag("en") to get the English upper-case form. 5. Print the Turkish result first, then the English result, each with System.out.println.
Q423.Medium
Write a Java program that demonstrates the PushbackInputStream class. The program should take the string "3@@4@56@@@78", read it byte by byte, and whenever two consecutive '@' characters are found, print "--" instead of them; otherwise print the character as it is. Use PushbackInputStream to push back a character when needed.
Show answer & explanation
Answer:
import java.io.*;

public class PushbackDemo {
    public static void main(String[] args) throws Exception {
        String text = "3@@4@56@@@78";
        byte[] data = text.getBytes();
        ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
        PushbackInputStream push = new PushbackInputStream(byteStream);
        int ch;
        while ((ch = push.read()) != -1) {
            if (ch == '@') {
                int next = push.read();
                if (next == '@') {
                    System.out.print("--");
                } else {
                    push.unread(next);
                    System.out.print((char) ch);
                }
            } else {
                System.out.print((char) ch);
            }
        }
    }
}
Explanation: 1. Convert the string "3@@4@56@@@78" into a byte array and wrap it in a ByteArrayInputStream. 2. Wrap that stream in a PushbackInputStream so we can push back one byte. 3. Read one byte at a time in a while loop until -1 (end of stream). 4. If the byte is '@', read the next byte. If that next byte is also '@', print "--" (the pair is consumed). 5. If the next byte is not '@', push it back with unread() and print the single '@'. 6. For any other byte, just print it as a character. 7. Output: 3--4@56---78.
Q424.Medium
Write a Java program that demonstrates the PushbackReader class. The program should read characters from a char array containing the sequence: '7', '-', '-', '8', '-', '9', '1', '-', '-', '-', '2', '3'. For each character read, if it is a hyphen ('-'), read the next character. If the next character is also a hyphen, print "#*" (without a newline). Otherwise, push back the next character and print the hyphen. For all other characters, print them as they are. Use a CharArrayReader and a PushbackReader.
Show answer & explanation
Answer:
import java.io.*;

public class PushbackReaderDemo {
    public static void main(String[] args) throws Exception {
        char[] data = {'7', '-', '-', '8', '-', '9', '1', '-', '-', '-', '2', '3'};
        CharArrayReader charArrayReader = new CharArrayReader(data);
        PushbackReader pushbackReader = new PushbackReader(charArrayReader);
        int ch;
        while ((ch = pushbackReader.read()) != -1) {
            if (ch == '-') {
                int next = pushbackReader.read();
                if (next == '-') {
                    System.out.print("#*");
                } else {
                    if (next != -1) {
                        pushbackReader.unread(next);
                    }
                    System.out.print((char) ch);
                }
            } else {
                System.out.print((char) ch);
            }
        }
    }
}
Explanation: 1. Import java.io.* for reader classes. 2. Define a char array with the given sequence. 3. Create a CharArrayReader on the array and wrap it with a PushbackReader. 4. Read characters one by one using pushbackReader.read(). 5. If the character is '-', read the next character. If that next character is also '-', print "#*" (and do not push back). Otherwise, push back the next character (if not end of stream) and print the hyphen. 6. For any other character, print it directly. 7. The loop continues until end of stream (-1).
Q425.Medium
Write a Java program that demonstrates the use of StringWriter. The program should read the contents of a file named "C://data//input.txt" using a BufferedReader (with UTF-8 encoding) and write the data to a StringWriter. Finally, print the contents of the StringWriter to the console. Handle any IOExceptions by declaring them in the main method.
Show answer & explanation
Answer:
import java.io.*;

public class StringWriterDemo {
    public static void main(String[] args) throws IOException {
        char[] buffer = new char[1024];
        StringWriter writer = new StringWriter();
        FileInputStream input = null;
        BufferedReader reader = null;
        try {
            input = new FileInputStream("C://data//input.txt");
            reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            int charsRead;
            while ((charsRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, charsRead);
            }
            System.out.println(writer.toString());
        } finally {
            if (writer != null) writer.close();
            if (reader != null) reader.close();
        }
    }
}
Explanation: 1. Import java.io.* for file and writer classes. 2. Create a char array buffer of size 1024 to read chunks. 3. Create a StringWriter to accumulate the file content. 4. Open a FileInputStream on "C://data//input.txt" and wrap it with a BufferedReader using UTF-8 encoding. 5. Read from the BufferedReader into the buffer until end of file (-1). For each read, write the characters to the StringWriter. 6. After reading, print the StringWriter's content using toString(). 7. Close both the StringWriter and BufferedReader in a finally block to release resources.
Q426.Medium
Write a Java program to demonstrate that a private constructor prevents instantiation from outside the class. Create a class named 'Demo' with a private constructor and a method 'show' that prints "Private Constructor Demo". Then, in a main method, try to create an object of 'Demo' and observe the compile-time error. Your program should include the necessary classes and comments explaining the error.
Show answer & explanation
Answer:
class Demo {
    private Demo() {
        // private constructor
    }
    void show() {
        System.out.println("Private Constructor Demo");
    }
}

public class PrivateConstructorExample {
    public static void main(String[] args) {
        // Demo obj = new Demo(); // Compile-time error: Demo() has private access in Demo
        System.out.println("Cannot create instance of Demo from outside the class due to private constructor.");
    }
}
Explanation: 1. Class Demo has a private constructor, so it cannot be called from outside the class. 2. In main, attempting `new Demo()` causes a compile-time error because the constructor is private. 3. The program comments out the erroneous line and prints a message instead. 4. This demonstrates that a private constructor restricts instantiation to within the class itself.
Q427.Medium
Write a Java program that demonstrates the protected access modifier across packages. Create a public class Vehicle in package garage with a protected method showInfo() that prints "Vehicle info". Then create a class Car in package showroom that extends Vehicle and calls showInfo() from its own method display(). Finally, create a public class Main in package showroom whose main method creates a Car object and calls display().
Show answer & explanation
Answer:
// File: garage/Vehicle.java
package garage;

public class Vehicle {
    protected void showInfo() {
        System.out.println("Vehicle info");
    }
}

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

import garage.Vehicle;

public class Car extends Vehicle {
    public void display() {
        showInfo();
    }
}

// File: showroom/Main.java
package showroom;

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.display();
    }
}
Explanation: 1) Vehicle is public so it can be imported from another package. 2) showInfo() is protected, so it is visible in subclasses even outside its package. 3) Car extends Vehicle, so inside Car we can call showInfo() directly. 4) Main creates a Car and calls display(), which calls the inherited protected method. 5) Output: Vehicle info.
Q428.Medium
Write a Java program to demonstrate that when overriding a method, the overriding method in the subclass cannot have a more restrictive access modifier than the overridden method. Create a superclass `Vehicle` with a protected method `display()` that prints "Vehicle display", and a subclass `Car` that overrides `display()` with the same protected access. Then, in a main method, create a `Car` object and call `display()`.
Show answer & explanation
Answer:
class Vehicle {
    protected void display() {
        System.out.println("Vehicle display");
    }
}

class Car extends Vehicle {
    @Override
    protected void display() {
        System.out.println("Car display");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.display();
    }
}
Explanation: 1. The superclass `Vehicle` declares a protected method `display()`. 2. The subclass `Car` overrides `display()` with the same protected access, which is allowed because it is not more restrictive. 3. In `main`, a `Car` object is created and `display()` is called, which invokes the overridden method in `Car` and prints "Car display".
Q429.Medium
Write a Java program that demonstrates why multiple inheritance of classes causes ambiguity but can be achieved cleanly using interfaces. Create two interfaces, Greetable (with method greet()) and Wishing (with method wish()), both declaring a method with the same name greet(). Then create a class FestivalGreeter that implements both interfaces and provides a single implementation of greet() that prints "Namaste" and a wish() method that prints "Happy Diwali". In main, create a FestivalGreeter object and call both methods.
Show answer & explanation
Answer:
interface Greetable {
    void greet();
}

interface Wishing {
    void greet();
    void wish();
}

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

    public void wish() {
        System.out.println("Happy Diwali");
    }

    public static void main(String[] args) {
        FestivalGreeter obj = new FestivalGreeter();
        obj.greet();
        obj.wish();
    }
}
Explanation: 1) Two interfaces Greetable and Wishing both declare greet(); since interfaces only declare methods, there is no conflicting implementation, so no ambiguity. 2) FestivalGreeter implements both interfaces and supplies one greet() method, which satisfies both declarations. 3) It also implements wish() required by Wishing. 4) main creates an object and calls greet() (prints Namaste) then wish() (prints Happy Diwali). 5) This shows multiple inheritance of type via interfaces works without the diamond ambiguity that classes would cause.
Q430.Medium
Write a Java program to demonstrate a default method in an interface. Create an interface 'Vehicle' with an abstract method 'start()' and a default method 'honk()' that prints "Beep beep!". Then create a class 'Car' that implements 'Vehicle' and provides an implementation of 'start()' that prints "Car starting...". In the main method, create a 'Car' object, call 'start()' and 'honk()'.
Show answer & explanation
Answer:
interface Vehicle {
    void start();
    default void honk() {
        System.out.println("Beep beep!");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.start();
        v.honk();
    }
}
Explanation: 1. Define interface 'Vehicle' with abstract method 'start()' and default method 'honk()' that prints "Beep beep!". 2. Class 'Car' implements 'Vehicle' and overrides 'start()' to print "Car starting...". It inherits the default 'honk()'. 3. In main, create a 'Car' object referenced by 'Vehicle' type. 4. Call 'start()' which invokes Car's implementation, printing "Car starting...". 5. Call 'honk()' which uses the default method, printing "Beep beep!".
Q431.Medium
Write a Java program using nested if statements. Declare a String variable address with the value "Pune, India". First check whether the address ends with "India". If it does, then check inside: if the address contains "Mumbai" print "Your city is Mumbai"; else if it contains "Nagpur" print "Your city is Nagpur"; otherwise print the part of the address before the comma (the city name). If the address does not end with "India", print "You are not living in India".
Show answer & explanation
Answer:
public class Resident {
    public static void main(String[] args) {
        String address = "Pune, India";

        if (address.endsWith("India")) {
            if (address.contains("Mumbai")) {
                System.out.println("Your city is Mumbai");
            } else if (address.contains("Nagpur")) {
                System.out.println("Your city is Nagpur");
            } else {
                System.out.println(address.split(",")[0]);
            }
        } else {
            System.out.println("You are not living in India");
        }
    }
}
Explanation: 1. Declare address = "Pune, India". 2. Outer if: address.endsWith("India") is true, so enter the block. 3. Inner if: address.contains("Mumbai") is false. 4. Inner else-if: address.contains("Nagpur") is false. 5. Inner else runs: address.split(",")[0] gives "Pune", so it prints Pune. 6. If the outer condition were false, it would print "You are not living in India".
Q432.Medium
Write a Java program that demonstrates a member inner class accessing a private field of the outer class. Create an outer class named 'BankAccount' with a private integer field 'balance' initialized to 5000. Inside it, define a non-static inner class 'Transaction' with a method 'showBalance()' that prints the balance. In the main method, create an instance of BankAccount, then create an instance of the inner class using the outer instance, and call showBalance().
Show answer & explanation
Answer:
class BankAccount {
    private int balance = 5000;

    class Transaction {
        void showBalance() {
            System.out.println("Balance is " + balance);
        }
    }

    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        BankAccount.Transaction txn = account.new Transaction();
        txn.showBalance();
    }
}
Explanation: 1. Define outer class BankAccount with private int balance = 5000. 2. Inside BankAccount, define non-static inner class Transaction with method showBalance() that prints balance. 3. In main, create BankAccount object account. 4. Create inner class object using account.new Transaction(). 5. Call txn.showBalance(), which prints 'Balance is 5000'.
Q433.Medium
Write a Java program that demonstrates a member inner class. Create an outer class Bank with a private integer field balance = 5000 and a member inner class Auditor that has a method showBalance() printing "Balance is " followed by the outer class's private balance. In main, create a Bank object, then create an Auditor object using it, and call showBalance().
Show answer & explanation
Answer:
class Bank {
    private int balance = 5000;

    class Auditor {
        void showBalance() {
            System.out.println("Balance is " + balance);
        }
    }
}

public class InnerClassDemo {
    public static void main(String args[]) {
        Bank bank = new Bank();
        Bank.Auditor auditor = bank.new Auditor();
        auditor.showBalance();
    }
}
Explanation: 1) Bank is the outer class with a private field balance = 5000. 2) Auditor is a non-static member inner class; it holds an implicit reference to its enclosing Bank object, so it can read the private balance directly. 3) In main, an outer object bank is created first. 4) The inner object is created with the syntax bank.new Auditor(), which links it to that specific Bank instance. 5) Calling showBalance() prints "Balance is 5000". 6) The compiler generates Bank.class and Bank$Auditor.class, and the inner class accesses the private field through a synthetic accessor.
Q434.Medium
Write a Java program that demonstrates handling a checked exception. The program should try to create a PrintWriter for a file named "notes.txt", write the line "stored" into it, and catch the FileNotFoundException using a try-catch block. After the try-catch, print "File stored successfully". Name the class CheckedDemo.
Show answer & explanation
Answer:
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CheckedDemo {

    public static void main(String[] args) {

        PrintWriter pw;
        try {
            pw = new PrintWriter("notes.txt"); // may throw checked exception
            pw.println("stored");
            pw.close(); // flush so the line is actually written
        }
        // handler for the checked exception
        catch (FileNotFoundException e) {
            System.out.println(e);
        }
        System.out.println("File stored successfully");
    }
}
Explanation: 1. Import java.io.FileNotFoundException and java.io.PrintWriter. 2. Declare a PrintWriter variable pw outside the try block. 3. Inside try, create new PrintWriter("notes.txt") which may throw FileNotFoundException (a checked exception). 4. Write "stored" using pw.println and then close/flush is optional here. 5. The catch block catches FileNotFoundException and prints the exception object. 6. After the try-catch, print "File stored successfully" so the program continues normally.
Q435.Medium
Write a Java program where a try block performs a division that throws an ArithmeticException, and the catch block itself also performs a division by zero (which throws an exception inside the catch block). Use the values 60 and 0 for the division in the try block, and 60 and 0 again in the catch block. After the try-catch, print "remaining code". Name the class CatchInsideCatch.
Show answer & explanation
Answer:
public class CatchInsideCatch {
    public static void main(String[] args) {
        try {
            int result1 = 60 / 0; // may throw ArithmeticException
        } catch (Exception e) {
            // generating an exception inside the catch block
            int result2 = 60 / 0; // may throw ArithmeticException
        }
        System.out.println("remaining code");
    }
}
Explanation: 1) The try block computes 60/0, which throws an ArithmeticException. 2) Control jumps to the catch block, which catches the exception. 3) Inside the catch block, 60/0 is computed again, throwing a new ArithmeticException. 4) This new exception is not handled anywhere, so it propagates and the program terminates abnormally. 5) Therefore the line System.out.println("remaining code") is never executed.
Q436.Medium
Write a Java program that, inside a try block, computes int result = 40 / 0 (which throws an ArithmeticException), but the catch block is written for ArrayIndexOutOfBoundsException. Show what happens when the program runs.
Show answer & explanation
Answer:
public class MismatchCatchDemo {
    public static void main(String[] args) {
        try {
            int result = 40 / 0; // throws ArithmeticException
        }
        // trying to handle ArithmeticException using ArrayIndexOutOfBoundsException
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
        }
        System.out.println("rest of the code");
    }
}
Explanation: 1) 40 / 0 causes an ArithmeticException (divide by zero) inside the try block. 2) The catch block only handles ArrayIndexOutOfBoundsException, which does not match the thrown ArithmeticException. 3) Since no matching catch is found, the exception is not handled here and propagates out of main. 4) The JVM prints the ArithmeticException stack trace (java.lang.ArithmeticException: / by zero) and terminates the program. 5) Therefore "rest of the code" is never printed.
Q437.MediumAnswer under review
Write a Java program that demonstrates thread states. Create a class named Task that implements Runnable. In its run() method, first call Thread.sleep(100) inside a try-catch block (this moves the thread into the TIMED_WAITING state). Then print the state of a thread reference t1 using Thread.currentThread() context, i.e. print the state of the main thread while the sleeping thread is in timed waiting. After that, call Thread.sleep(200) inside another try-catch block. The main method should create a Thread t1 from a Task object, start it, and then print the state of t1.
Show answer & explanation
Answer:
class Task implements Runnable {
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        System.out.println("State of the main thread while the task thread is in timed waiting: " + Thread.currentThread().getState());
        try {
            Thread.sleep(200);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

public class ThreadStateDemo {
    public static void main(String[] args) {
        Task task = new Task();
        Thread t1 = new Thread(task);
        t1.start();
        System.out.println("State of t1 after start(): " + t1.getState());
    }
}
Explanation: 1. Task implements Runnable and defines run(). 2. Inside run(), Thread.sleep(100) puts the task thread into TIMED_WAITING. 3. While it sleeps, the main thread prints the state of the current (main) thread. 4. A second Thread.sleep(200) keeps the task thread in timed waiting a bit longer. 5. In main, a Thread t1 is created from Task and started; t1.getState() shows its state (RUNNABLE or TIMED_WAITING). 6. This demonstrates thread states such as NEW, RUNNABLE and TIMED_WAITING.
Q438.Medium
Write a Java program that demonstrates a synchronized block. Create a class Table with a method printTable(int n) that prints the multiplication table of n from 1 to 5, with a 300 ms pause between each line. The method should use a synchronized block on 'this' to ensure that only one thread prints the table at a time. In the main method, create two threads that share the same Table object and call printTable with different numbers. Start both threads and wait for them to finish.
Show answer & explanation
Answer:
class Table {
    void printTable(int n) {
        synchronized (this) {
            for (int i = 1; i <= 5; i++) {
                System.out.println(n * i);
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    System.out.println(e);
                }
            }
        }
    }
}

public class SyncBlockDemo {
    public static void main(String[] args) {
        Table table = new Table();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                table.printTable(5);
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                table.printTable(100);
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }
}
Explanation: 1. The Table class has a printTable method that prints the multiplication table of n from 1 to 5, pausing 300 ms after each line. 2. The entire loop is inside a synchronized block on 'this', so only one thread can execute the loop at a time for a given Table instance. 3. In main, we create one Table object and two threads that call printTable with 5 and 100 respectively. 4. Both threads are started and then joined to wait for completion.
Q439.Medium
Write a Java program that demonstrates a synchronized block using an anonymous class. Create a class Messenger with a method sendMessage(String msg) that prints the message, sleeps for 500 milliseconds, and then prints that the message was sent. In the main method, create a Messenger object, then create two threads using anonymous inner classes that each call sendMessage with different messages, synchronizing on the Messenger object. Start both threads and wait for them to finish.
Show answer & explanation
Answer:
class Messenger {
    public void sendMessage(String msg) {
        System.out.println("\nSending: " + msg);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            System.out.println("Thread interrupted.");
        }
        System.out.println(msg + " sent");
    }
}

public class SyncAnonymousDemo {
    public static void main(String[] args) {
        Messenger messenger = new Messenger();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                synchronized (messenger) {
                    messenger.sendMessage("Hello");
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                synchronized (messenger) {
                    messenger.sendMessage("Welcome to the Java tutorial");
                }
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted");
        }
    }
}
Explanation: 1. The Messenger class has a sendMessage method that prints the message, sleeps for 500 ms, then prints that it was sent. 2. In main, we create one Messenger object shared by both threads. 3. Two threads are created using anonymous inner classes implementing Runnable. 4. Each thread's run method contains a synchronized block on the shared Messenger object, ensuring only one thread executes sendMessage at a time. 5. Both threads are started and then joined to wait for completion.
Q440.Medium
Write a Java program that demonstrates inter-thread communication using PipedReader and PipedWriter. One thread should write the text "Jai Hind from Bharat\n" into a PipedWriter, and another thread should read it character by character from a connected PipedReader and print each character to the console.
Show answer & explanation
Answer:
import java.io.PipedReader;
import java.io.PipedWriter;

public class PipeDemo {
    public static void main(String[] args) {
        try {
            final PipedReader reader = new PipedReader();
            final PipedWriter writer = new PipedWriter(reader);

            Thread readerThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        int data = reader.read();
                        while (data != -1) {
                            System.out.print((char) data);
                            data = reader.read();
                        }
                    } catch (Exception ex) {
                    }
                }
            });

            Thread writerThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        writer.write("Jai Hind from Bharat\n".toCharArray());
                    } catch (Exception ex) {
                    }
                }
            });

            readerThread.start();
            writerThread.start();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
Explanation: 1. Create a PipedReader and a PipedWriter connected to it via the constructor PipedWriter(reader). 2. The reader thread loops calling reader.read(); each int returned is cast to char and printed until -1 (end of stream). 3. The writer thread writes the character array of "Jai Hind from Bharat\n" into the pipe. 4. Both threads are started; the pipe passes data from writer to reader, so the text is printed to the console.
Q441.Medium
Write a Java program that reads a text file named "input.txt" containing the line "I love my India". The program should replace every space character with an underscore '_' and print the modified content to the console. Use a custom FilterReader to perform the replacement.
Show answer & explanation
Answer:
import java.io.*;

class SpaceToUnderscoreFilter extends FilterReader {
    SpaceToUnderscoreFilter(Reader in) {
        super(in);
    }

    public int read() throws IOException {
        int c = super.read();
        if ((char) c == ' ') {
            return '_';
        } else {
            return c;
        }
    }
}

public class FilterReaderDemo {
    public static void main(String[] args) {
        try {
            Reader reader = new FileReader("input.txt");
            SpaceToUnderscoreFilter filter = new SpaceToUnderscoreFilter(reader);
            int ch;
            while ((ch = filter.read()) != -1) {
                System.out.print((char) ch);
            }
            filter.close();
            reader.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Explanation: 1. Create a custom FilterReader subclass that overrides read(). 2. In read(), call super.read() to get the next character. 3. If the character is a space (' '), return '_' instead; otherwise return the character. 4. In main, open a FileReader for "input.txt" and wrap it with the custom filter. 5. Read characters one by one until end of file (-1), printing each. 6. Close the filter and reader.
Q442.Medium
Write a Java program that demonstrates FileDescriptor operations. The program should: create a file named "Notes.txt", write the byte values {65, 66, 67, 68, 69} to it using a FileOutputStream, flush the stream, obtain the FileDescriptor via getFD(), call sync() on it to force buffers to the underlying device, then read the file back with a FileInputStream and print each byte as a character. Finally print whether the descriptor is valid using valid() and print a success message.
Show answer & explanation
Answer:
import java.io.*;
public class DescriptorDemo {
    public static void main(String[] args) {
        FileDescriptor fd = null;
        byte[] data = {65, 66, 67, 68, 69};
        try {
            FileOutputStream fos = new FileOutputStream("Notes.txt");
            FileInputStream fis = new FileInputStream("Notes.txt");
            fd = fos.getFD();
            fos.write(data);
            fos.flush();
            fd.sync(); // force buffers to synchronize with the device
            int value = 0;
            while ((value = fis.read()) != -1) {
                char c = (char) value;
                System.out.print(c);
            }
            System.out.println("\nDescriptor valid: " + fd.valid());
            System.out.println("sync() executed successfully!!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Explanation: 1. A FileOutputStream opens/creates Notes.txt and a FileInputStream is created to read it back. 2. getFD() returns the FileDescriptor of the output stream. 3. write(data) writes the five bytes; flush() pushes buffered data out. 4. fd.sync() forces all system buffers to synchronize with the underlying device. 5. The input stream reads bytes one by one until -1 and prints them as characters (ABCDE). 6. fd.valid() returns true while the descriptor is open, and a success message is printed.
Q443.Medium
Write a Java program that demonstrates covariant return types. Create a base class Vehicle with a method getVehicle() that returns a Vehicle object (returning this). Create a subclass Car that overrides getVehicle() so it returns a Car object instead of Vehicle. In the main method, create a Car object, call getVehicle() on it, and print a message showing which class the returned object belongs to. FileName: VehicleDemo.java
Show answer & explanation
Answer:
class Vehicle {
    Vehicle getVehicle() {
        return this;
    }
}

class Car extends Vehicle {
    @Override
    Car getVehicle() {
        return this;
    }
}

public class VehicleDemo {
    public static void main(String[] args) {
        Car c = new Car();
        Car returned = c.getVehicle();
        System.out.println("Returned object is of type: " + returned.getClass().getSimpleName());
    }
}
Explanation: 1. Vehicle declares getVehicle() returning Vehicle and returns this. 2. Car extends Vehicle and overrides getVehicle() with a narrower return type Car (covariant return type) — allowed because Car is a subclass of Vehicle. 3. In main, a Car object is created and getVehicle() is called; the compiler knows the return type is Car, so it can be assigned to a Car variable without casting. 4. getClass().getSimpleName() prints 'Car', confirming the returned object's type.
Q444.Medium
Write a Java program that demonstrates the covariant return type. Create a class Vehicle with a method getDetails() that returns a Vehicle object and prints "Vehicle details". Create a subclass Car that overrides getDetails() so that its return type is Car (a subtype of Vehicle) and prints "Car details". In main(), create a Car object, call getDetails() through a Vehicle reference and through a Car reference, and show that no explicit cast is needed.
Show answer & explanation
Answer:
class Vehicle {
    Vehicle getDetails() {
        System.out.println("Vehicle details");
        return this;
    }
}

class Car extends Vehicle {
    @Override
    Car getDetails() {
        System.out.println("Car details");
        return this;
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.getDetails();
        Car c = new Car();
        Car result = c.getDetails();
        System.out.println(result instanceof Car);
    }
}
Explanation: 1) Vehicle declares getDetails() returning Vehicle. 2) Car overrides it with return type Car, which is allowed because Car is a subtype of Vehicle (covariant return type). 3) Calling v.getDetails() through a Vehicle reference runs Car's version (dynamic dispatch) and prints "Car details". 4) Calling c.getDetails() through a Car reference returns a Car directly, so no cast is needed; result instanceof Car prints true.
Q445.Medium
Write a Java program that demonstrates using both an abstract class and an interface together. Create an interface Payment with four methods: pay(), refund(), checkStatus() and cancel(). Create an abstract class OnlinePayment that implements Payment and provides a concrete implementation of checkStatus() that prints "Status checked". Then create a class UpiPayment that extends OnlinePayment and implements the remaining three methods, each printing a short message ("Paid via UPI", "Refunded via UPI", "Cancelled via UPI"). In main(), create a UpiPayment object and call all four methods.
Show answer & explanation
Answer:
interface Payment {
    void pay();
    void refund();
    void checkStatus();
    void cancel();
}

abstract class OnlinePayment implements Payment {
    public void checkStatus() {
        System.out.println("Status checked");
    }
}

class UpiPayment extends OnlinePayment {
    public void pay() {
        System.out.println("Paid via UPI");
    }
    public void refund() {
        System.out.println("Refunded via UPI");
    }
    public void cancel() {
        System.out.println("Cancelled via UPI");
    }
}

public class Main {
    public static void main(String[] args) {
        UpiPayment p = new UpiPayment();
        p.pay();
        p.refund();
        p.checkStatus();
        p.cancel();
    }
}
Explanation: 1) The interface Payment declares four abstract methods, so any implementing class must define them. 2) The abstract class OnlinePayment implements Payment but only provides checkStatus(); the other three remain abstract, which is allowed because the class is abstract. 3) UpiPayment extends OnlinePayment (inheriting checkStatus) and implements pay(), refund() and cancel(). 4) In main(), a UpiPayment object is created and all four methods are called, printing the four messages in order.
Q446.Medium
Write a Java program to multiply two 2×2 matrices and print the resulting matrix. Use matrix A = {{2, 3}, {4, 5}} and matrix B = {{1, 2}, {3, 4}}. The element at row i, column j of the product is the sum over k of A[i][k] * B[k][j].
Show answer & explanation
Answer:
public class MatrixMultiply {
    public static void main(String[] args) {
        int a[][] = {{2, 3}, {4, 5}};
        int b[][] = {{1, 2}, {3, 4}};
        int c[][] = new int[2][2];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                c[i][j] = 0;
                for (int k = 0; k < 2; k++) {
                    c[i][j] += a[i][k] * b[k][j];
                }
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Explanation: 1) Declare two 2×2 matrices a and b and a result matrix c of size 2×2. 2) Loop i over rows of a and j over columns of b. 3) For each (i,j), set c[i][j]=0 and add a[i][k]*b[k][j] for k=0,1. 4) Row 0: c[0][0]=2*1+3*3=11, c[0][1]=2*2+3*4=16. 5) Row 1: c[1][0]=4*1+5*3=19, c[1][1]=4*2+5*4=28. 6) Print each row followed by a newline, giving: 11 16 19 28
Q447.Medium
Write a Java program that demonstrates how the compiler generates an internal class for a local inner class. The program should have an outer class named OuterDemo with a private instance variable, and a method that defines a local inner class named InnerLocal which prints the outer class's private variable. The compiler will generate a class like OuterDemo$1InnerLocal that holds a reference to the outer class instance.
Show answer & explanation
Answer:
public class OuterDemo {
    private int value = 45;

    void show() {
        class InnerLocal {
            void display() {
                System.out.println(value);
            }
        }
        InnerLocal inner = new InnerLocal();
        inner.display();
    }

    public static void main(String[] args) {
        OuterDemo obj = new OuterDemo();
        obj.show();
    }
}
Explanation: 1. OuterDemo has a private instance variable value = 45. 2. The method show() declares a local inner class InnerLocal inside it. 3. InnerLocal's display() accesses the outer class's private field value; the compiler generates OuterDemo$1InnerLocal with a synthetic reference to the outer instance (this$0) and an accessor method. 4. show() creates an InnerLocal object and calls display(), which prints 45. 5. main() creates an OuterDemo and calls show(), so the output is 45.
Q448.Medium
Write a Java program with an outer class named OuterDemo that has a private instance variable data = 30 and a method display(). Inside display(), declare a local variable value = 50 and define a local inner class Inner with a method msg() that prints value. In display(), create an Inner object and call msg(). In main(), create an OuterDemo object and call display().
Show answer & explanation
Answer:
class OuterDemo {
    private int data = 30;
    void display() {
        int value = 50;
        class Inner {
            void msg() {
                System.out.println(value);
            }
        }
        Inner i = new Inner();
        i.msg();
    }
    public static void main(String[] args) {
        OuterDemo obj = new OuterDemo();
        obj.display();
    }
}
Explanation: 1) OuterDemo has an instance variable data = 30 (not used in output but part of the class). 2) display() declares a local variable value = 50. 3) A local inner class Inner is defined inside display(); its msg() method prints value. Since Java 8, a local inner class can access effectively final local variables, so value is accessible. 4) display() creates an Inner object and calls msg(), which prints 50. 5) main() creates an OuterDemo object and calls display(), so the program outputs 50.
Q449.Medium
Write a Java program to demonstrate static synchronization. Create a class 'MathTable' with a static synchronized method 'printTable(int n)' that prints the first 5 multiples of n (n*1 to n*5), sleeping 200 ms after each print. Create two thread classes: one calls MathTable.printTable(2) and the other calls MathTable.printTable(5). In main, start both threads. Explain why static synchronization prevents interference between them.
Show answer & explanation
Answer:
class MathTable {
    synchronized static void printTable(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(200);
            } catch (Exception e) {
            }
        }
    }
}

class ThreadA extends Thread {
    public void run() {
        MathTable.printTable(2);
    }
}

class ThreadB extends Thread {
    public void run() {
        MathTable.printTable(5);
    }
}

public class StaticSyncDemo {
    public static void main(String[] args) {
        ThreadA t1 = new ThreadA();
        ThreadB t2 = new ThreadB();
        t1.start();
        t2.start();
    }
}
Explanation: 1. 'printTable' is 'synchronized static', so the monitor lock is the MathTable class object, not any instance. 2. ThreadA and ThreadB are separate objects, but both call the same static method. 3. Since the class-level lock is common to all instances, only one thread enters printTable at a time. 4. So the multiples of 2 (2,4,6,8,10) print fully, then the multiples of 5 (5,10,15,20,25) print, with no interleaving. 5. Without 'static', each object would have its own lock and the outputs could interleave.
Q450.Medium
Write a Java program that demonstrates static synchronization using anonymous classes to create the threads. Create a class named 'Counter' with a static synchronized method 'showMultiples(int n)' that prints the first 5 multiples of n (n*1 to n*5), pausing 300 ms between prints. In the main method, create two threads using anonymous inner classes: one calls Counter.showMultiples(3) and the other calls Counter.showMultiples(7). Start both threads.
Show answer & explanation
Answer:
class Counter {
    synchronized static void showMultiples(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(300);
            } catch (Exception e) {
            }
        }
    }
}

public class StaticSyncAnonymous {
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                Counter.showMultiples(3);
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                Counter.showMultiples(7);
            }
        };
        t1.start();
        t2.start();
    }
}
Explanation: 1. 'Counter.showMultiples' is declared 'synchronized static', so the lock is on the Counter class object, shared by all threads. 2. Two threads are created using anonymous subclasses of Thread, each overriding run(). 3. t1 calls showMultiples(3) and t2 calls showMultiples(7). 4. Because the method is static synchronized, only one thread can execute it at a time; the second waits until the first finishes all 5 prints. 5. Hence the multiples of 3 (3,6,9,12,15) print completely before the multiples of 7 (7,14,21,28,35), with a 300 ms pause between each print.
Q451.Medium
Write a Java program that demonstrates a deadlock scenario. Create two String objects: resource1 = "resourceA" and resource2 = "resourceB". Create two threads: Thread-1 locks resource1, then sleeps for 100 ms, then tries to lock resource2 and prints "Thread-1: locked both resources". Thread-2 locks resource2, then sleeps for 100 ms, then tries to lock resource1 and prints "Thread-2: locked both resources". Start both threads. The program will likely deadlock because each thread holds one lock and waits for the other.
Show answer & explanation
Answer:
public class DeadlockDemo {
    public static void main(String[] args) {
        final String resource1 = "resourceA";
        final String resource2 = "resourceB";
        Thread t1 = new Thread(() -> {
            synchronized (resource1) {
                System.out.println("Thread-1: locked resource1");
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (resource2) {
                    System.out.println("Thread-1: locked both resources");
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (resource2) {
                System.out.println("Thread-2: locked resource2");
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (resource1) {
                    System.out.println("Thread-2: locked both resources");
                }
            }
        });
        t1.start();
        t2.start();
    }
}
Explanation: 1. Define two String constants resource1 and resource2. 2. Create Thread-1: it synchronizes on resource1, prints a message, sleeps 100 ms, then tries to synchronize on resource2 and prints a success message. 3. Create Thread-2: it synchronizes on resource2, prints a message, sleeps 100 ms, then tries to synchronize on resource1 and prints a success message. 4. Start both threads. 5. Deadlock can occur: Thread-1 holds resource1 and waits for resource2, while Thread-2 holds resource2 and waits for resource1, causing a circular wait.
Q452.Medium
Write a Java program that demonstrates how to avoid deadlock by ensuring a consistent lock ordering. Create two resource classes, ResourceA and ResourceB, each with a private integer field (e.g., valueA=100, valueB=200) and getter/setter methods. In the main method, create one instance of each resource. Create two threads: Thread-1 acquires the lock on ResourceA first, then after a short delay acquires the lock on ResourceB, and prints "Thread-1 acquired both resources". Thread-2 acquires the lock on ResourceA first, then after a short delay acquires the lock on ResourceB, and prints "Thread-2 acquired both resources". Both threads must acquire locks in the same order (ResourceA then ResourceB) to prevent deadlock. Start both threads.
Show answer & explanation
Answer:
public class DeadlockAvoidance {
    static class ResourceA {
        private int value = 100;
        public int getValue() { return value; }
        public void setValue(int value) { this.value = value; }
    }
    static class ResourceB {
        private int value = 200;
        public int getValue() { return value; }
        public void setValue(int value) { this.value = value; }
    }
    public static void main(String[] args) {
        final ResourceA a = new ResourceA();
        final ResourceB b = new ResourceB();
        Thread t1 = new Thread(() -> {
            synchronized (a) {
                System.out.println("Thread-1: locked ResourceA");
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (b) {
                    System.out.println("Thread-1 acquired both resources");
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (a) {
                System.out.println("Thread-2: locked ResourceA");
                try { Thread.sleep(100); } catch (InterruptedException e) {}
                synchronized (b) {
                    System.out.println("Thread-2 acquired both resources");
                }
            }
        });
        t1.start();
        t2.start();
    }
}
Explanation: 1. Define two resource classes ResourceA and ResourceB with private integer fields and getter/setter methods. 2. In main, create one instance of each resource: a and b. 3. Create Thread-1: it synchronizes on a first, prints a message, sleeps briefly, then synchronizes on b and prints that it acquired both resources. 4. Create Thread-2: it also synchronizes on a first, prints a message, sleeps briefly, then synchronizes on b and prints that it acquired both resources. 5. Because both threads acquire locks in the same order (a then b), deadlock cannot occur: if Thread-1 holds a, Thread-2 will wait for a before trying to lock b, so no circular wait. 6. Start both threads.
Q453.Medium
Write a Java program that demonstrates nested try blocks handling two different exceptions. In the outer try block, place two inner try blocks: the first inner try divides 84 by 0 (catching ArithmeticException), and the second inner try stores a value at index 6 of an int array of size 6 (catching ArrayIndexOutOfBoundsException). After both inner try blocks, print "remaining statement". The outer try has a catch for Exception that prints "outer catch handled". Finally, after the outer try-catch, print "program ended".
Show answer & explanation
Answer:
public class NestedTryDemo {
    public static void main(String[] args) {
        try {
            try {
                System.out.println("attempting division by zero");
                int q = 84 / 0;
            } catch (ArithmeticException e) {
                System.out.println(e);
            }

            try {
                int arr[] = new int[6];
                arr[6] = 9;
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println(e);
            }

            System.out.println("remaining statement");
        } catch (Exception e) {
            System.out.println("outer catch handled");
        }

        System.out.println("program ended");
    }
}
Explanation: 1. The outer try block contains two inner try-catch blocks. 2. First inner try: 84/0 throws ArithmeticException, caught by its own catch which prints the exception message. 3. Second inner try: arr[6]=9 on an array of size 6 throws ArrayIndexOutOfBoundsException, caught by its own catch. 4. Since both inner exceptions are handled, control continues and prints "remaining statement". 5. The outer catch is not triggered, so after the outer try-catch "program ended" is printed.
Q454.Medium
Write a Java program that shows that calling the String contains() method with null as the argument throws a NullPointerException. Create a String variable named text with the value "Hello India!". Then, inside a try block, check if(text.contains(null)) and print "Inside the if block" if true, otherwise print "Inside the else block". Add a catch block for NullPointerException that prints "Null is not allowed".
Show answer & explanation
Answer:
public class ContainsNullDemo {
    public static void main(String[] args) {
        String text = "Hello India!";
        try {
            if (text.contains(null)) {
                System.out.println("Inside the if block");
            } else {
                System.out.println("Inside the else block");
            }
        } catch (NullPointerException e) {
            System.out.println("Null is not allowed");
        }
    }
}
Explanation: 1. The String text is initialized to "Hello India!". 2. The contains() method requires a non-null CharSequence argument; passing null causes it to throw a NullPointerException. 3. Because the call is inside a try block, the exception is caught by the catch(NullPointerException e) block instead of crashing the program. 4. The catch block prints "Null is not allowed". 5. So the output is: Null is not allowed.
Q455.Medium
Write a Java program that demonstrates a static nested class containing a static method. The outer class should have a static variable `count = 45`. The static nested class `Helper` should have a static method `show()` that prints "count is " followed by the value of `count`. In `main`, call the static method directly through the nested class name without creating any instance of the nested class.
Show answer & explanation
Answer:
public class OuterDemo {
    static int count = 45;
    static class Helper {
        static void show() {
            System.out.println("count is " + count);
        }
    }
    public static void main(String args[]) {
        OuterDemo.Helper.show(); // no instance of static nested class needed
    }
}
Explanation: 1. The outer class OuterDemo declares a static variable count = 45. 2. The static nested class Helper is declared inside OuterDemo with a static method show(). 3. Because Helper is static, its static method show() can be called using the class name only. 4. In main, OuterDemo.Helper.show() is invoked without creating any object of Helper. 5. show() prints "count is 45", demonstrating that static members of a static nested class need no instance.
Q456.Medium
Write a Java program that shows what the compiler-generated class file for a static nested class looks like. The outer class `TestOuter1` should have a static variable `data = 25` and a static nested class `Inner` with a method `msg()` that prints "data is " followed by `data`. In `main`, create an instance of `Inner` and call `msg()`. Also show, as a comment or a separate demonstration class, the equivalent compiler-generated form of the nested class named `TestOuter1$Inner` that uses a StringBuilder to build the output string.
Show answer & explanation
Answer:
public class TestOuter1 {
    static int data = 25;
    static class Inner {
        void msg() {
            System.out.println("data is " + data);
        }
    }
    public static void main(String args[]) {
        TestOuter1.Inner obj = new TestOuter1.Inner();
        obj.msg();
    }
}

// Compiler-generated equivalent of the nested class:
// static class TestOuter1$Inner {
//     TestOuter1$Inner() {}
//     void msg() {
//         System.out.println((new StringBuilder()).append("data is ")
//             .append(TestOuter1.data).toString());
//     }
// }
Explanation: 1. The outer class TestOuter1 has a static variable data = 25. 2. The static nested class Inner has an instance method msg() that prints "data is " + data. 3. In main, an object of Inner is created with new TestOuter1.Inner() and msg() is called. 4. The compiler converts string concatenation into a StringBuilder chain, producing the class TestOuter1$Inner with a default constructor and a msg() method. 5. Running the program prints "data is 25", matching the compiler-generated form shown in the comment.
Q457.Medium
Write a Java program that uses labeled loops to print pairs of numbers (i, j) for i from 1 to 4 and j from 1 to 4, but stops completely when i equals 3 and j equals 2. Use a label on the outer loop and a break statement to exit both loops when that condition is met.
Show answer & explanation
Answer:
public class LabeledLoopDemo {
    public static void main(String[] args) {
        outer:
        for (int i = 1; i <= 4; i++) {
            inner:
            for (int j = 1; j <= 4; j++) {
                if (i == 3 && j == 2) {
                    break outer;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}
Explanation: 1. The outer loop runs i from 1 to 4, and the inner loop runs j from 1 to 4. 2. The label 'outer' is placed before the outer for loop. 3. Inside the inner loop, we check if i==3 and j==2. If true, 'break outer;' exits both loops immediately. 4. Otherwise, we print the pair (i, j). 5. The program prints all pairs except those that would come after (3,2) in the iteration order, because the break stops everything.
Q458.Medium
Write a Java program that reads a text file named "notes.txt" (located in the current working directory) byte by byte using a BufferedInputStream wrapped around a FileInputStream, and prints each character to the console. Close both streams at the end and handle any exceptions by printing the exception.
Show answer & explanation
Answer:
import java.io.*;
public class BufferedReadDemo{
 public static void main(String args[]){
  try{
   FileInputStream fin=new FileInputStream("notes.txt");
   BufferedInputStream bin=new BufferedInputStream(fin);
   int c;
   while((c=bin.read())!=-1){
    System.out.print((char)c);
   }
   bin.close();
   fin.close();
  }catch(Exception e){System.out.println(e);}
 }
}
Explanation: 1) Import java.io.* for stream classes. 2) Create a FileInputStream on "notes.txt" to open the file. 3) Wrap it in a BufferedInputStream so reads are buffered for efficiency. 4) Loop calling bin.read(); it returns the next byte (0-255) or -1 at end of file. 5) Cast each byte to char and print it. 6) When read() returns -1 the loop stops; close the BufferedInputStream and FileInputStream. 7) Any IOException is caught and printed.
Q459.Medium
Write a Java program with a thread class whose run() method loops twice; in each iteration it checks Thread.interrupted() and prints "interrupted thread code" if true, otherwise prints "normal thread code". In main, create two such threads t1 and t2, start t1 and immediately interrupt it, then start t2 without interrupting it.
Show answer & explanation
Answer:
public class InterruptDemo extends Thread {
    public void run() {
        for (int i = 1; i <= 2; i++) {
            if (Thread.interrupted()) {
                System.out.println("interrupted thread code");
            } else {
                System.out.println("normal thread code");
            }
        }
    }

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

        t1.start();
        t1.interrupt();

        t2.start();
    }
}
Explanation: 1) run() loops i = 1 to 2 and calls the static Thread.interrupted(), which returns the interrupt flag and then clears it. 2) t1 is started and then interrupted, so its first check likely sees the flag true and prints "interrupted thread code"; the flag is cleared, so the second iteration prints "normal thread code". 3) t2 is never interrupted, so both of its iterations print "normal thread code". 4) Because threads run concurrently, the exact interleaving of t1 and t2 output lines may vary, but t1 prints one interrupted line (if the interrupt lands before its first check) and t2 prints two normal lines.
Q460.Medium
Write a Java program that uses a labeled break statement to exit an outer loop from within 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 outer loop using a label. Otherwise, print the values of the outer and inner loop variables separated by a space. Use the label 'outer:' for the outer loop.
Show answer & explanation
Answer:
public class LabeledBreakDemo {
    public static void main(String[] args) {
        outer:
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 4; j++) {
                if (i == 3 && j == 2) {
                    break outer;
                }
                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 outer;' exits both loops immediately. 4. Otherwise, we print i and j separated by a space. 5. The label 'outer:' is placed before the outer for loop, allowing the break to target it. 6. The program prints all pairs (i,j) except those that would come after (3,2) in the iteration order, because the break terminates both loops.
Q461.Medium
Write a Java program that uses SequenceInputStream to read and print the contents of two files, first.txt and second.txt, one after the other. Use FileInputStream objects for both files and close all streams at the end.
Show answer & explanation
Answer:
import java.io.*;

public class SequenceDemo {
    public static void main(String[] args) throws Exception {
        FileInputStream f1 = new FileInputStream("first.txt");
        FileInputStream f2 = new FileInputStream("second.txt");
        SequenceInputStream seq = new SequenceInputStream(f1, f2);
        int ch;
        while ((ch = seq.read()) != -1) {
            System.out.print((char) ch);
        }
        seq.close();
        f1.close();
        f2.close();
    }
}
Explanation: 1. Create a FileInputStream for first.txt and another for second.txt. 2. Wrap both in a SequenceInputStream, which reads f1 fully and then continues with f2. 3. Loop calling seq.read(); it returns -1 at end of both files. 4. Cast each byte to char and print it, so the two files' contents appear concatenated. 5. Close the SequenceInputStream and both FileInputStreams to release resources.
Q462.Medium
Write a Java program that uses SequenceInputStream with an Enumeration to read the contents of four files — part1.txt, part2.txt, part3.txt and part4.txt — one after another and print the combined data to the console. Create a Vector, add the four FileInputStream objects to it, obtain an Enumeration by calling elements(), pass that Enumeration to the SequenceInputStream constructor, and then read and print every byte until end of stream. Close the streams at the end.
Show answer & explanation
Answer:
import java.io.*;
import java.util.*;

public class MultiFileReader {
    public static void main(String[] args) throws IOException {
        FileInputStream f1 = new FileInputStream("part1.txt");
        FileInputStream f2 = new FileInputStream("part2.txt");
        FileInputStream f3 = new FileInputStream("part3.txt");
        FileInputStream f4 = new FileInputStream("part4.txt");

        Vector<FileInputStream> v = new Vector<>();
        v.add(f1);
        v.add(f2);
        v.add(f3);
        v.add(f4);

        Enumeration<FileInputStream> e = v.elements();
        SequenceInputStream bin = new SequenceInputStream(e);

        int i;
        while ((i = bin.read()) != -1) {
            System.out.print((char) i);
        }

        bin.close();
        f1.close();
        f2.close();
        f3.close();
        f4.close();
    }
}
Explanation: 1. Create one FileInputStream for each of the four files part1.txt to part4.txt. 2. Add all four streams to a Vector so they can be enumerated. 3. Call v.elements() to get an Enumeration over the streams. 4. Pass this Enumeration to the SequenceInputStream constructor, which reads the streams one after another in enumeration order. 5. Loop with bin.read() until it returns -1, printing each byte cast to char, so the file contents appear concatenated. 6. Close the SequenceInputStream and the individual file streams.
Q463.Medium
Write a Java program that demonstrates throwing a checked exception. Create a class named FileCheckDemo with a static method readConfig() that declares throws FileNotFoundException. Inside readConfig(), create a FileReader for the path "D:\\Office\\Ramesh\\config.txt" wrapped in a BufferedReader, then explicitly throw a new FileNotFoundException(). In main(), call readConfig() inside a try block, catch FileNotFoundException and print its stack trace, then print "remaining code...".
Show answer & explanation
Answer:
import java.io.*;

public class FileCheckDemo {

    // method that declares a checked exception
    public static void readConfig() throws FileNotFoundException {

        FileReader file = new FileReader("D:\\Office\\Ramesh\\config.txt");
        BufferedReader fileInput = new BufferedReader(file);

        throw new FileNotFoundException();
    }

    // main method
    public static void main(String args[]) {
        try {
            readConfig();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("remaining code...");
    }
}
Explanation: 1. FileNotFoundException is a checked exception, so any method that throws it must declare it with 'throws' in its signature. 2. readConfig() declares 'throws FileNotFoundException' and opens a FileReader/BufferedReader for the given path. 3. It then explicitly throws a new FileNotFoundException using the throw keyword. 4. main() calls readConfig() inside a try block, so the checked exception must be handled or declared. 5. The catch block catches FileNotFoundException and prints the stack trace with e.printStackTrace(). 6. Execution continues after the try-catch, so "remaining code..." is printed.
Q464.Medium
Write a Java program to demonstrate throwing a user-defined exception. Define a custom exception class 'InvalidAgeException' that extends Exception. In the main method, throw an object of InvalidAgeException with the message "Age must be above 18", catch it, and print "Caught the exception" followed by the exception message.
Show answer & explanation
Answer:
class InvalidAgeException extends Exception {
    public InvalidAgeException(String str) {
        super(str);
    }
}
public class TestCustomException {
    public static void main(String[] args) {
        try {
            throw new InvalidAgeException("Age must be above 18");
        } catch (InvalidAgeException e) {
            System.out.println("Caught the exception");
            System.out.println(e.getMessage());
        }
    }
}
Explanation: 1. Create InvalidAgeException class extending Exception, with a constructor that calls super(str). 2. In main, use try block to throw new InvalidAgeException with message. 3. Catch block catches InvalidAgeException and prints "Caught the exception". 4. Then prints the exception message using getMessage(). 5. Output: Caught the exception followed by Age must be above 18.
Q465.Medium
Write a Java program to demonstrate the use of the super keyword to call a parent class constructor from a child class. Create a parent class 'Vehicle' with fields 'regNo' (int) and 'model' (String), and a constructor to initialize them. Create a child class 'Car' that extends 'Vehicle' and adds a field 'price' (double). The child class constructor should accept regNo, model, and price, and use super(regNo, model) to initialize the inherited fields. Include a method 'display()' in the child class to print the details. In the main method, create a Car object with regNo 101, model "Hyundai", and price 750000.0, and call display().
Show answer & explanation
Answer:
class Vehicle {
    int regNo;
    String model;
    Vehicle(int regNo, String model) {
        this.regNo = regNo;
        this.model = model;
    }
}

class Car extends Vehicle {
    double price;
    Car(int regNo, String model, double price) {
        super(regNo, model);
        this.price = price;
    }
    void display() {
        System.out.println(regNo + " " + model + " " + price);
    }
}

public class TestSuper {
    public static void main(String[] args) {
        Car c1 = new Car(101, "Hyundai", 750000.0);
        c1.display();
    }
}
Explanation: 1. Define class Vehicle with fields regNo and model, and a constructor to initialize them. 2. Define class Car that extends Vehicle, adding field price. 3. In Car's constructor, call super(regNo, model) to invoke Vehicle's constructor and initialize inherited fields. 4. Assign price to the Car's field. 5. The display method prints regNo, model, and price. 6. In main, create a Car object with given values and call display, which outputs: 101 Hyundai 750000.0
Q466.Medium
Write a Java program that demonstrates the ByteArrayOutputStream class. The program should write the byte value 66 into a ByteArrayOutputStream and then copy that same data into two files, notes1.txt and notes2.txt, using writeTo(). Finally print "Done" to the console.
Show answer & explanation
Answer:
import java.io.*;

public class ByteArrayDemo {
    public static void main(String args[]) throws Exception {
        FileOutputStream out1 = new FileOutputStream("notes1.txt");
        FileOutputStream out2 = new FileOutputStream("notes2.txt");

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        bout.write(66);
        bout.writeTo(out1);
        bout.writeTo(out2);

        bout.flush();
        bout.close(); // has no effect on a ByteArrayOutputStream
        out1.close();
        out2.close();
        System.out.println("Done");
    }
}
Explanation: 1) Create two FileOutputStream objects for notes1.txt and notes2.txt. 2) Create a ByteArrayOutputStream bout which stores bytes in memory. 3) bout.write(66) stores the single byte 66 in the internal buffer. 4) bout.writeTo(out1) writes the entire buffer content to the first file; bout.writeTo(out2) writes the same content to the second file. 5) flush() and close() on ByteArrayOutputStream have no real effect since it is memory based; closing the file streams releases them. 6) Finally "Done" is printed.
Q467.Medium
Write a Java program to demonstrate exception propagation. Create a class ExceptionPropagationDemo with three methods: method1(), method2(), and method3(). In method1(), perform an integer division by zero (e.g., int result = 100 / 0;). method2() calls method1(). method3() calls method2() inside a try-catch block that catches Exception and prints "Exception caught". In the main method, create an object and call method3(), then print "Program continues". Show that the unchecked exception propagates from method1 to method3 where it is handled.
Show answer & explanation
Answer:
public class ExceptionPropagationDemo {
    void method1() {
        int result = 100 / 0;
    }
    void method2() {
        method1();
    }
    void method3() {
        try {
            method2();
        } catch (Exception e) {
            System.out.println("Exception caught");
        }
    }
    public static void main(String[] args) {
        ExceptionPropagationDemo demo = new ExceptionPropagationDemo();
        demo.method3();
        System.out.println("Program continues");
    }
}
Explanation: 1. method1() performs division by zero, which throws an ArithmeticException (an unchecked exception). 2. Since method1() does not handle it, the exception propagates to method2(), which called method1(). 3. method2() does not handle it either, so it propagates to method3(). 4. method3() has a try-catch block that catches Exception, so it prints "Exception caught". 5. After handling, method3() returns normally, and main() prints "Program continues". 6. This demonstrates that unchecked exceptions are automatically propagated up the call stack until caught.
Q468.Medium
Write a Java program that demonstrates exception propagation using the throws keyword. Create a class 'Demo' with three methods: methodA() that throws an IOException with message "Input error", methodB() that calls methodA() and declares throws IOException, and methodC() that calls methodB() inside a try-catch block catching Exception and printing "Exception handled". In the main method, create a Demo object, call methodC(), and then print "Execution completed". The program should compile and run without errors.
Show answer & explanation
Answer:
import java.io.IOException;

class Demo {
    void methodA() throws IOException {
        throw new IOException("Input error");
    }
    void methodB() throws IOException {
        methodA();
    }
    void methodC() {
        try {
            methodB();
        } catch (Exception e) {
            System.out.println("Exception handled");
        }
    }
}

public class ExceptionPropagation {
    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.methodC();
        System.out.println("Execution completed");
    }
}
Explanation: 1. Define class Demo with methodA() that throws IOException with message "Input error". 2. methodB() calls methodA() and declares throws IOException, propagating the exception. 3. methodC() calls methodB() inside a try-catch block that catches Exception and prints "Exception handled". 4. In main, create Demo object, call methodC(), then print "Execution completed". 5. When run, the exception propagates from methodA to methodB to methodC where it is caught, and execution continues.
Q469.Medium
Write a Java program to demonstrate that Java monitors are reentrant. Create a class ReentrantDemo with two synchronized methods: outer() and inner(). The outer() method should call inner() and then print "Inside outer method". The inner() method should print "Inside inner method". In the main method, create an object of ReentrantDemo and call outer(). Show that a thread can reacquire the same monitor when calling a synchronized method from another synchronized method of the same object.
Show answer & explanation
Answer:
public class ReentrantDemo {
    public synchronized void outer() {
        inner();
        System.out.println("Inside outer method");
    }
    public synchronized void inner() {
        System.out.println("Inside inner method");
    }
    public static void main(String[] args) {
        ReentrantDemo demo = new ReentrantDemo();
        demo.outer();
    }
}
Explanation: 1. The class ReentrantDemo has two synchronized methods: outer() and inner(). 2. When a thread calls outer(), it acquires the monitor (lock) of the ReentrantDemo object. 3. Inside outer(), it calls inner(). Since the thread already holds the monitor, it can reacquire it (reentrant). 4. inner() executes and prints "Inside inner method". 5. After inner() returns, outer() continues and prints "Inside outer method". 6. The main method creates an object and calls outer(), demonstrating reentrant behavior.
Q470.Medium
Write a Java program that demonstrates a static blank final variable. Declare a static final int variable named 'marks' without initializing it at declaration, initialize it inside a static block to 85, and then print its value from the main method.
Show answer & explanation
Answer:
class Student {
    static final int marks; // static blank final variable
    static {
        marks = 85;
    }
    public static void main(String args[]) {
        System.out.println(Student.marks);
    }
}
Explanation: 1) 'static final int marks;' is declared but not initialized, so it is a static blank final variable. 2) A static block runs once when the class is loaded; inside it we assign marks = 85, which is the only allowed initialization for a static blank final variable. 3) The main method prints Student.marks, which outputs 85. 4) Trying to assign marks again anywhere would cause a compile error, showing the final nature.
Q471.Medium
Write a Java program that prints the class loader of the current class and the class loader of the String class. Explain why the output for String is null.
Show answer & explanation
Answer:
public class ClassLoaderDemo {
    public static void main(String[] args) {
        Class<?> cls = ClassLoaderDemo.class;
        System.out.println(cls.getClassLoader());
        System.out.println(String.class.getClassLoader());
    }
}
Explanation: 1. The class ClassLoaderDemo is loaded by the application class loader (system class loader), so getClassLoader() returns sun.misc.Launcher$AppClassLoader@... (or similar). 2. The String class is part of the Java core library (rt.jar) and is loaded by the bootstrap class loader. 3. The bootstrap class loader is implemented in native code and is represented as null in Java, so getClassLoader() returns null for String. 4. Therefore, the program prints the application class loader for ClassLoaderDemo and null for String.
Q472.Medium
Write a Java program that demonstrates the String.format() method. Use a student name "Aarav" and print: (1) a string "student is Aarav" using %s, (2) a string "marks are 78.456000" using %f on the value 78.456, and (3) a string where the same value 78.456 is formatted with width 30 and 10 digits after the decimal point using %30.10f. Print all three results on separate lines.
Show answer & explanation
Answer:
public class FormatDemo {
    public static void main(String[] args) {
        String name = "Aarav";
        String s1 = String.format("student is %s", name);
        String s2 = String.format("marks are %f", 78.456);
        String s3 = String.format("marks are %30.10f", 78.456);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
}
Explanation: 1) %s inserts the string name, so s1 = "student is Aarav". 2) %f prints a floating value with 6 decimal places by default, so 78.456 becomes 78.456000, giving s2 = "marks are 78.456000". 3) %30.10f means total width 30 characters with 10 digits after the decimal point; 78.456 padded to 10 decimals is 78.4560000000 (13 chars), so it is left-padded with spaces to width 30. 4) Each result is printed with System.out.println on its own line.
Q473.Medium
Write a Java program that uses String.format() to format different data types into strings. Format the following values: an integer 305, a string "Priya Sharma", a float 305.00, the hexadecimal representation of 305, and the character 'k'. Print each formatted string on a new line.
Show answer & explanation
Answer:
public class FormatDataTypes {
    public static void main(String[] args) {
        String str1 = String.format("%d", 305);
        String str2 = String.format("%s", "Priya Sharma");
        String str3 = String.format("%f", 305.00);
        String str4 = String.format("%x", 305);
        String str5 = String.format("%c", 'k');
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        System.out.println(str5);
    }
}
Explanation: 1. The program defines a class FormatDataTypes and a main method. 2. str1 uses %d to format 305 as an integer: "305". 3. str2 uses %s to format the string "Priya Sharma": "Priya Sharma". 4. str3 uses %f to format 305.00 as a floating-point number: "305.000000" (default six decimal places). 5. str4 uses %x to format 305 as a hexadecimal integer: 305 in decimal is 131 in hex, so "131". 6. str5 uses %c to format the character 'k': "k". 7. Each string is printed on its own line.
Q474.Medium
Write a Java program that demonstrates formatting an integer with width and padding using String.format(). Specifically, format the integer 250 in the following ways: (1) as a plain integer, (2) right-aligned in a width of 8 characters, (3) left-aligned in a width of 8 characters, (4) with a leading space for positive numbers (using '% d'), and (5) zero-padded to a total width of 8 characters. Print each formatted string on a new line.
Show answer & explanation
Answer:
public class FormatWidthPadding {
    public static void main(String[] args) {
        String str1 = String.format("%d", 250);
        String str2 = String.format("|%8d|", 250);
        String str3 = String.format("|%-8d|", 250);
        String str4 = String.format("|% d|", 250);
        String str5 = String.format("|%08d|", 250);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        System.out.println(str5);
    }
}
Explanation: 1. The program defines a class FormatWidthPadding and a main method. 2. str1 uses %d to format 250 as a plain integer: "250". 3. str2 uses |%8d| to right-align 250 in an 8-character field: five spaces then 250, enclosed in pipes: "| 250|". 4. str3 uses |%-8d| to left-align 250 in an 8-character field: 250 then five spaces: "|250 |". 5. str4 uses |% d| to include a leading space for positive numbers: "| 250|". 6. str5 uses |%08d| to zero-pad to width 8: five zeros then 250: "|00000250|". 7. Each string is printed on its own line.
Q475.Medium
Write a Java program that demonstrates that calling join() on a thread which gets interrupted throws InterruptedException. Create a class named Worker that extends Thread and stores a reference to another thread (the one to be interrupted). In its run() method, it should call interrupt() on that stored thread. In main, create a thread 'helper' that simply sleeps for a long time, start it, create a Worker thread passing 'helper' as the thread to interrupt, start the worker, and then call helper.join() inside a try-catch so that the InterruptedException is caught and its message printed. Name the file InterruptJoinDemo.java.
Show answer & explanation
Answer:
public class InterruptJoinDemo {
    static class Worker extends Thread {
        Thread threadToInterrupt;
        Worker(Thread t) {
            this.threadToInterrupt = t;
        }
        public void run() {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
            threadToInterrupt.interrupt();
        }
    }

    public static void main(String[] args) {
        Thread helper = new Thread(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
        });
        helper.start();

        // the worker interrupts the main thread, which is blocked in helper.join()
        Worker w = new Worker(Thread.currentThread());
        w.start();

        try {
            helper.join();
        } catch (InterruptedException e) {
            System.out.println("join() threw InterruptedException: " + e.getMessage());
        }
        helper.interrupt();
        System.out.println("Main finished");
    }
}
Explanation: 1) Worker extends Thread and holds a reference to the thread it must interrupt. 2) Worker.run() calls threadToInterrupt.interrupt(), which interrupts the helper thread. 3) In main, helper is started and sleeps for 10 seconds. 4) The worker thread is started, so it interrupts helper almost immediately. 5) main calls helper.join(), which waits for helper to finish. 6) Because helper was interrupted while main was waiting in join(), join() throws InterruptedException, which is caught and printed.
Q476.Medium
Write a Java program named JoinTimeoutDemo.java that creates three threads of the same class. Each thread's run() method prints the numbers 1 to 4, pausing 400 milliseconds before each number. In main, start the first thread and call join(1200) on it (handling InterruptedException), then start the second and third threads.
Show answer & explanation
Answer:
class JoinTimeoutDemo extends Thread {
    public void run() {
        for (int i = 1; i <= 4; i++) {
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
            System.out.println(i);
        }
    }

    public static void main(String args[]) {
        JoinTimeoutDemo t1 = new JoinTimeoutDemo();
        JoinTimeoutDemo t2 = new JoinTimeoutDemo();
        JoinTimeoutDemo t3 = new JoinTimeoutDemo();
        t1.start();
        try {
            t1.join(1200);
        } catch (InterruptedException e) {
            System.out.println(e);
        }
        t2.start();
        t3.start();
    }
}
Explanation: 1. The class JoinTimeoutDemo extends Thread and overrides run(). 2. run() loops i = 1 to 4; before printing each i it sleeps 400 ms, so t1 prints 1,2,3 at roughly 400,800,1200 ms. 3. main creates t1, t2, t3 and starts t1. 4. t1.join(1200) makes main wait at most 1200 ms for t1; since t1 needs about 1600 ms total, main resumes after the timeout (t1 has printed 1,2,3). 5. main then starts t2 and t3, which run concurrently with the rest of t1.
Q477.Medium
Write a Java program where a method declares that it may throw an IOException using the throws keyword, but no exception actually occurs. The method should print "payment processed" and the main method (which also declares throws IOException) should call it and then print "normal flow...". Show that the program runs fine when the exception does not occur.
Show answer & explanation
Answer:
import java.io.*;

class PaymentService {
    void processPayment() throws IOException {
        System.out.println("payment processed");
    }
}

public class TestThrowsDemo {
    public static void main(String args[]) throws IOException { // declare exception
        PaymentService ps = new PaymentService();
        ps.processPayment();

        System.out.println("normal flow...");
    }
}
Explanation: Step 1: Define class PaymentService with method processPayment() that declares throws IOException but only prints "payment processed". Step 2: Define main method that also declares throws IOException (declaring, not handling). Step 3: Create a PaymentService object and call processPayment(); since no exception is thrown, it prints "payment processed". Step 4: Control returns to main, which then prints "normal flow...". Step 5: Because no exception actually occurs, the throws declaration has no effect and the program completes normally. Output: payment processed normal flow...
Q478.Medium
Write a Java program (file: WorkerThread.java) that shows that a thread cannot be made a daemon after it has been started. Create a class WorkerThread extending Thread whose run() prints the current thread's name and whether it is a daemon. In main, create two WorkerThread objects, start the first one, then call setDaemon(true) on it (which must throw IllegalThreadStateException), and finally start the second thread.
Show answer & explanation
Answer:
public class WorkerThread extends Thread {
    public void run() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Name: " + Thread.currentThread().getName());
        System.out.println("Daemon: " + Thread.currentThread().isDaemon());
    }

    public static void main(String[] args) {
        WorkerThread w1 = new WorkerThread();
        WorkerThread w2 = new WorkerThread();
        w1.start();
        try {
            w1.setDaemon(true); // throws IllegalThreadStateException
        } catch (IllegalThreadStateException e) {
            System.out.println("Cannot set daemon after start: " + e);
        }
        w2.start();
    }
}
Explanation: 1) WorkerThread extends Thread and overrides run() to print the running thread's name and daemon status. 2) In main, two WorkerThread objects w1 and w2 are created. 3) w1.start() begins execution of w1, so w1 is now an alive thread. 4) Calling w1.setDaemon(true) after start() throws IllegalThreadStateException; the try-catch prints the message instead of crashing. 5) w2.start() then runs normally as a user thread.
Q479.Medium
Write a Java program in a file named TestThrow.java with a method checkNum(int num) that throws an ArithmeticException with the message "Number is negative, cannot calculate square" if num is less than 1; otherwise it prints "Square of <num> is <num*num>". In main(), create an object of the class, call checkNum(-3), and then print "Rest of the code..".
Show answer & explanation
Answer:
public class TestThrow {
    // method that validates the number before squaring
    public static void checkNum(int num) {
        if (num < 1) {
            throw new ArithmeticException("Number is negative, cannot calculate square");
        }
        else {
            System.out.println("Square of " + num + " is " + (num * num));
        }
    }

    public static void main(String[] args) {
        TestThrow obj = new TestThrow();
        obj.checkNum(-3);
        System.out.println("Rest of the code..");
    }
}
Explanation: 1) checkNum(int num) checks whether num < 1; if true it uses 'throw new ArithmeticException(...)' to raise an exception with the given message. 2) main() creates an object obj of TestThrow and calls obj.checkNum(-3). 3) Since -3 < 1, the method throws ArithmeticException instead of printing the square. 4) There is no try-catch in main(), so the exception propagates and the JVM prints the exception message and stack trace. 5) Because the exception is uncaught, the line System.out.println("Rest of the code..") is never executed.
Q480.Medium
Write a Java program in a file named TestThrowAndThrows.java that demonstrates the use of 'throws' and 'throw'. Create a static method called method() that declares 'throws ArithmeticException', prints "Inside the method()", and then throws a new ArithmeticException with the message "throwing ArithmeticException". In main(), call method() inside a try block and catch ArithmeticException, printing "caught in main() method" in the catch block.
Show answer & explanation
Answer:
public class TestThrowAndThrows
{
    // user-defined method that declares it may throw ArithmeticException
    static void method() throws ArithmeticException
    {
        System.out.println("Inside the method()");
        throw new ArithmeticException("throwing ArithmeticException");
    }

    public static void main(String args[])
    {
        try
        {
            method();
        }
        catch(ArithmeticException e)
        {
            System.out.println("caught in main() method");
        }
    }
}
Explanation: 1) The method() signature uses 'throws ArithmeticException' to declare that it may throw this unchecked exception. 2) Inside method(), it first prints "Inside the method()" and then uses 'throw new ArithmeticException(...)' to actually raise the exception. 3) main() calls method() inside a try block, so when the exception is thrown, control jumps to the catch block. 4) The catch(ArithmeticException e) block prints "caught in main() method", so the program ends normally. 5) Output: first line "Inside the method()", second line "caught in main() method".
Q481.Medium
Write a Java program that demonstrates whether Java comments are executed. The program should include a comment containing a Unicode escape sequence that, when processed, causes a statement to be executed. The program should print a message indicating that the comment was executed. Use the class name 'Demo'.
Show answer & explanation
Answer:
public class Demo {
    public static void main(String[] args) {
        // This comment will be executed
        // \u000d System.out.println("Comment executed!");
    }
}
Explanation: 1. Java processes Unicode escapes (like \u000d) before lexical analysis, even inside comments. 2. The sequence \u000d is a carriage return, which ends the comment line. 3. The rest of the line becomes actual code: System.out.println("Comment executed!"); 4. Thus, the statement is executed and prints 'Comment executed!'. 5. This shows that comments can be indirectly executed via Unicode escapes.
Q482.Medium
Write a Java program that uses the DataOutputStream class to write an integer value 75 to a text file named dataout.txt on the D: drive, flush and close the stream, and then print "Done..." to the console.
Show answer & explanation
Answer:
import java.io.*;
public class DataOutputDemo {
    public static void main(String[] args) throws IOException {
        FileOutputStream file = new FileOutputStream("D:\\dataout.txt");
        DataOutputStream data = new DataOutputStream(file);
        data.writeInt(75);
        data.flush();
        data.close();
        System.out.println("Done...");
    }
}
Explanation: 1) FileOutputStream opens (or creates) the file D:\dataout.txt for writing bytes. 2) DataOutputStream wraps the file stream so primitive types can be written in binary form. 3) data.writeInt(75) writes the 4-byte binary representation of 75 to the file. 4) data.flush() forces any buffered bytes to the file, and data.close() releases the stream. 5) Finally "Done..." is printed to the console.
Q483.Medium
Write a Java program that demonstrates converting a String into byte arrays using different character encodings. Use the input string "Namaste India." and print the byte values (as integers) obtained from getBytes() for the charsets "UTF-16", "UTF-16BE", "ISO-8859-1" and "UTF-16LE". Handle the UnsupportedEncodingException with a try-catch block. Name the file CharsetBytesDemo.java.
Show answer & explanation
Answer:
import java.io.*;

public class CharsetBytesDemo
{
    public static void main(String[] args)
    {
        String str = "Namaste India.";
        System.out.println("The input String is : ");
        System.out.println(str + "\n");

        try
        {
            byte[] byteArr = str.getBytes("UTF-16");
            System.out.println("After converted into UTF-16 the String is : ");
            for (int j = 0; j < byteArr.length; j++)
            {
                System.out.print(byteArr[j]);
            }
            System.out.println("\n");

            byte[] byteArr1 = str.getBytes("UTF-16BE");
            System.out.println("After converted into UTF-16BE the String is : ");
            for (int j = 0; j < byteArr1.length; j++)
            {
                System.out.print(byteArr1[j]);
            }
            System.out.println("\n");

            byte[] byteArr2 = str.getBytes("ISO-8859-1");
            System.out.println("After converted into ISO-8859-1 the String is : ");
            for (int j = 0; j < byteArr2.length; j++)
            {
                System.out.print(byteArr2[j]);
            }
            System.out.println("\n");

            byte[] byteArr3 = str.getBytes("UTF-16LE");
            System.out.println("After converted into UTF-16LE the String is : ");
            for (int j = 0; j < byteArr3.length; j++)
            {
                System.out.print(byteArr3[j]);
            }
        }
        catch (UnsupportedEncodingException g)
        {
            System.out.println("Unsupported character set" + g);
        }
    }
}
Explanation: 1. Create a String str = "Namaste India.". 2. Call str.getBytes("UTF-16") which returns a byte array; UTF-16 adds a byte-order mark (two bytes) at the start, so the array is longer than the plain characters. 3. Loop over the byte array and print each byte as an integer using System.out.print. 4. Repeat the same for "UTF-16BE" (big-endian, no BOM), "ISO-8859-1" (one byte per Latin character) and "UTF-16LE" (little-endian, no BOM). 5. getBytes(String) throws UnsupportedEncodingException, so the calls are placed inside a try block with a catch that prints an error message.
Q484.Medium
Write a Java program that demonstrates the getBytes() method of the String class when an unsupported character encoding is specified. The program should attempt to convert the string "Welcome to India." into bytes using the encoding "UTF-17". Since this encoding is not supported, the getBytes() method will throw an UnsupportedEncodingException. Handle this exception by printing the message "Unsupported encoding: UTF-17" to the standard error stream. The program should be in a class named StringGetBytesExample4.
Show answer & explanation
Answer:
public class StringGetBytesExample4 {
    public static void main(String[] args) {
        String str = "Welcome to India.";
        System.out.println("The input String is: ");
        System.out.println(str + "\n");
        try {
            byte[] byteArr = str.getBytes("UTF-17");
            System.out.println("After converted into UTF-17 the String is: ");
            for (int j = 0; j < byteArr.length; j++) {
                System.out.print(byteArr[j]);
            }
        } catch (java.io.UnsupportedEncodingException e) {
            System.err.println("Unsupported encoding: UTF-17");
        }
    }
}
Explanation: 1. Declare a string str with the value "Welcome to India.". 2. Print the original string. 3. Use a try-catch block to handle UnsupportedEncodingException. 4. Inside try, call str.getBytes("UTF-17"). Since "UTF-17" is not a supported encoding, this throws UnsupportedEncodingException. 5. The catch block catches the exception and prints the error message to System.err. 6. If the encoding were supported, the program would print the byte array values.
Q485.Medium
Write a Java program that demonstrates the three types of variables in Java: a static variable shared by all objects, an instance variable, and a local variable inside a method. Use a static variable marks = 80, an instance variable rollNo = 12, and a local variable count = 5 inside a method.
Show answer & explanation
Answer:
public class Student {
    static int marks = 80;   // static variable
    int rollNo = 12;         // instance variable

    void show() {
        int count = 5;       // local variable
        System.out.println(count);
    }

    public static void main(String[] args) {
        Student s = new Student();
        s.show();
        System.out.println(marks);
        System.out.println(s.rollNo);
    }
}
Explanation: 1) static int marks = 80 is a static variable: only one copy exists and it is shared by all objects of the class. 2) int rollNo = 12 is an instance variable: each object gets its own copy. 3) Inside method show(), int count = 5 is a local variable: it exists only while the method runs. 4) In main, an object s is created, show() prints the local variable 5. 5) marks is printed directly (static), and s.rollNo is printed through the object, giving 80 and 12.
Q486.Medium
Write a Java program that assigns the int value 200 to an int variable, then narrows it to a byte variable using a cast. Print both the int value and the byte value.
Show answer & explanation
Answer:
public class ByteOverflowDemo {
    public static void main(String[] args) {
        int a = 200;
        byte b = (byte)a;
        System.out.println(a);
        System.out.println(b);
    }
}
Explanation: 1) Declare int a = 200. 2) Cast it to byte: byte b = (byte)a; this keeps only the low 8 bits. 3) 200 in binary is 11001000, which as a signed byte equals -56 (since 200 - 256 = -56). 4) Print a, which outputs 200. 5) Print b, which outputs -56 due to overflow in the narrowing conversion.
Q487.Medium
Write a Java program to demonstrate upcasting. Create a class Animal with a method sound() that prints "Animal makes a sound". Create a subclass Dog that extends Animal and overrides sound() to print "Dog barks". In the main method, create a Dog object and assign it to an Animal reference. Call sound() using that reference. What is the output?
Show answer & explanation
Answer:
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

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

    public static void main(String[] args) {
        Animal a = new Dog(); // upcasting
        a.sound();
    }
}
Explanation: 1. Define a parent class Animal with a method sound() that prints "Animal makes a sound". 2. Define a child class Dog that extends Animal and overrides sound() to print "Dog barks". 3. In main, create a Dog object and assign it to an Animal reference (upcasting). 4. Call sound() using the Animal reference. At runtime, the JVM sees the actual object is Dog, so Dog's sound() is invoked. 5. Output: Dog barks.
Q488.Medium
Write a Java program that demonstrates that runtime polymorphism cannot be achieved through data members. Create a parent class Vehicle with an integer data member maxSpeed = 80, and a child class Car (extends Vehicle) with its own data member maxSpeed = 120. In the main method, declare a Vehicle reference that points to a Car object, and print the value of maxSpeed accessed through that reference.
Show answer & explanation
Answer:
class Vehicle {
    int maxSpeed = 80;
}

class Car extends Vehicle {
    int maxSpeed = 120;
}

class TestPolymorphism {
    public static void main(String[] args) {
        Vehicle v = new Car();
        System.out.println(v.maxSpeed);
    }
}
Explanation: 1. Vehicle declares maxSpeed = 80; Car hides it with its own maxSpeed = 120. 2. Data members are not overridden in Java — they are hidden, and access is decided by the reference type at compile time. 3. v is declared as Vehicle, so v.maxSpeed reads Vehicle's field. 4. Hence the program prints 80, showing runtime polymorphism does not apply to data members.
Q489.Medium
Write a Java program that demonstrates the legal usage of the strictfp keyword. Show that strictfp can be applied to a class, to an interface, and to a method. Create a strictfp class named Shape, a strictfp interface named Measurable, and inside the Shape class a strictfp method named computeArea that prints a message.
Show answer & explanation
Answer:
strictfp class Shape {
    strictfp void computeArea() {
        System.out.println("Computing area with strict floating-point precision");
    }
}

strictfp interface Measurable {
    double area();
}

class Main {
    public static void main(String[] args) {
        Shape s = new Shape();
        s.computeArea();
    }
}
Explanation: 1) The strictfp keyword forces the same floating-point results on every platform. 2) It may be applied to a class: 'strictfp class Shape' makes all its float/double operations strict. 3) It may be applied to an interface: 'strictfp interface Measurable'. 4) It may be applied to a method: 'strictfp void computeArea()'. 5) The main method creates a Shape object and calls computeArea, which prints the message.
Q490.Medium
Write a Java program that demonstrates the illegal uses of the strictfp keyword: applying it to an abstract method, to an instance variable, and to a constructor. Show each illegal case in its own class so the compiler reports an error for each.
Show answer & explanation
Answer:
class A {
    strictfp abstract void show(); // illegal: strictfp not allowed on abstract methods
}

class B {
    strictfp int value = 25; // illegal: strictfp not allowed on variables
}

class C {
    strictfp C() {} // illegal: strictfp not allowed on constructors
}
Explanation: 1) The strictfp modifier may only be applied to classes, interfaces and non-abstract methods. 2) In class A, marking an abstract method strictfp is illegal because an abstract method has no body to enforce strict floating-point behaviour. 3) In class B, marking an instance variable strictfp is illegal because strictfp does not apply to fields. 4) In class C, marking a constructor strictfp is illegal because constructors cannot take the strictfp modifier. 5) Each of these snippets therefore causes a compile-time error, illustrating the illegal combinations.
Q491.Hard
Write a Java program that prints numbers from 1 to 30 using two threads: one thread prints odd numbers and the other prints even numbers, in order. Use a synchronized block and wait()/notify() for coordination. The output should be: 1 2 3 4 ... 30.
Show answer & explanation
Answer:
public class OddEvenPrinter {
    private int count = 1;
    private static final int MAX = 30;

    public void printOdd() {
        synchronized (this) {
            while (count < MAX) {
                while (count % 2 == 0) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(count + " ");
                count++;
                notify();
            }
        }
    }

    public void printEven() {
        synchronized (this) {
            while (count < MAX) {
                while (count % 2 == 1) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(count + " ");
                count++;
                notify();
            }
        }
    }

    public static void main(String[] args) {
        OddEvenPrinter printer = new OddEvenPrinter();
        Thread t1 = new Thread(() -> printer.printOdd());
        Thread t2 = new Thread(() -> printer.printEven());
        t1.start();
        t2.start();
    }
}
Explanation: 1. The shared counter `count` starts at 1 and goes up to 30. 2. Two threads run methods `printOdd` and `printEven`, both synchronized on the same object. 3. The odd thread waits while `count` is even; the even thread waits while `count` is odd. 4. When a thread prints a number, it increments `count` and calls `notify()` to wake the other thread. 5. The loop continues until `count` reaches 30, printing numbers in order.
Q492.Hard
Write a Java program demonstrating inter-thread communication. Create a class Account with an int balance = 8000. It has a synchronized method withdraw(int amt) that prints "going to withdraw...", and if balance < amt prints "Less balance; waiting for deposit..." and calls wait(); otherwise it subtracts amt and prints "withdraw completed...". It also has a synchronized method deposit(int amt) that prints "going to deposit...", adds amt to balance, prints "deposit completed..." and calls notify(). In main, start one thread that withdraws 10000 and another thread that deposits 3000 after a short delay.
Show answer & explanation
Answer:
class Account{
int balance=8000;

synchronized void withdraw(int amt){
System.out.println("going to withdraw...");
if(this.balance<amt){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.balance-=amt;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amt){
System.out.println("going to deposit...");
this.balance+=amt;
System.out.println("deposit completed...");
notify();
}
}

public class InterThreadDemo{
public static void main(String args[]){
final Account a=new Account();
new Thread(){
public void run(){a.withdraw(10000);}
}.start();
new Thread(){
public void run(){
try{Thread.sleep(500);}catch(Exception e){}
a.deposit(3000);
}
}.start();
}
}
Explanation: 1) Account holds balance=8000 and two synchronized methods so only one thread uses the object at a time. 2) The withdraw thread enters withdraw(10000): balance 8000 < 10000, so it prints the waiting message and calls wait(), releasing the lock. 3) The deposit thread then acquires the lock, adds 3000 (balance becomes 11000), prints deposit completed and calls notify(). 4) notify() wakes the waiting withdraw thread, which re-acquires the lock, subtracts 10000 (balance 1000) and prints withdraw completed. 5) wait() releases the lock while sleep() would not; that is why wait/notify is used for this coordination.
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