Coding Questions Questions

Question Bank › Technical › Java › Coding Questions

12345

Other questions

Q201.Easy
Write a Java program that demonstrates the toCharArray() method of the String class. Create a string with the value "world", convert it to a character array, and then print each character on the same line.
Show answer & explanation
Answer:
public class StringToCharArrayExample {
    public static void main(String[] args) {
        String s = "world";
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            System.out.print(ch[i]);
        }
    }
}
Explanation: 1. Define a class StringToCharArrayExample with a main method. 2. Create a String variable s and assign it the value "world". 3. Call the toCharArray() method on s to convert it into a character array ch. 4. Use a for loop to iterate over the array from index 0 to ch.length-1. 5. Inside the loop, print each character using System.out.print(ch[i]). 6. The output will be 'world' printed on one line.
Q202.Easy
Write a Java program that takes the string "Learning Java is fun", converts it into a character array using the toCharArray() method, prints the length of the character array, and then prints each character of the array on its own line.
Show answer & explanation
Answer:
public class StringToCharArrayExample {
    public static void main(String[] args) {
        String s1 = "Learning Java is fun";
        char[] ch = s1.toCharArray();
        int len = ch.length;
        System.out.println("Char Array length: " + len);
        System.out.println("Char Array elements: ");
        for (int i = 0; i < len; i++) {
            System.out.println(ch[i]);
        }
    }
}
Explanation: 1. Declare a String s1 with the value "Learning Java is fun". 2. Call s1.toCharArray() to get a char array ch containing every character. 3. Store ch.length in len and print it (the string has 19 characters). 4. Loop from i = 0 to len-1, printing each ch[i] on a separate line. 5. This prints the length followed by each character one per line.
Q203.Easy
Write a Java program that reads the contents of a text file named "notes.txt" located at D:\notes.txt using the BufferedReader class, and prints each character of the file to the console. Close both the BufferedReader and the FileReader at the end.
Show answer & explanation
Answer:
import java.io.*;
public class ReadFileExample {
    public static void main(String args[]) throws Exception {
        FileReader fr = new FileReader("D:\\notes.txt");
        BufferedReader br = new BufferedReader(fr);

        int c;
        while ((c = br.read()) != -1) {
            System.out.print((char) c);
        }
        br.close();
        fr.close();
    }
}
Explanation: 1. Import java.io.* to get FileReader and BufferedReader. 2. Create a FileReader pointing to D:\notes.txt. 3. Wrap it in a BufferedReader for efficient reading. 4. br.read() returns the next character as an int, or -1 at end of file. 5. Loop while the value is not -1, casting each int to char and printing it. 6. Finally close the BufferedReader and the FileReader.
Q204.Easy
Write a Java program that reads a person's name from the console using InputStreamReader and BufferedReader, then prints a welcome message in the form "Welcome <name>".
Show answer & explanation
Answer:
import java.io.*;
public class WelcomeReader {
    public static void main(String args[]) throws Exception {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(reader);
        System.out.println("Enter your name");
        String name = br.readLine();
        System.out.println("Welcome " + name);
    }
}
Explanation: 1. Create an InputStreamReader connected to System.in to read keyboard input. 2. Wrap it in a BufferedReader to read a full line of text. 3. Print the prompt "Enter your name". 4. Use br.readLine() to read the name typed by the user into the String name. 5. Print "Welcome " concatenated with the name.
Q205.Easy
Write a Java program that repeatedly reads lines of text from the console using InputStreamReader and BufferedReader, printing each line back, and stops when the user enters the word "bye".
Show answer & explanation
Answer:
import java.io.*;
public class ConsoleLoopExample {
    public static void main(String args[]) throws Exception {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(reader);
        String input = "";
        while (!input.equals("bye")) {
            System.out.println("Enter data: ");
            input = br.readLine();
            System.out.println("data is: " + input);
        }
        br.close();
        reader.close();
    }
}
Explanation: 1. Create an InputStreamReader wrapping System.in to read bytes from the keyboard. 2. Wrap it in a BufferedReader so we can read whole lines with readLine(). 3. Initialize input to an empty string so the loop starts. 4. The while loop runs as long as input is not equal to "bye". 5. Inside the loop, prompt the user, read a line, and print it back. 6. When the user types "bye", the condition fails and the loop ends. 7. Close the BufferedReader and the InputStreamReader.
Q206.Easy
Write a Java program that uses BufferedWriter to write the text "Welcome to India" to a file named "output.txt" in the current directory. After writing, close the writer and print "Done" to the console. Handle any exceptions by declaring throws Exception in the main method.
Show answer & explanation
Answer:
import java.io.*;

public class BufferedWriterDemo {
    public static void main(String[] args) throws Exception {
        FileWriter writer = new FileWriter("output.txt");
        BufferedWriter buffer = new BufferedWriter(writer);
        buffer.write("Welcome to India");
        buffer.close();
        System.out.println("Done");
    }
}
Explanation: 1. Import java.io.* to use FileWriter and BufferedWriter. 2. Define class BufferedWriterDemo with main method that throws Exception. 3. Create a FileWriter object writer for file "output.txt". 4. Wrap writer in a BufferedWriter object buffer. 5. Call buffer.write("Welcome to India") to write the string. 6. Call buffer.close() to flush and close the stream. 7. Print "Done" to the console.
Q207.Easy
Write a Java program that demonstrates the use of the CharArrayReader class. Create a character array containing the characters of the string "India", then use a CharArrayReader to read and print each character followed by its integer Unicode value, separated by " : ". The program should handle any exceptions.
Show answer & explanation
Answer:
import java.io.CharArrayReader;

public class CharArrayReaderDemo {
    public static void main(String[] args) throws Exception {
        char[] letters = { 'I', 'n', 'd', 'i', 'a' };
        CharArrayReader reader = new CharArrayReader(letters);
        int ch;
        while ((ch = reader.read()) != -1) {
            System.out.println((char) ch + " : " + ch);
        }
        reader.close();
    }
}
Explanation: 1. Import java.io.CharArrayReader. 2. Define a class CharArrayReaderDemo with main method that throws Exception. 3. Create a char array letters with characters 'I','n','d','i','a'. 4. Create a CharArrayReader object reader passing the array. 5. Use a while loop: read one character at a time into int ch; continue until read() returns -1. 6. Inside loop, cast ch to char and print it followed by " : " and the integer value ch. 7. After loop, close the reader.
Q208.Easy
Write a Java program that converts a given string to lowercase and prints the result. Use the string "WELCOME TO INDIA".
Show answer & explanation
Answer:
public class LowerCaseExample {
    public static void main(String[] args) {
        String s = "WELCOME TO INDIA";
        String lower = s.toLowerCase();
        System.out.println(lower);
    }
}
Explanation: 1. Define a string variable s with value "WELCOME TO INDIA". 2. Call the toLowerCase() method on s, which returns a new string with all characters converted to lowercase. 3. Store the result in variable lower. 4. Print the lower string using System.out.println. 5. The output will be "welcome to india".
Q209.Easy
Write a Java program that demonstrates the PrintStream class. Create a FileOutputStream for the file "C:\\output\\report.txt", wrap it in a PrintStream, write the integer 2024 and the strings "Namaste India" and "Welcome to Mumbai" using println, then close both streams and print "Done" to the console.
Show answer & explanation
Answer:
import java.io.FileOutputStream;
import java.io.PrintStream;

public class PrintStreamDemo {
    public static void main(String[] args) throws Exception {
        FileOutputStream fout = new FileOutputStream("C:\\output\\report.txt");
        PrintStream pout = new PrintStream(fout);
        pout.println(2024);
        pout.println("Namaste India");
        pout.println("Welcome to Mumbai");
        pout.close();
        fout.close();
        System.out.println("Done");
    }
}
Explanation: 1. Import java.io.FileOutputStream and java.io.PrintStream. 2. In main, create a FileOutputStream pointing to the target file path. 3. Wrap the FileOutputStream in a PrintStream so we can use println. 4. Call pout.println with the integer 2024 and the two strings; PrintStream writes them to the file. 5. Close the PrintStream first, then the FileOutputStream, to flush and release resources. 6. Finally print "Done" to the console with System.out.println.
Q210.Easy
Write a Java program that uses the printf() method of the PrintStream class (System.out) to print an integer value using the %d format specifier. Create a class named PrintDemo.java, declare int marks = 87 in main(), and print it with System.out.printf("%d", marks).
Show answer & explanation
Answer:
public class PrintDemo {
    public static void main(String[] args) {
        int marks = 87;
        System.out.printf("%d", marks);
    }
}
Explanation: 1) System.out is an object of PrintStream, which has a printf() method. 2) Declare int marks = 87. 3) printf("%d", marks) formats the integer using the %d specifier and prints it. 4) Output is: 87 (no newline, since no %n is used).
Q211.Easy
Write a Java program that creates the string s1 = "  welcome to mumbai   ", prints its length and the string itself (without trim), then stores s1.trim() in a variable and prints the trimmed string's length and the trimmed string. Name the class TrimLengthDemo.
Show answer & explanation
Answer:
public class TrimLengthDemo {
    public static void main(String[] args) {
        String s1 = "  welcome to mumbai   ";
        System.out.println(s1.length());
        System.out.println(s1); // Without trim()
        String tr = s1.trim();
        System.out.println(tr.length());
        System.out.println(tr); // With trim()
    }
}
Explanation: 1) s1 = " welcome to mumbai " has 2 leading spaces, the text 'welcome to mumbai' (17 characters) and 3 trailing spaces, so length = 2 + 17 + 3 = 22. 2) Printing s1 shows the spaces too. 3) s1.trim() removes the 2 leading and 3 trailing spaces, leaving 'welcome to mumbai' of length 17. 4) So the program prints 22, the padded string, then 17, then the trimmed string.
Q212.Easy
Write a Java program that checks whether a string contains only white spaces or also other characters. Use the trim() method: if the trimmed string's length is greater than 0, print "The string contains characters other than white spaces"; otherwise print "The string contains only white spaces". Test it first with the string "  delhi  " and then with a string made of only spaces "     ". Name the class WhitespaceCheck.
Show answer & explanation
Answer:
public class WhitespaceCheck
{
    public static void main(String[] args)
    {
        String str = "  delhi  ";

        if ((str.trim()).length() > 0)
        {
            System.out.println("The string contains characters other than white spaces");
        }
        else
        {
            System.out.println("The string contains only white spaces");
        }

        str = "     ";

        if ((str.trim()).length() > 0)
        {
            System.out.println("The string contains characters other than white spaces");
        }
        else
        {
            System.out.println("The string contains only white spaces");
        }
    }
}
Explanation: 1) Declare str = " delhi ". 2) str.trim() removes leading and trailing spaces giving "delhi", whose length is 5 > 0, so the first message 'contains characters other than white spaces' is printed. 3) Reassign str = " " (only spaces). 4) str.trim() gives an empty string of length 0, so the else branch prints 'contains only white spaces'. 5) The program thus demonstrates that trim() lets us detect whitespace-only strings.
Q213.Easy
Write a Java program to demonstrate that the trim() method returns a new string when the original string has leading or trailing whitespace, but returns the same string reference when there is no whitespace to trim. Use the strings "  hello  " and "world". Print the hash codes of the original and trimmed strings for both cases.
Show answer & explanation
Answer:
public class TrimDemo {
    public static void main(String[] args) {
        String strWithSpaces = "  hello  ";
        String trimmedStr = strWithSpaces.trim();
        System.out.println(strWithSpaces.hashCode());
        System.out.println(trimmedStr.hashCode());

        String strWithoutSpaces = "world";
        String sameStr = strWithoutSpaces.trim();
        System.out.println(strWithoutSpaces.hashCode());
        System.out.println(sameStr.hashCode());
    }
}
Explanation: 1. Create a string with leading and trailing spaces: " hello ". 2. Call trim() to get a new string without spaces. 3. Print hashCode() of both strings; they will differ because trim() created a new string. 4. Create a string without spaces: "world". 5. Call trim(); since no trimming is needed, the same string reference is returned. 6. Print hashCode() of both; they will be the same.
Q214.Easy
Write a Java program to demonstrate that strings are immutable. Create a string variable 'name' with the value "Amit". Then call the concat method on it to append " Sharma" and store the result in a new variable 'fullName'. Print both 'name' and 'fullName'. Explain why 'name' remains unchanged.
Show answer & explanation
Answer:
class StringImmutableDemo {
    public static void main(String[] args) {
        String name = "Amit";
        String fullName = name.concat(" Sharma");
        System.out.println("name: " + name);
        System.out.println("fullName: " + fullName);
    }
}
Explanation: 1. Declare a String variable 'name' and assign "Amit". 2. Call 'concat(" Sharma")' on 'name' and assign the result to 'fullName'. The concat method returns a new String; it does not modify the original. 3. Print 'name' and 'fullName'. 'name' prints "Amit" because strings are immutable; 'fullName' prints "Amit Sharma". 4. This shows that the original string remains unchanged.
Q215.Easy
Write a Java program that uses the PrintWriter class to write a message to the console and another message to a file named "output.txt". The console message should be "Hello, this is a test." and the file message should be "Writing to a file using PrintWriter.". The program should flush and close the writer after each use.
Show answer & explanation
Answer:
import java.io.File;
import java.io.PrintWriter;

public class PrintWriterDemo {
    public static void main(String[] args) throws Exception {
        // Write to console
        PrintWriter consoleWriter = new PrintWriter(System.out);
        consoleWriter.write("Hello, this is a test.");
        consoleWriter.flush();
        consoleWriter.close();

        // Write to file
        PrintWriter fileWriter = new PrintWriter(new File("output.txt"));
        fileWriter.write("Writing to a file using PrintWriter.");
        fileWriter.flush();
        fileWriter.close();
    }
}
Explanation: 1. Import java.io.File and java.io.PrintWriter. 2. Create a PrintWriter for System.out to write to the console. 3. Use write() to output the console message, then flush() and close(). 4. Create another PrintWriter for the file "output.txt". 5. Write the file message, then flush() and close() to save it.
Q216.Easy
Write a Java program that stores the integer 45 in a variable, converts it to a String using String.valueOf(int), then concatenates the string "10" to it and prints the result.
Show answer & explanation
Answer:
public class IntToStringDemo {
    public static void main(String[] args) {
        int marks = 45;
        String s1 = String.valueOf(marks);
        System.out.println(s1 + 10);
    }
}
Explanation: 1) Declare an int variable marks = 45. 2) String.valueOf(marks) converts the integer 45 into the string "45" and stores it in s1. 3) The expression s1 + 10 concatenates the string "45" with the number 10, giving "4510" (string concatenation, not addition). 4) System.out.println prints 4510.
Q217.Easy
Write a Java program that converts two boolean values (one true, one false) into their String representations using String.valueOf(boolean), and prints both resulting strings on separate lines.
Show answer & explanation
Answer:
public class BooleanToStringDemo {
    public static void main(String[] args) {
        boolean isPassed = true;
        boolean isFailed = false;
        String s1 = String.valueOf(isPassed);
        String s2 = String.valueOf(isFailed);
        System.out.println(s1);
        System.out.println(s2);
    }
}
Explanation: 1) Declare two boolean variables: isPassed = true and isFailed = false. 2) Call String.valueOf(isPassed) which returns the string "true" and store it in s1. 3) Call String.valueOf(isFailed) which returns the string "false" and store it in s2. 4) Print s1, which outputs true. 5) Print s2, which outputs false.
Q218.Easy
Write a Java program that converts two char values 'R' and 'K' into Strings using String.valueOf(char) and prints both resulting strings.
Show answer & explanation
Answer:
public class ValueOfCharDemo {
    public static void main(String[] args) {
        char c1 = 'R';
        char c2 = 'K';
        String s1 = String.valueOf(c1);
        String s2 = String.valueOf(c2);
        System.out.println(s1);
        System.out.println(s2);
    }
}
Explanation: 1) Declare char variables c1 = 'R' and c2 = 'K'. 2) String.valueOf(c1) uses the char overload and returns the String "R". 3) String.valueOf(c2) returns the String "K". 4) Print s1 and s2, so the output is R on the first line and K on the second line.
Q219.Easy
Write a Java program that converts a float value 7.25f and a double value 3.75 into their String forms using String.valueOf(float) and String.valueOf(double), then prints both strings.
Show answer & explanation
Answer:
public class ValueOfFloatDemo {
    public static void main(String[] args) {
        float price = 7.25f;
        double rate = 3.75;
        String s1 = String.valueOf(price);
        String s2 = String.valueOf(rate);
        System.out.println(s1);
        System.out.println(s2);
    }
}
Explanation: 1) Declare a float variable price = 7.25f and a double variable rate = 3.75. 2) Call String.valueOf(price) which uses the float overload and returns "7.25". 3) Call String.valueOf(rate) which uses the double overload and returns "3.75". 4) Store results in s1 and s2 and print them, giving output 7.25 then 3.75.
Q220.Easy
Write a Java program that demonstrates the use of String.valueOf() to convert various primitive types and an object into strings. Use the following values: boolean true, byte 21, short 22, int 23, long 24L, float 25.5f, double 26.5d, a char array {'I','n','d','i','a'}, and an instance of the class itself. Print each converted string on a new line.
Show answer & explanation
Answer:
public class StringValueOfDemo {
    public static void main(String[] args) {
        boolean b = true;
        byte by = 21;
        short sh = 22;
        int i = 23;
        long l = 24L;
        float f = 25.5f;
        double d = 26.5d;
        char[] chr = {'I','n','d','i','a'};
        StringValueOfDemo obj = new StringValueOfDemo();
        System.out.println(String.valueOf(b));
        System.out.println(String.valueOf(by));
        System.out.println(String.valueOf(sh));
        System.out.println(String.valueOf(i));
        System.out.println(String.valueOf(l));
        System.out.println(String.valueOf(f));
        System.out.println(String.valueOf(d));
        System.out.println(String.valueOf(chr));
        System.out.println(String.valueOf(obj));
    }
}
Explanation: 1. Declare variables of each primitive type with the given values. 2. Create a char array with the characters of "India". 3. Create an instance of the class. 4. Call String.valueOf() on each variable and print the result. 5. For the char array, String.valueOf(char[]) returns a string containing the characters. 6. For the object, String.valueOf(obj) calls obj.toString(), which returns a string like 'StringValueOfDemo@hashcode'.
Q221.Easy
Write a Java program that creates a file named "greeting.txt" and writes the text "Namaste India" to it using an OutputStreamWriter. Ensure the writer is closed properly.
Show answer & explanation
Answer:
import java.io.*;

public class FileWriterExample {
    public static void main(String[] args) {
        try {
            OutputStream outputStream = new FileOutputStream("greeting.txt");
            Writer writer = new OutputStreamWriter(outputStream);
            writer.write("Namaste India");
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Explanation: 1. Import java.io.* for file I/O classes. 2. Create a FileOutputStream for "greeting.txt". 3. Wrap it with OutputStreamWriter to write characters. 4. Use write() to output the string "Namaste India". 5. Close the writer to flush and release resources. 6. Catch and handle any exceptions.
Q222.Easy
Write a Java program that uses InputStreamReader to read characters from a file named "notes.txt" and print them to the console one character at a time. Handle any exceptions using a try-catch block.
Show answer & explanation
Answer:
import java.io.*;

public class ReaderDemo {
    public static void main(String[] args) {
        try {
            InputStream stream = new FileInputStream("notes.txt");
            Reader reader = new InputStreamReader(stream);
            int data = reader.read();
            while (data != -1) {
                System.out.print((char) data);
                data = reader.read();
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Explanation: 1. Open a FileInputStream on "notes.txt" to get raw bytes. 2. Wrap it in an InputStreamReader so bytes are decoded into characters. 3. Call read() once to get the first character as an int. 4. Loop while the value is not -1 (end of file), casting each int to char and printing it. 5. Call read() again each iteration to advance. 6. Close the reader and catch any IOException with a try-catch block.
Q223.Easy
Write a Java program to demonstrate that private members (variables and methods) are accessible only within the same class. Create a class 'Employee' with a private int variable 'salary' initialized to 50000 and a private method 'displaySalary' that prints the salary. Then, in another class 'PrivateAccessDemo', try to access these private members from the main method and observe the compile-time errors. Your program should include comments explaining the errors.
Show answer & explanation
Answer:
class Employee {
    private int salary = 50000;
    private void displaySalary() {
        System.out.println("Salary: " + salary);
    }
}

public class PrivateAccessDemo {
    public static void main(String[] args) {
        Employee emp = new Employee();
        // System.out.println(emp.salary); // Compile-time error: salary has private access in Employee
        // emp.displaySalary(); // Compile-time error: displaySalary() has private access in Employee
        System.out.println("Private members are not accessible from outside the class.");
    }
}
Explanation: 1. Class Employee declares 'salary' and 'displaySalary' as private, so they are only accessible within Employee. 2. In PrivateAccessDemo's main, attempting to access emp.salary or emp.displaySalary() causes compile-time errors because private members are not visible outside the class. 3. The erroneous lines are commented out, and a message is printed to illustrate the restriction. 4. This shows that private access modifier restricts visibility to the same class only.
Q224.Easy
Write a Java program that demonstrates the default (package-private) access modifier. Create a class Laptop in package electronics with a default method start() that prints "Laptop started". Then create a public class Shop in the same package electronics whose main method creates a Laptop object and calls start(). Explain in the program comments why this works only within the same package.
Show answer & explanation
Answer:
// File: electronics/Laptop.java
package electronics;

class Laptop {
    void start() {
        System.out.println("Laptop started");
    }
}

// File: electronics/Shop.java
package electronics;

public class Shop {
    public static void main(String[] args) {
        Laptop l = new Laptop();
        l.start();
    }
}
Explanation: 1) Laptop has no access modifier, so it is default (package-private). 2) start() also has no modifier, so it is default. 3) Shop is in the same package electronics, so it can create a Laptop and call start(). 4) If Shop were in another package, both Laptop and start() would be inaccessible. 5) Output: Laptop started.
Q225.Easy
Write a Java program to demonstrate the public access modifier. Create a class `Greeting` in package `mypack` with a public method `sayHello()` that prints "Hello from mypack". Then, in the default package, create a class `Main` that imports `mypack.Greeting`, creates an instance, and calls `sayHello()`.
Show answer & explanation
Answer:
// File: mypack/Greeting.java
package mypack;

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

// File: Main.java
import mypack.Greeting;

public class Main {
    public static void main(String[] args) {
        Greeting g = new Greeting();
        g.sayHello();
    }
}
Explanation: 1. The class `Greeting` is declared public in package `mypack`, so it can be accessed from any other package. 2. Its method `sayHello()` is also public, allowing it to be called from outside the package. 3. The `Main` class imports `mypack.Greeting`, creates an object, and calls `sayHello()`, which prints the message.
Q226.Easy
Write a Java program that demonstrates encapsulation: create a class 'Employee' with a single private field 'empName', a public getter getEmpName() and a public setter setEmpName(String empName). In a main method, set the name to "Ramesh" using the setter and print it using the getter.
Show answer & explanation
Answer:
public class Employee {
    // private data member
    private String empName;

    // getter method for empName
    public String getEmpName() {
        return empName;
    }

    // setter method for empName
    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public static void main(String[] args) {
        Employee e = new Employee();
        e.setEmpName("Ramesh");
        System.out.println(e.getEmpName());
    }
}
Explanation: 1. empName is private, so it is hidden from direct access (data hiding). 2. The public setter setEmpName() assigns the value using this.empName = empName. 3. The public getter getEmpName() returns the stored value. 4. main() sets the name to "Ramesh" and prints it, giving output: Ramesh.
Q227.Easy
Write a Java program that defines a read-only class named 'Library' which has only a private data member 'libraryName' initialised to "City Central Library" and only a getter method getLibraryName() to read it. Include a main method that creates a Library object and prints the library name.
Show answer & explanation
Answer:
public class Library {
    // private data member
    private String libraryName = "City Central Library";

    // only getter method (no setter) -> read-only class
    public String getLibraryName() {
        return libraryName;
    }

    public static void main(String[] args) {
        Library lib = new Library();
        System.out.println(lib.getLibraryName());
    }
}
Explanation: 1. The field libraryName is declared private, so it cannot be changed from outside the class. 2. Only a getter getLibraryName() is provided; there is no setter, so the value can be read but never modified -> read-only class. 3. main() creates a Library object and calls the getter. 4. Output: City Central Library.
Q228.Easy
Write a Java program that defines a write-only class named 'Employee' with a private field 'department' (String). The class should have only a setter method for department and no getter method. Include a main method to create an Employee object and set its department.
Show answer & explanation
Answer:
public class Employee {
    private String department;

    public void setDepartment(String department) {
        this.department = department;
    }

    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setDepartment("Finance");
        System.out.println("Department set successfully.");
    }
}
Explanation: 1. The Employee class has a private field 'department', so it cannot be accessed directly. 2. Only a public setter method setDepartment is provided, making it a write-only class (no getter). 3. The main method creates an Employee object and calls setDepartment to assign a value. 4. Since there is no getter, the value cannot be read from outside, but it is stored internally.
Q229.Easy
Write a Java program that demonstrates encapsulation using a class named 'Customer' with four private fields: customerId (long), fullName (String), email (String), and balance (float). Provide public getter and setter methods for each field. Also include a main method to test the class by creating an object, setting values, and printing them.
Show answer & explanation
Answer:
class Customer {
    private long customerId;
    private String fullName;
    private String email;
    private float balance;

    public long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(long customerId) {
        this.customerId = customerId;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public float getBalance() {
        return balance;
    }

    public void setBalance(float balance) {
        this.balance = balance;
    }
}

public class Main {
    public static void main(String[] args) {
        Customer cust = new Customer();
        cust.setCustomerId(1001L);
        cust.setFullName("Ramesh Kumar");
        cust.setEmail("ramesh@example.com");
        cust.setBalance(5000.0f);
        System.out.println("Customer ID: " + cust.getCustomerId());
        System.out.println("Name: " + cust.getFullName());
        System.out.println("Email: " + cust.getEmail());
        System.out.println("Balance: " + cust.getBalance());
    }
}
Explanation: 1. The Customer class has four private fields: customerId, fullName, email, and balance, so they cannot be accessed directly from outside the class. 2. For each field, a public getter (e.g., getCustomerId) and a public setter (e.g., setCustomerId) are provided. This is encapsulation: data is hidden and accessed only through methods. 3. The Main class creates a Customer object, uses setters to assign values, and uses getters to retrieve and print them. 4. This ensures controlled access and maintains data integrity.
Q230.Easy
Write a Java program that demonstrates multiple inheritance using interfaces. Define an interface Singer with method sing() and an interface Dancer with method dance(). Create a class Performer that implements both Singer and Dancer, where sing() prints "La La La" and dance() prints "Thumka". In main, create a Performer object and call both methods.
Show answer & explanation
Answer:
interface Singer {
    void sing();
}

interface Dancer {
    void dance();
}

class Performer implements Singer, Dancer {
    public void sing() {
        System.out.println("La La La");
    }

    public void dance() {
        System.out.println("Thumka");
    }

    public static void main(String[] args) {
        Performer obj = new Performer();
        obj.sing();
        obj.dance();
    }
}
Explanation: 1) Interface Singer declares sing(); interface Dancer declares dance(). 2) Class Performer implements both interfaces, so it inherits both method contracts (multiple inheritance of type). 3) Performer provides concrete sing() printing "La La La" and dance() printing "Thumka". 4) main creates a Performer object and calls sing() then dance(), producing the two output lines in order.
Q231.Easy
Write a Java program to demonstrate interface inheritance. Create an interface 'Readable' with a method 'read()'. Create another interface 'Writable' that extends 'Readable' and adds a method 'write()'. Then create a class 'Document' that implements 'Writable', providing implementations for both methods: 'read()' prints "Reading document" and 'write()' prints "Writing document". In the main method, create a 'Document' object and call both methods.
Show answer & explanation
Answer:
interface Readable {
    void read();
}

interface Writable extends Readable {
    void write();
}

class Document implements Writable {
    public void read() {
        System.out.println("Reading document");
    }
    public void write() {
        System.out.println("Writing document");
    }
}

public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        doc.read();
        doc.write();
    }
}
Explanation: 1. Define interface 'Readable' with method 'read()'. 2. Define interface 'Writable' that extends 'Readable' and adds method 'write()'. 3. Class 'Document' implements 'Writable', so it must implement both 'read()' and 'write()'. 4. In main, create a 'Document' object and call 'read()' which prints "Reading document". 5. Call 'write()' which prints "Writing document".
Q232.Easy
Write a Java program that demonstrates a static method in an interface. Define an interface 'Calculator' with a static method 'square' that returns the square of an integer, and an abstract method 'display()'. Create a class 'MyCalculator' that implements Calculator and provides implementation for display(). In the main method, call the static method using the interface name and also create an object of MyCalculator to call display().
Show answer & explanation
Answer:
interface Calculator {
    void display();
    static int square(int n) {
        return n * n;
    }
}

class MyCalculator implements Calculator {
    public void display() {
        System.out.println("MyCalculator display method");
    }
}

public class StaticInterfaceDemo {
    public static void main(String[] args) {
        int result = Calculator.square(7);
        System.out.println("Square of 7 is: " + result);
        MyCalculator mc = new MyCalculator();
        mc.display();
    }
}
Explanation: 1. Define interface Calculator with abstract method display() and static method square(int n) that returns n*n. 2. Class MyCalculator implements Calculator and provides implementation for display(). 3. In main, call static method using interface name: Calculator.square(7) and print result. 4. Create MyCalculator object and call display().
Q233.Easy
Write a Java program that declares two int variables a = 15 and b = 9, and uses a simple if statement to print "a + b is greater than 20" only when the sum of a and b is greater than 20.
Show answer & explanation
Answer:
public class Citizen {
public static void main(String[] args) {
int a = 15;
int b = 9;
if(a+b > 20) {
System.out.println("a + b is greater than 20");
}
}
}
Explanation: 1) Declare int a = 15 and int b = 9. 2) Compute a + b = 15 + 9 = 24. 3) The if condition checks 24 > 20, which is true. 4) Since the condition is true, the block executes and prints "a + b is greater than 20".
Q234.Easy
Write a Java program that demonstrates the use of a simple if statement. Declare an integer variable marks and set it to 75. If marks is greater than 60, print the message "Marks are above 60".
Show answer & explanation
Answer:
public class MarksExample {
    public static void main(String[] args) {
        int marks = 75;
        if (marks > 60) {
            System.out.print("Marks are above 60");
        }
    }
}
Explanation: 1. Create a class MarksExample with a main method. 2. Declare an int variable marks and assign 75. 3. Use if(marks > 60) to test the condition; 75 > 60 is true. 4. Since the condition is true, the block runs and prints "Marks are above 60". 5. If marks were 60 or less, the block would be skipped.
Q235.Easy
Write a Java program that uses an if-else statement to check whether a given integer is even or odd. Use the number 17 and print "even number" if it is even, otherwise print "odd number".
Show answer & explanation
Answer:
public class IfElseEvenOdd {
    public static void main(String[] args) {
        int number = 17;
        if (number % 2 == 0) {
            System.out.println("even number");
        } else {
            System.out.println("odd number");
        }
    }
}
Explanation: 1. Declare an integer variable number and assign 17. 2. Use an if statement to check if number % 2 == 0. 3. Since 17 % 2 equals 1, the condition is false, so the else block executes. 4. The else block prints "odd number".
Q236.Easy
Write a Java program that uses an if-else-if ladder to print a grade based on marks. Rules: marks below 40 -> "Fail"; 40 to 59 -> "Grade C"; 60 to 79 -> "Grade B"; 80 to 89 -> "Grade A"; 90 to 100 -> "Grade A+"; anything else -> "Invalid marks". Use marks = 72.
Show answer & explanation
Answer:
public class GradeLadder {
    public static void main(String[] args) {
        int marks = 72;
        if (marks < 40) {
            System.out.println("Fail");
        } else if (marks >= 40 && marks < 60) {
            System.out.println("Grade C");
        } else if (marks >= 60 && marks < 80) {
            System.out.println("Grade B");
        } else if (marks >= 80 && marks < 90) {
            System.out.println("Grade A");
        } else if (marks >= 90 && marks <= 100) {
            System.out.println("Grade A+");
        } else {
            System.out.println("Invalid marks");
        }
    }
}
Explanation: 1) Set marks = 72. 2) First condition marks < 40 is false (72 is not below 40). 3) Next marks >= 40 && marks < 60 is false (72 is not below 60). 4) Next marks >= 60 && marks < 80 is true (72 lies between 60 and 79), so this block runs. 5) The program prints: Grade B. Remaining else-if branches are skipped once a condition is true.
Q237.Easy
Write a Java program that demonstrates a nested if statement. A person is allowed to donate blood only if their age is at least 18 AND their weight is more than 45. Use an outer if on age and an inner if on weight. Use age = 22 and weight = 60, and print "Eligible to donate blood" when both conditions hold.
Show answer & explanation
Answer:
public class BloodDonationCheck {
    public static void main(String[] args) {
        int age = 22;
        int weight = 60;
        if (age >= 18) {
            if (weight > 45) {
                System.out.println("Eligible to donate blood");
            }
        }
    }
}
Explanation: 1) Declare age = 22 and weight = 60. 2) Outer if checks age >= 18: 22 >= 18 is true, so control enters the outer block. 3) Inner if checks weight > 45: 60 > 45 is true, so the inner block runs. 4) The program prints: Eligible to donate blood. 5) If either condition were false, nothing would be printed (nested if has no else here).
Q238.Easy
Write a Java program that defines a member inner class (a non-static class declared inside another class but outside any method). Create an outer class named 'Library' with a method 'display()' that prints 'Welcome to the Library'. Inside Library, define a member inner class 'Book' with a method 'show()' that prints 'Book: Java Programming'. In the main method, create an instance of Library, then create an instance of the inner class using the outer instance, and call both display() and show().
Show answer & explanation
Answer:
class Library {
    void display() {
        System.out.println("Welcome to the Library");
    }

    class Book {
        void show() {
            System.out.println("Book: Java Programming");
        }
    }

    public static void main(String[] args) {
        Library lib = new Library();
        lib.display();
        Library.Book b = lib.new Book();
        b.show();
    }
}
Explanation: 1. Define outer class Library with method display() that prints a welcome message. 2. Inside Library, define non-static inner class Book with method show() that prints book details. 3. In main, create Library object lib. 4. Call lib.display() to print welcome message. 5. Create inner class object using lib.new Book(). 6. Call b.show() to print book details.
Q239.Easy
Write a Java program named NameCompareDemo.java that demonstrates the String compareTo() method. Create the following strings: a1 = "tiger", a2 = "tiger", a3 = "zebra", a4 = "tiler", a5 = "apple". Print the result of a1.compareTo(a2), a1.compareTo(a3), a1.compareTo(a4) and a1.compareTo(a5), each on its own line.
Show answer & explanation
Answer:
public class NameCompareDemo {
    public static void main(String args[]) {
        String a1 = "tiger";
        String a2 = "tiger";
        String a3 = "zebra";
        String a4 = "tiler";
        String a5 = "apple";
        System.out.println(a1.compareTo(a2)); // 0, both equal
        System.out.println(a1.compareTo(a3)); // 't' - 'z' = 116 - 122 = -6
        System.out.println(a1.compareTo(a4)); // 'g' - 'l' = 103 - 108 = -5
        System.out.println(a1.compareTo(a5)); // 't' - 'a' = 116 - 97 = 19
    }
}
Explanation: 1) compareTo() compares characters position by position and returns the difference of the first unequal pair; if all compared characters match it returns the length difference. 2) a1 vs a2: both "tiger", so result is 0. 3) a1 vs a3: first char 't'(116) vs 'z'(122) differ, so 116-122 = -6. 4) a1 vs a4: 't'='t', 'i'='i', then 'g'(103) vs 'l'(108), so 103-108 = -5. 5) a1 vs a5: first char 't'(116) vs 'a'(97), so 116-97 = 19. 6) The program prints 0, -6, -5, 19 on separate lines.
Q240.Easy
Write a Java program that demonstrates the use of the compareTo() method of the String class. The compareTo() method compares two strings lexicographically and returns an integer: 0 if the strings are equal, a positive value if the first string is greater, and a negative value if the first string is smaller. In your program, create three strings: s1 = "Rahul", s2 = "Rahul", and s3 = "Amit". Then print the results of s1.compareTo(s2), s1.compareTo(s3), and s3.compareTo(s1).
Show answer & explanation
Answer:
public class StringCompareToDemo {
    public static void main(String[] args) {
        String s1 = "Rahul";
        String s2 = "Rahul";
        String s3 = "Amit";
        System.out.println(s1.compareTo(s2)); // 0
        System.out.println(s1.compareTo(s3)); // positive
        System.out.println(s3.compareTo(s1)); // negative
    }
}
Explanation: 1) Define a class StringCompareToDemo with a main method. 2) Create three String variables: s1 = "Rahul", s2 = "Rahul", s3 = "Amit". 3) s1.compareTo(s2) returns 0 because both strings are identical. 4) s1.compareTo(s3) compares 'R' (82) with 'A' (65); difference is 17, so it returns 17 (positive). 5) s3.compareTo(s1) compares 'A' (65) with 'R' (82); difference is -17, so it returns -17 (negative). 6) Print each result on a new line.
Q241.Easy
Write a Java program that shows what happens without exception handling. In the main method, compute int result = 100/0; and then print "rest of the code". Name the class NoHandlerDemo.
Show answer & explanation
Answer:
public class NoHandlerDemo {

    public static void main(String[] args) {

        int result = 100/0; // may throw ArithmeticException

        System.out.println("rest of the code");
    }
}
Explanation: 1. The class NoHandlerDemo has a main method. 2. The statement int result = 100/0; performs integer division by zero. 3. Java throws an ArithmeticException at runtime because there is no try-catch. 4. The program terminates abnormally, so "rest of the code" is never printed. 5. This demonstrates the problem of not handling exceptions.
Q242.Easy
Write a Java program that divides 80 by 0 inside a try block, catches the ArithmeticException and prints the exception object, then after the try-catch prints "rest of the code". Name the class DivideCatchDemo.
Show answer & explanation
Answer:
public class DivideCatchDemo {

    public static void main(String[] args) {
        try {
            int data = 80 / 0; // may throw exception
        }
        // handling the exception
        catch (ArithmeticException e) {
            System.out.println(e);
        }
        System.out.println("rest of the code");
    }
}
Explanation: 1) The class DivideCatchDemo has a main method. 2) Inside try, 80/0 causes an ArithmeticException (divide by zero). 3) Control jumps to the catch block for ArithmeticException, which prints the exception, e.g. java.lang.ArithmeticException: / by zero. 4) After the try-catch, the statement prints "rest of the code". 5) Because the exception was handled, the program does not crash and continues normally.
Q243.Easy
Write a Java program that keeps a division inside a try block where no exception occurs (use 100/5), prints "rest of the code" after the division, and includes a catch block for ArithmeticException that prints the exception. Name the class SafeTryDemo.
Show answer & explanation
Answer:
public class SafeTryDemo {

    public static void main(String[] args) {
        try {
            int result = 100 / 5; // no exception here
            System.out.println("rest of the code");
        }
        // handling the exception (will not run here)
        catch (ArithmeticException e) {
            System.out.println(e);
        }
    }
}
Explanation: 1) The class SafeTryDemo has a main method. 2) Inside try, 100/5 = 20 is computed; since divisor is not zero, no exception is thrown. 3) So the next statement prints "rest of the code". 4) The catch block for ArithmeticException is present but never executes because no exception occurred. 5) Program ends normally with output: rest of the code.
Q244.Easy
Write a Java program that tries to divide 96 by 0 inside a try block, catches the exception using the parent Exception class and prints the exception object, then prints "rest of the code". Name the class ParentCatchDemo.
Show answer & explanation
Answer:
public class ParentCatchDemo {
    public static void main(String[] args) {
        try {
            int value = 96 / 0; // may throw exception
        }
        catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("rest of the code");
    }
}
Explanation: 1) The class ParentCatchDemo has the main method. 2) The try block computes 96/0, which throws an ArithmeticException. 3) The catch block catches it using the parent class Exception and prints the exception object, e.g. java.lang.ArithmeticException: / by zero. 4) After the try-catch, execution continues and prints "rest of the code". 5) Because the exception is handled, the program does not terminate abnormally.
Q245.Easy
Write a Java program that attempts to divide 84 by 0 inside a try block, catches the exception, and prints the custom message "Cannot divide by zero". Name the class CustomMessageDemo.
Show answer & explanation
Answer:
public class CustomMessageDemo {
    public static void main(String[] args) {
        try {
            int result = 84 / 0; // may throw exception
        }
        catch (Exception e) {
            // display the custom message
            System.out.println("Cannot divide by zero");
        }
    }
}
Explanation: 1) The class CustomMessageDemo contains the main method. 2) Inside the try block, 84/0 causes an ArithmeticException. 3) Control jumps to the catch block that catches Exception e. 4) The catch block prints the custom message "Cannot divide by zero". 5) The program ends normally without crashing.
Q246.Easy
Write a Java program that stores i = 80 and j = 0. In a try block compute data = i / j (which throws an exception). In the catch block, resolve the situation by printing i / (j + 4). Name the class ResolveInCatch.
Show answer & explanation
Answer:
public class ResolveInCatch {
    public static void main(String[] args) {
        int i = 80;
        int j = 0;
        int data;
        try {
            data = i / j; // may throw ArithmeticException
        } catch (Exception e) {
            // resolving the exception in the catch block
            System.out.println(i / (j + 4));
        }
    }
}
Explanation: 1) i = 80 and j = 0, so i / j in the try block throws an ArithmeticException (division by zero). 2) The catch block catches this exception. 3) Inside the catch block, j + 4 = 0 + 4 = 4, so i / (j + 4) = 80 / 4 = 20. 4) The program prints 20 and terminates normally.
Q247.Easy
Write a Java program that stores the marks {12, 24, 36, 48} in an int array, tries to print the element at index 9 (which does not exist), catches the resulting ArrayIndexOutOfBoundsException and prints the exception object, then prints "remaining code runs" after the try-catch block.
Show answer & explanation
Answer:
public class MarksArrayDemo {
    public static void main(String[] args) {
        try {
            int marks[] = {12, 24, 36, 48};
            System.out.println(marks[9]); // may throw exception
        }
        // handling the array exception
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
        }
        System.out.println("remaining code runs");
    }
}
Explanation: 1) The array marks has 4 elements, so valid indices are 0 to 3. 2) Accessing marks[9] is out of range, so Java throws ArrayIndexOutOfBoundsException at runtime. 3) The catch block catches exactly that exception type and prints the exception object (e.g. java.lang.ArrayIndexOutOfBoundsException: Index 9 out of bounds for length 4). 4) Because the exception is handled, the program does not crash and continues. 5) The final println prints "remaining code runs".
Q248.Easy
Write a Java program that uses StringReader to read the string "Namaste India!!\nWelcome to Bharat." character by character and print each character to the console until the end of the stream.
Show answer & explanation
Answer:
import java.io.StringReader;

public class StringReaderDemo {
    public static void main(String[] args) throws Exception {
        String text = "Namaste India!!\nWelcome to Bharat.";
        StringReader reader = new StringReader(text);
        int k = 0;
        while ((k = reader.read()) != -1) {
            System.out.print((char) k);
        }
    }
}
Explanation: 1. Create a StringReader wrapping the string "Namaste India!!\nWelcome to Bharat.". 2. Call reader.read() in a while loop; it returns the next character as an int, or -1 at end of string. 3. Cast each returned int to char and print it with System.out.print so the text appears exactly as stored. 4. The loop stops when read() returns -1, i.e., after the last character '.'.
Q249.Easy
Write a Java program that creates a File object for the directory "C:/Users/priya/Documents", lists all files in it using listFiles(), and for each file prints its name, whether it can be written (canWrite()), whether it is hidden (isHidden()), and its length in bytes.
Show answer & explanation
Answer:
import java.io.*;
public class DirListing {
    public static void main(String[] args) {
        File dir = new File("C:/Users/priya/Documents");
        File files[] = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                System.out.println(file.getName() + " Can Write: " + file.canWrite()
                    + " Is Hidden: " + file.isHidden() + " Length: " + file.length() + " bytes");
            }
        }
    }
}
Explanation: 1. A File object is created pointing to the directory path. 2. listFiles() returns an array of File objects for the entries in the directory (null if it is not a directory or an I/O error occurs). 3. A null check avoids a NullPointerException. 4. For each entry, getName() gives the file name, canWrite() tells if it is writable, isHidden() tells if it is hidden, and length() gives the size in bytes. 5. All four values are printed for every file in the directory.
Q250.Easy
Write a Java program that uses the Scanner class to read a single line of input from the user. Prompt the user with 'Enter your city: ', read the full line using in.nextLine(), and then print 'City is: ' followed by the entered city. FileName: CityScanner.java
Show answer & explanation
Answer:
import java.util.*;
public class CityScanner {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter your city: ");
        String city = in.nextLine();
        System.out.println("City is: " + city);
        in.close();
    }
}
Explanation: 1. Import java.util.* to use the Scanner class. 2. Create a Scanner object 'in' that reads from System.in (keyboard). 3. Print the prompt 'Enter your city: ' using System.out.print so input appears on the same line. 4. in.nextLine() reads the entire line typed by the user (including spaces) and stores it in the String variable city. 5. Print 'City is: ' concatenated with city, then close the scanner with in.close().
Q251.Easy
Write a Java program that declares an int array of size 4, instantiates it, initializes its elements to 15, 25, 35 and 45, and then traverses the array using a for loop with the array's length property, printing each element on a new line.
Show answer & explanation
Answer:
public class ArrayDemo {
    public static void main(String[] args) {
        int a[] = new int[4];
        a[0] = 15;
        a[1] = 25;
        a[2] = 35;
        a[3] = 45;
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
Explanation: 1. Declare and instantiate an int array a of size 4 using new int[4]; all elements start as 0. 2. Initialize a[0]=15, a[1]=25, a[2]=35, a[3]=45. 3. Use a for loop from i=0 while i < a.length (length is a property of the array, here 4). 4. Print a[i] each iteration, so the output is 15, 25, 35, 45 each on its own line.
Q252.Easy
Write a Java program that creates an int array holding the marks {7, 8, 9}, obtains the Class object of that array using getClass(), and prints the name of the array's class (the proxy class name) using getName().
Show answer & explanation
Answer:
public class ArrayClassName {
    public static void main(String[] args) {
        int marks[] = {7, 8, 9};
        Class c = marks.getClass();
        String name = c.getName();
        System.out.println(name);
    }
}
Explanation: 1. Declare and initialize an int array marks with values 7, 8, 9. 2. Call marks.getClass() to get the Class object of the array; Java creates a proxy class for the array object. 3. Call getName() on that Class object to get the class name as a String. 4. Print the name; for an int array the output is [I (the JVM signature for int array).
Q253.Easy
Write a Java program that declares a source char array containing the characters of the word 'placement' (i.e. {'p','l','a','c','e','m','e','n','t'}), declares a destination char array of length 5, copies 5 characters starting from index 2 of the source array into the destination array starting at index 0 using System.arraycopy(), and then prints the destination array as a string.
Show answer & explanation
Answer:
public class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] source = {'p', 'l', 'a', 'c', 'e', 'm', 'e', 'n', 't'};
        char[] destination = new char[5];

        System.arraycopy(source, 2, destination, 0, 5);

        System.out.println(String.valueOf(destination));
    }
}
Explanation: 1. Declare the source char array with the 9 characters of 'placement'. 2. Declare a destination char array of length 5. 3. Call System.arraycopy(source, 2, destination, 0, 5): start reading source at index 2 ('a'), write into destination from index 0, copying 5 characters. 4. The copied characters are source[2..6] = 'a','c','e','m','e'. 5. String.valueOf(destination) converts the char array to a string, so the program prints: acem e (i.e. 'aceme').
Q254.Easy
Write a Java program that creates an int array named marks with the values {21, 14, 7, 9}, prints the original array elements, then creates a clone of the array using the clone() method, prints the cloned array elements, and finally prints whether the original array and the cloned array are the same object (using ==).
Show answer & explanation
Answer:
public class ArrayCloneDemo {
    public static void main(String[] args) {
        int marks[] = {21, 14, 7, 9};

        System.out.println("Original array:");
        for (int m : marks) {
            System.out.println(m);
        }

        int clonedMarks[] = marks.clone();

        System.out.println("Cloned array:");
        for (int m : clonedMarks) {
            System.out.println(m);
        }

        System.out.println("Are both references equal?");
        System.out.println(marks == clonedMarks);
    }
}
Explanation: 1. Declare and initialize the int array marks with {21, 14, 7, 9}. 2. Use an enhanced for loop to print each element of the original array. 3. Call marks.clone() to create a new array clonedMarks; for a one-dimensional array this copies the actual values (deep copy of elements). 4. Print each element of clonedMarks with another enhanced for loop. 5. Compare marks == clonedMarks: clone() returns a new array object, so the references differ and the program prints false.
Q255.Easy
Write a Java program to add two 2×3 matrices and print the resulting matrix. Use matrix A = {{2, 5, 7}, {1, 6, 8}} and matrix B = {{3, 4, 2}, {5, 2, 9}}.
Show answer & explanation
Answer:
public class MatrixAdd {
    public static void main(String[] args) {
        int a[][] = {{2, 5, 7}, {1, 6, 8}};
        int b[][] = {{3, 4, 2}, {5, 2, 9}};
        int c[][] = new int[2][3];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 3; j++) {
                c[i][j] = a[i][j] + b[i][j];
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Explanation: 1) Declare two 2×3 matrices a and b and a result matrix c of size 2×3. 2) Loop i over the 2 rows and j over the 3 columns. 3) Add corresponding elements: c[i][j] = a[i][j] + b[i][j]. 4) Row 0: 2+3=5, 5+4=9, 7+2=9. 5) Row 1: 1+5=6, 6+2=8, 8+9=17. 6) Print each row followed by a newline, giving: 5 9 9 6 8 17
Q256.Easy
Write a Java program that declares, instantiates, and initializes an integer array in a single line with the values 5, 10, 15, 20. Then, use a for loop to print each element of the array on a new line.
Show answer & explanation
Answer:
public class ArrayInitDemo {
    public static void main(String[] args) {
        int[] arr = {5, 10, 15, 20};
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
Explanation: 1. Define a class ArrayInitDemo with a main method. 2. Declare and initialize an integer array arr with values 5, 10, 15, 20 in a single line. 3. Use a for loop: for (int i = 0; i < arr.length; i++) to iterate over the array indices. 4. Inside the loop, print the element at index i using System.out.println(arr[i]). 5. The loop runs from index 0 to arr.length-1, printing each element on a new line.
Q257.Easy
Write a Java program that uses a for-each loop to print all elements of an integer array. The array should contain the values 10, 20, 30, 40, 50. Use the for-each loop syntax to iterate and print each element on a new line.
Show answer & explanation
Answer:
public class ForEachDemo {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}
Explanation: 1. Define a class ForEachDemo with a main method. 2. Declare and initialize an integer array numbers with values 10, 20, 30, 40, 50. 3. Use a for-each loop: for (int num : numbers) to iterate over each element. 4. Inside the loop, print the current element using System.out.println(num). 5. The loop automatically iterates through all elements, printing each on a new line.
Q258.Easy
Write a Java program that uses a for-each loop to print all elements of an integer array containing the values 5, 10, 15, 20, 25.
Show answer & explanation
Answer:
public class ForEachDemo {
    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}
Explanation: 1. Declare and initialize an integer array 'numbers' with values 5, 10, 15, 20, 25. 2. Use a for-each loop: for (int num : numbers). This iterates over each element of the array. 3. Inside the loop, print the current element 'num'. 4. The loop automatically goes through all elements without needing an index. 5. The output will be each number on a new line.
Q259.Easy
Write a Java program that passes an int array to a method and prints the smallest element of that array. In main, declare and initialize the array with the values 48, 12, 27, 9, 33 and pass it to the method.
Show answer & explanation
Answer:
public class MinArrayDemo {
    static void findMin(int[] arr) {
        int min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (min > arr[i]) {
                min = arr[i];
            }
        }
        System.out.println(min);
    }

    public static void main(String[] args) {
        int[] a = {48, 12, 27, 9, 33};
        findMin(a);
    }
}
Explanation: 1) Define a static method findMin(int[] arr) that starts with min = arr[0] = 48. 2) Loop i from 1 to arr.length-1, comparing each element with min and updating min when a smaller value is found: 12 < 48 so min=12; 27 not smaller; 9 < 12 so min=9; 33 not smaller. 3) After the loop min = 9, which is printed. 4) In main, the array {48,12,27,9,33} is created and passed to findMin, so the same method logic works on any array passed to it.
Q260.Easy
Write a Java program that demonstrates passing an anonymous array to a method. Create a method that receives an int array and prints each element on its own line, then call it from main by passing an anonymous array containing the values 7, 14, 21, 28, 35.
Show answer & explanation
Answer:
public class AnonymousArrayDemo {
    static void showArray(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
        }
    }

    public static void main(String[] args) {
        showArray(new int[]{7, 14, 21, 28, 35});
    }
}
Explanation: 1) Define a static method showArray(int[] nums) that loops from index 0 to nums.length-1 and prints each element with println. 2) In main, call showArray and pass an anonymous array new int[]{7,14,21,28,35} directly, without storing it in a named variable. 3) The method receives the array reference and prints 7, 14, 21, 28, 35 each on a new line. 4) Because the array has no name in main, it is an anonymous array; it is created and passed in the same expression.
Q261.Easy
Write a Java program that defines a method named getNumbers() which returns an integer array containing the values {5, 15, 25, 35, 45}. In the main method, call this method, store the returned array in a variable, and then print each element of the array using a for loop.
Show answer & explanation
Answer:
public class ReturnArrayDemo {
    static int[] getNumbers() {
        return new int[]{5, 15, 25, 35, 45};
    }

    public static void main(String[] args) {
        int[] arr = getNumbers();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
Explanation: 1. Define a static method getNumbers() that returns an int array. It creates and returns a new array with elements {5, 15, 25, 35, 45}. 2. In main, call getNumbers() and assign the returned array to int[] arr. 3. Use a for loop with index i from 0 to arr.length-1 (i < arr.length). 4. In each iteration, print arr[i]. 5. The output will be each number on a new line: 5, 15, 25, 35, 45.
Q262.Easy
Write a Java program that declares and initializes a 2D array with the values {{3,5,7},{1,6,9},{8,2,4}}, then prints the array in matrix form (each row on its own line, values separated by a space).
Show answer & explanation
Answer:
public class MatrixPrint {
    public static void main(String[] args) {
        int[][] mat = {{3,5,7},{1,6,9},{8,2,4}};
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(mat[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Explanation: 1) int[][] mat = {{3,5,7},{1,6,9},{8,2,4}}; declares, instantiates and initializes a 3x3 array in one statement. 2) The outer loop i runs over the 3 rows (0,1,2). 3) The inner loop j runs over the 3 columns of each row and prints mat[i][j] followed by a space. 4) After each row, System.out.println() moves to a new line. 5) Output is: 3 5 7 1 6 9 8 2 4
Q263.Easy
Write a Java program that creates a jagged (ragged) 2D array with 3 rows, where row 0 has 2 columns, row 1 has 5 columns and row 2 has 3 columns. Fill the array with consecutive integers starting from 0 (row by row) and then print it row by row, with a space between values and a new line after each row.
Show answer & explanation
Answer:
public class JaggedDemo {
    public static void main(String[] args) {
        int[][] grid = new int[3][];
        grid[0] = new int[2];
        grid[1] = new int[5];
        grid[2] = new int[3];

        int value = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                grid[i][j] = value++;
            }
        }

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Explanation: 1) Declare int[][] grid = new int[3][]; so only the number of rows is fixed. 2) Give each row its own length: row 0 -> 2, row 1 -> 5, row 2 -> 3, making it jagged. 3) Use a counter value starting at 0; nested loops over each row's own length assign grid[i][j] = value++. 4) Fill order: row 0 gets 0 1; row 1 gets 2 3 4 5 6; row 2 gets 7 8 9. 5) Print with nested loops using grid[i].length so each row prints only its own columns, then println() moves to the next line.
Q264.Easy
Write a Java program that generates a NullPointerException but does NOT provide a catch block specifically for NullPointerException. Inside a try block, declare a String variable set to null and print its length. Provide catch blocks for ArithmeticException (printing "Arithmetic Exception occurs") and ArrayIndexOutOfBoundsException (printing "ArrayIndexOutOfBounds Exception occurs"), followed by a catch block for Exception (printing "Parent Exception occurs"). After the try-catch, print "rest of the code".
Show answer & explanation
Answer:
public class MultipleCatchParentDemo {
    public static void main(String[] args) {
        try {
            String s = null;
            System.out.println(s.length());
        }
        catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");
        }
        catch (Exception e) {
            System.out.println("Parent Exception occurs");
        }
        System.out.println("rest of the code");
    }
}
Explanation: 1. The try block sets String s = null and calls s.length(), which throws a NullPointerException. 2. The JVM checks the catch blocks in order: ArithmeticException does not match, ArrayIndexOutOfBoundsException does not match. 3. The catch(Exception e) block matches because NullPointerException is a subclass of Exception (the parent class). 4. So "Parent Exception occurs" is printed. 5. Control then continues after the try-catch, printing "rest of the code".
Q265.Easy
Write a Java program that opens a file named "greeting.txt" (located in the current working directory) using FileInputStream, reads only the first character from the file, prints that character to the console, and then closes the stream. Handle any exception by printing the exception message.
Show answer & explanation
Answer:
import java.io.FileInputStream;

public class ReadOneChar {
    public static void main(String[] args) {
        try {
            FileInputStream fin = new FileInputStream("greeting.txt");
            int ch = fin.read();
            System.out.print((char) ch);
            fin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Explanation: 1. Import java.io.FileInputStream. 2. Open the file "greeting.txt" by creating new FileInputStream("greeting.txt") inside a try block. 3. Call fin.read() once; it returns the first byte as an int (or -1 if the file is empty). 4. Cast the returned int to char and print it with System.out.print. 5. Close the stream using fin.close(). 6. Catch any Exception and print it to report errors such as a missing file.
Q266.Easy
Write a Java program that opens a file named "notes.txt" (located in the current working directory) using FileInputStream and prints every character of the file to the console until the end of the file is reached. Handle any exception by printing the exception message.
Show answer & explanation
Answer:
import java.io.FileInputStream;

public class ReadAllChars {
    public static void main(String[] args) {
        try {
            FileInputStream fin = new FileInputStream("notes.txt");
            int ch = 0;
            while ((ch = fin.read()) != -1) {
                System.out.print((char) ch);
            }
            fin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Explanation: 1. Import java.io.FileInputStream. 2. Create a FileInputStream object on the file "notes.txt" inside a try block. 3. Declare an int variable ch and loop while (ch = fin.read()) != -1; read() returns the next byte as int, or -1 at end of file. 4. Inside the loop cast each byte to char and print it with System.out.print so characters appear continuously. 5. After the loop close the stream with fin.close(). 6. Catch any Exception and print it so file-not-found or IO errors are reported.
Q267.Easy
Write a Java program that demonstrates a local inner class. Create an outer class named Shop with a private instance variable price = 250. In a method bill(), define a local inner class Receipt with a method show() that prints the price, then create an object of Receipt and call show(). The main method should create a Shop object and invoke bill().
Show answer & explanation
Answer:
public class Shop {
    private int price = 250;

    void bill() {
        class Receipt {
            void show() {
                System.out.println(price);
            }
        }
        Receipt r = new Receipt();
        r.show();
    }

    public static void main(String[] args) {
        Shop s = new Shop();
        s.bill();
    }
}
Explanation: 1. Shop declares a private instance variable price = 250. 2. The method bill() defines a local inner class Receipt inside it. 3. Receipt's show() method prints the outer class's price (accessible because the local inner class can access outer members). 4. bill() creates a Receipt object and calls show(), printing 250. 5. main() creates a Shop and calls bill(), so the program outputs 250.
Q268.Easy
Write a Java program that demonstrates the difference between the == operator and the equals() method for String objects. The == operator compares references, not the actual string contents. In your program, create three strings: s1 = "Priya", s2 = "Priya", and s3 = new String("Priya"). Then print the results of s1 == s2 and s1 == s3.
Show answer & explanation
Answer:
public class StringEqualityDemo {
    public static void main(String[] args) {
        String s1 = "Priya";
        String s2 = "Priya";
        String s3 = new String("Priya");
        System.out.println(s1 == s2); // true
        System.out.println(s1 == s3); // false
    }
}
Explanation: 1) Define a class StringEqualityDemo with a main method. 2) Create s1 = "Priya" and s2 = "Priya". Both are string literals, so they refer to the same object in the string pool. 3) Create s3 = new String("Priya"). This creates a new String object in heap memory, separate from the pool. 4) s1 == s2 compares references; since both point to the same pooled object, it prints true. 5) s1 == s3 compares references; s1 points to the pooled object, s3 points to a new object, so it prints false.
Q269.Easy
Write a Java program to show that String is immutable when using concat(). Start with s1 = "java string". Call s1.concat("is immutable") without assigning the result and print s1. Then assign s1 = s1.concat(" is immutable so assign it explicitly") and print s1 again. Name the class ImmutableDemo.
Show answer & explanation
Answer:
public class ImmutableDemo {
    public static void main(String args[]) {
        String s1 = "java string";
        // concat() returns a new String; s1 itself does not change (immutable)
        s1.concat("is immutable");
        System.out.println(s1);
        s1 = s1.concat(" is immutable so assign it explicitly");
        System.out.println(s1);
    }
}
Explanation: 1) s1 is created as "java string". 2) s1.concat("is immutable") creates a new String "java stringis immutable" but the result is not stored, so s1 still refers to "java string". 3) Printing s1 gives: java string. 4) s1 = s1.concat(" is immutable so assign it explicitly") stores the new string back into s1. 5) Printing s1 gives: java string is immutable so assign it explicitly. 6) This shows String is immutable: concat() never modifies the original object, so explicit assignment is required.
Q270.Easy
Write a Java program that concatenates strings using chained concat() calls. Declare str1 = "Namaste", str2 = "Bharat", str3 = "Mitra". Build str4 by chaining concat() to join str1, a space, str2, a space and str3. Then build str5 = str1.concat("!!!") and str6 = str1.concat("@").concat(str2). Print str4, str5 and str6 each on its own line. Name the class ConcatChain.
Show answer & explanation
Answer:
public class ConcatChain {
    public static void main(String[] args) {
        String str1 = "Namaste";
        String str2 = "Bharat";
        String str3 = "Mitra";
        String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
        System.out.println(str4);
        String str5 = str1.concat("!!!");
        System.out.println(str5);
        String str6 = str1.concat("@").concat(str2);
        System.out.println(str6);
    }
}
Explanation: 1) Each concat() call returns a new String, so calls can be chained left to right. 2) str1.concat(" ") gives "Namaste ", then .concat(str2) gives "Namaste Bharat", then .concat(" ") gives "Namaste Bharat ", then .concat(str3) gives "Namaste Bharat Mitra" -> printed as str4. 3) str1.concat("!!!") gives "Namaste!!!" -> printed as str5. 4) str1.concat("@") gives "Namaste@", then .concat(str2) gives "Namaste@Bharat" -> printed as str6.
Q271.Easy
Write a Java program that directly creates a thread using the Thread class constructor Thread(String name) with the name "Report thread", starts it, and then prints the thread's name obtained via getName().
Show answer & explanation
Answer:
public class ReportThread
{
    public static void main(String[] args)
    {
        Thread t = new Thread("Report thread");
        t.start();
        String str = t.getName();
        System.out.println(str);
    }
}
Explanation: 1) new Thread("Report thread") uses the Thread(String name) constructor, setting the thread's name. 2) t.start() moves the thread to the active state (its default run() does nothing extra). 3) t.getName() returns "Report thread". 4) System.out.println(str) prints the name.
Q272.Easy
Write a Java program that creates a class named TaskRunner implementing Runnable. In its run() method it should print "Task is now executing ...". In main, create a Runnable object, wrap it in a Thread using the constructor Thread(Runnable r, String name) with the name "Payment thread", start the thread, then print the thread's name using getName().
Show answer & explanation
Answer:
public class TaskRunner implements Runnable
{
    public void run()
    {
        System.out.println("Task is now executing ...");
    }

    public static void main(String[] args)
    {
        Runnable r1 = new TaskRunner();
        Thread th1 = new Thread(r1, "Payment thread");
        th1.start();
        String str = th1.getName();
        System.out.println(str);
    }
}
Explanation: 1) TaskRunner implements Runnable and overrides run() to print the message. 2) In main, a Runnable object r1 is created from TaskRunner. 3) new Thread(r1, "Payment thread") uses the Thread(Runnable, String) constructor, so the thread's name is set to "Payment thread". 4) th1.start() begins execution; run() prints "Task is now executing ...". 5) th1.getName() returns "Payment thread", which is printed.
Q273.Easy
Write a Java program that prints the message "Welcome to Java Programming" to the console. Save the program in a file named Welcome.java.
Show answer & explanation
Answer:
public class Welcome {
    public static void main(String[] args) {
        System.out.println("Welcome to Java Programming");
    }
}
Explanation: 1. The public class name must match the file name, so the class is Welcome and the file is Welcome.java. 2. The main method signature is public static void main(String[] args), which is the program's entry point. 3. System.out.println(...) writes the string to standard output and moves to a new line. 4. The message is enclosed in double quotes: "Welcome to Java Programming". 5. Compile with javac Welcome.java and run with java Welcome.
Q274.Easy
Write a Java program that prints the message "Namaste Bharat" to the console. Save the program in a file named Greet.java.
Show answer & explanation
Answer:
public class Greet {
    public static void main(String[] args) {
        System.out.println("Namaste Bharat");
    }
}
Explanation: 1. The class name must match the file name, so the class is named Greet and saved as Greet.java. 2. The entry point is public static void main(String[] args). 3. System.out.println(...) prints the given text followed by a new line. 4. The text "Namaste Bharat" is placed inside double quotes as a string literal. 5. Compile with javac Greet.java and run with java Greet to see the output.
Q275.Easy
Write a Java program that writes text into a file using BufferedOutputStream connected to a FileOutputStream. Create a FileOutputStream for the file "output.txt", wrap it in a BufferedOutputStream, write the string "Hello Mumbai learners." as bytes, then flush, close the buffered stream, close the file stream, and finally print "done".
Show answer & explanation
Answer:
import java.io.*;

public class BufferedOutputDemo {
    public static void main(String[] args) throws Exception {
        FileOutputStream fout = new FileOutputStream("output.txt");
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        String s = "Hello Mumbai learners.";
        byte b[] = s.getBytes();
        bout.write(b);
        bout.flush();
        bout.close();
        fout.close();
        System.out.println("done");
    }
}
Explanation: 1. FileOutputStream opens (or creates) the file output.txt for writing bytes. 2. BufferedOutputStream wraps the file stream so writes are buffered in memory for efficiency. 3. The string is converted to bytes with getBytes() and written via bout.write(b). 4. flush() forces any buffered bytes into the underlying FileOutputStream so the data reaches the file. 5. close() is called on both streams to release resources, and "done" is printed.
Q276.Easy
Write a Java program that stores the string "Welcome Bharat readers" in a String. Use the contains() method to check for "Bharat" and print the boolean result. Then check for "bharat" (lowercase) and print that boolean result too, to show that contains() is case-sensitive. Name the file CaseCheck.java.
Show answer & explanation
Answer:
public class CaseCheck {
    public static void main(String[] args) {
        String str = "Welcome Bharat readers";
        boolean isContains = str.contains("Bharat");
        System.out.println(isContains);
        // Case Sensitive
        System.out.println(str.contains("bharat")); // false
    }
}
Explanation: 1) Create a class CaseCheck with a main method. 2) Store "Welcome Bharat readers" in a String variable str. 3) str.contains("Bharat") finds the exact sequence "Bharat", so isContains is true and true is printed. 4) str.contains("bharat") looks for lowercase 'b', but the string has uppercase 'B', so no match is found. 5) Therefore the second println prints false, demonstrating that contains() is case-sensitive.
Q277.Easy
Write a Java program that stores the sentence "Visit India Gate to see Delhi" in a String. Use the contains() method inside an if-else control structure to check whether the sentence contains "India Gate". If it does, print "This string contains India Gate"; otherwise print "Result not found". Name the file ContainsCheck.java.
Show answer & explanation
Answer:
public class ContainsCheck {
    public static void main(String[] args) {
        String str = "Visit India Gate to see Delhi";
        if (str.contains("India Gate")) {
            System.out.println("This string contains India Gate");
        } else {
            System.out.println("Result not found");
        }
    }
}
Explanation: 1) Create a class ContainsCheck with a main method. 2) Store the sentence "Visit India Gate to see Delhi" in a String variable str. 3) Call str.contains("India Gate"), which returns true because that exact char-sequence appears in the sentence. 4) Since the condition is true, the if-block runs and prints "This string contains India Gate". 5) The else-block would print "Result not found" only if contains() returned false.
Q278.Easy
Write a Java program that demonstrates a static nested class with an instance method. Create an outer class named College that has a static int field named strength set to 45. Inside it, define a static nested class named Department with an instance method display() that prints "strength is " followed by the value of the outer class's static field. In the main method, create an object of the nested class using the outer class name (College.Department) and call display().
Show answer & explanation
Answer:
class College {
    static int strength = 45;
    static class Department {
        void display() {
            System.out.println("strength is " + strength);
        }
    }
    public static void main(String args[]) {
        College.Department obj = new College.Department();
        obj.display();
    }
}
Explanation: 1. The outer class College holds a static field strength = 45. 2. The static nested class Department is declared inside College; being static, it can directly use the outer class's static members. 3. Its instance method display() prints "strength is " concatenated with strength. 4. In main, the nested class object is created as new College.Department() (accessed via the outer class name). 5. Calling obj.display() prints: strength is 45.
Q279.Easy
Write a Java program that uses a simple for loop to print the first 8 multiples of 3, each on a new line (i.e., 3, 6, 9, ..., 24).
Show answer & explanation
Answer:
public class MultiplesOfThree {
    public static void main(String[] args) {
        for (int i = 1; i <= 8; i++) {
            System.out.println(i * 3);
        }
    }
}
Explanation: 1) Initialization: i = 1 starts the counter. 2) Condition: loop continues while i <= 8, giving exactly 8 iterations. 3) Body: prints i * 3, so it prints 3, 6, 9, 12, 15, 18, 21, 24. 4) Increment: i++ increases i by 1 each time until the condition becomes false.
Q280.Easy
Write a Java program that uses a nested for loop to print all pairs of row and column numbers where the outer loop variable r runs from 1 to 4 and the inner loop variable c runs from 1 to 2. Each pair should be printed on its own line as "r c" (row number, a space, then column number).
Show answer & explanation
Answer:
public class NestedLoopPairs {
    public static void main(String[] args) {
        for (int r = 1; r <= 4; r++) {
            for (int c = 1; c <= 2; c++) {
                System.out.println(r + " " + c);
            }
        }
    }
}
Explanation: 1) The outer loop runs r = 1, 2, 3, 4. 2) For each value of r, the inner loop runs completely with c = 1, 2. 3) So the printed pairs are 1 1, 1 2, 2 1, 2 2, 3 1, 3 2, 4 1, 4 2 — total 4 x 2 = 8 lines. 4) The inner loop restarts from c = 1 every time the outer loop moves to the next r.
Q281.Easy
Write a Java program that demonstrates an infinite for loop. Use a for loop with no initialization, condition or update (i.e., for(;;)) and inside it print the statement "endless loop". Name the class LoopDemo.
Show answer & explanation
Answer:
public class LoopDemo {
    public static void main(String[] args) {
        // Using no condition in for loop
        for (;;) {
            System.out.println("endless loop");
        }
    }
}
Explanation: 1) A for loop has three parts: initialization; condition; update. 2) Writing for(;;) leaves all three parts empty, so there is no condition to stop the loop. 3) With no terminating condition the loop runs forever, printing "endless loop" repeatedly. 4) Such a loop is called an infinite (infinitive) for loop and is normally stopped externally (e.g., Ctrl+C) or by a break inside the body.
Q282.Easy
Write a Java program that demonstrates the sleep() method on a custom thread. Create a class named WorkerThread that extends Thread; in its run() method, loop with i from 1 to 4 (i.e., i < 5), and on each iteration make the thread sleep for 300 milliseconds (handling InterruptedException by printing the exception), then print the value of i. In main, create two WorkerThread objects and start both of them.
Show answer & explanation
Answer:
class WorkerThread extends Thread {
    public void run() {
        for (int i = 1; i < 5; i++) {
            // the thread will sleep for 300 milliseconds
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
            System.out.println(i);
        }
    }

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

        t1.start();
        t2.start();
    }
}
Explanation: 1) WorkerThread extends Thread so it can run as a separate thread. 2) run() contains the thread's work: a for loop from i = 1 to 4. 3) Inside the loop, Thread.sleep(300) pauses the current thread for 300 ms; it must be wrapped in try-catch because it can throw InterruptedException. 4) After the pause, the value of i is printed. 5) In main, two WorkerThread objects t1 and t2 are created and start() is called on each, so both threads run run() concurrently, each printing 1 to 4 with 300 ms gaps.
Q283.Easy
Write a Java program that demonstrates the sleep() method of the Thread class on the main thread. The program should loop 5 times and, on each iteration, make the main thread sleep for 1000 milliseconds (1 second) before printing the loop variable. Catch any exception and print it. Name the class MainThreadSleepDemo.
Show answer & explanation
Answer:
public class MainThreadSleepDemo
{
    public static void main(String[] args)
    {
        try
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.sleep(1000);
                System.out.println(i);
            }
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
}
Explanation: 1. The class MainThreadSleepDemo has a main method. 2. A try block starts a loop from i = 0 to i < 5. 3. On each iteration, Thread.sleep(1000) pauses the main thread for 1000 ms (1 second). 4. After the pause, the current value of i is printed. 5. The loop runs 5 times, so 0, 1, 2, 3, 4 are printed with a 1-second gap between each. 6. If an InterruptedException occurs, the catch block prints it.
Q284.Easy
Write a Java program that demonstrates the sleep() method of the Thread class when a negative sleeping time is passed. The program should loop 5 times, and inside the loop call Thread.sleep(-100), which throws an IllegalArgumentException. Catch the exception and print it. Name the class SleepNegativeDemo.
Show answer & explanation
Answer:
public class SleepNegativeDemo
{
    public static void main(String[] args)
    {
        try
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.sleep(-100);
                System.out.println(i);
            }
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
}
Explanation: 1. The class SleepNegativeDemo has a main method. 2. A try block starts a loop from i = 0 to i < 5. 3. Inside the loop, Thread.sleep(-100) is called with a negative value, which immediately throws an IllegalArgumentException. 4. The println(i) line is never reached because the exception is thrown first. 5. The catch block catches the exception and prints it, e.g. java.lang.IllegalArgumentException: timeout value is negative. 6. The program then ends normally.
Q285.Easy
Write a Java program that demonstrates autoboxing of a primitive into a wrapper object. Declare an int variable with the value 45, then convert it to an Integer in two ways: explicitly using Integer.valueOf(), and implicitly through autoboxing. Print the primitive int, the explicitly created Integer, and the autoboxed Integer separated by spaces.
Show answer & explanation
Answer:
public class AutoboxDemo {
    public static void main(String[] args) {
        // Converting int into Integer
        int value = 45;
        Integer explicitObj = Integer.valueOf(value); // explicit conversion
        Integer autoObj = value;                      // autoboxing: compiler inserts Integer.valueOf(value)

        System.out.println(value + " " + explicitObj + " " + autoObj);
    }
}
Explanation: 1. Declare a primitive int value = 45. 2. Use Integer.valueOf(value) to explicitly create an Integer object explicitObj. 3. Assign value directly to an Integer variable autoObj; this is autoboxing, and the compiler internally inserts Integer.valueOf(value). 4. Print value, explicitObj and autoObj separated by spaces, giving the output: 45 45 45.
Q286.Easy
Write a Java program that demonstrates unboxing of a wrapper object into a primitive. Create an Integer wrapper object holding the value 7, then convert it to an int in two ways: explicitly using intValue(), and implicitly through unboxing. Print the wrapper object, the explicitly converted int, and the implicitly unboxed int separated by spaces.
Show answer & explanation
Answer:
public class UnboxDemo {
    public static void main(String[] args) {
        // Converting Integer to int
        Integer num = new Integer(7);
        int explicitVal = num.intValue(); // explicit conversion
        int autoVal = num;                // unboxing: compiler inserts num.intValue()

        System.out.println(num + " " + explicitVal + " " + autoVal);
    }
}
Explanation: 1. Create an Integer wrapper object num with value 7 using new Integer(7). 2. Call num.intValue() to explicitly extract the primitive int into explicitVal. 3. Assign num directly to an int variable autoVal; this is unboxing, and the compiler internally inserts num.intValue(). 4. Print num, explicitVal and autoVal separated by spaces, giving the output: 7 7 7.
Q287.Easy
Write a Java program that declares primitive variables of each type (byte, short, int, long, float, double, char, boolean) with the values 5, 15, 25, 35, 45.5F, 55.5D, 'z', false respectively. Convert each primitive into its corresponding wrapper object (autoboxing), print all the objects, then convert each object back to its primitive (unboxing) and print all the primitive values.
Show answer & explanation
Answer:
public class WrapperDemo {
    public static void main(String[] args) {
        byte b = 5;
        short s = 15;
        int i = 25;
        long l = 35;
        float f = 45.5F;
        double d = 55.5D;
        char c = 'z';
        boolean bool = false;

        // Autoboxing: primitives to wrapper objects
        Byte byteObj = b;
        Short shortObj = s;
        Integer intObj = i;
        Long longObj = l;
        Float floatObj = f;
        Double doubleObj = d;
        Character charObj = c;
        Boolean boolObj = bool;

        System.out.println("---Printing object values---");
        System.out.println("Byte object: " + byteObj);
        System.out.println("Short object: " + shortObj);
        System.out.println("Integer object: " + intObj);
        System.out.println("Long object: " + longObj);
        System.out.println("Float object: " + floatObj);
        System.out.println("Double object: " + doubleObj);
        System.out.println("Character object: " + charObj);
        System.out.println("Boolean object: " + boolObj);

        // Unboxing: wrapper objects to primitives
        byte byteVal = byteObj;
        short shortVal = shortObj;
        int intVal = intObj;
        long longVal = longObj;
        float floatVal = floatObj;
        double doubleVal = doubleObj;
        char charVal = charObj;
        boolean boolVal = boolObj;

        System.out.println("---Printing primitive values---");
        System.out.println("byte value: " + byteVal);
        System.out.println("short value: " + shortVal);
        System.out.println("int value: " + intVal);
        System.out.println("long value: " + longVal);
        System.out.println("float value: " + floatVal);
        System.out.println("double value: " + doubleVal);
        System.out.println("char value: " + charVal);
        System.out.println("boolean value: " + boolVal);
    }
}
Explanation: 1) Declare one primitive of each of the 8 types with the given values. 2) Assign each primitive to its wrapper type (Byte, Short, Integer, Long, Float, Double, Character, Boolean) - this is autoboxing, done automatically by the compiler. 3) Print each wrapper object; println calls toString() so the stored value appears. 4) Assign each wrapper object back to a primitive variable - this is unboxing (e.g., intVal = intObj calls intValue()). 5) Print each primitive; the output shows the same values, demonstrating both conversions work.
Q288.Easy
Write a Java program that creates a custom wrapper class named 'Meter' which wraps a primitive int (representing a distance in metres). The class should have a no-arg constructor, a constructor taking an int, getter and setter methods, and an overridden toString() that returns the stored value as a String. In main, create a Meter object with the value 25 and print it.
Show answer & explanation
Answer:
class Meter {
    private int value;
    Meter() {}
    Meter(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return Integer.toString(value);
    }
}

public class TestMeter {
    public static void main(String[] args) {
        Meter m = new Meter(25);
        System.out.println(m);
    }
}
Explanation: 1) Define class Meter with a private int field 'value' that wraps the primitive. 2) Provide a no-arg constructor and a constructor Meter(int) that assigns the field. 3) Add getValue() and setValue(int) to read/modify the wrapped value. 4) Override toString() to return Integer.toString(value) so printing the object shows the number. 5) In main, create Meter m = new Meter(25) and System.out.println(m) prints 25.
Q289.Easy
Write a Java program that defines a class named Greet and prints the line "Welcome to Java, Rohan" to the console when run.
Show answer & explanation
Answer:
class Greet {
    public static void main(String args[]) {
        System.out.println("Welcome to Java, Rohan");
    }
}
Explanation: 1) Declare a class named Greet — the file should be saved as Greet.java. 2) Inside it, define the entry point: public static void main(String args[]). 3) Use System.out.println to print the exact text "Welcome to Java, Rohan". 4) Compile with 'javac Greet.java' and run with 'java Greet'; the message is displayed on the console.
Q290.Easy
Write a Java program that prints the message "Namaste India" to the console. Use a class named Greet with a main method.
Show answer & explanation
Answer:
class Greet {
    public static void main(String args[]) {
        System.out.println("Namaste India");
    }
}
Explanation: 1) Define a class named Greet. 2) Inside it, declare the entry point: public static void main(String args[]). 3) Use System.out.println to print the text to the console. 4) The string "Namaste India" is printed followed by a new line when the program runs.
Q291.Easy
Write a Java program that prints "Namaste India" to the console using a main method written in an unusual but valid style: put the access modifier after the static modifier, use var-args (three dots) for the String parameter, and end the class declaration with an optional semicolon. The program must compile and run correctly.
Show answer & explanation
Answer:
class Bharat {
    static public void main(String... args) {
        System.out.println("Namaste India");
    }
};
Explanation: 1) The class is named Bharat and its closing brace is followed by an optional semicolon, which Java allows. 2) The main method is declared as 'static public void main(String... args)': the order of static and public does not matter, and var-args (String...) is a valid alternative to String[]. 3) Inside main, System.out.println prints the text "Namaste India" followed by a newline. 4) Because the signature is still a valid main method, the JVM runs it and the message appears on the console.
Q292.Easy
Write a Java program that demonstrates the syntax of a nested interface declared within another interface. Define an interface named 'Vehicle' that contains a nested interface named 'Engine' with a method 'start()'. Then create a class 'Car' that implements 'Vehicle.Engine' and provides the implementation of 'start()' to print "Engine started". Finally, in a main method, instantiate 'Car' and call 'start()'.
Show answer & explanation
Answer:
interface Vehicle {
    interface Engine {
        void start();
    }
}

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

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.start();
    }
}
Explanation: 1. Define an interface 'Vehicle'. 2. Inside 'Vehicle', declare a nested interface 'Engine' with a method 'start()'. 3. Create a class 'Car' that implements 'Vehicle.Engine'. 4. Provide the implementation of 'start()' in 'Car' to print the message. 5. In the main method, create an object of 'Car' and call 'start()'.
Q293.Easy
Write a Java program that demonstrates the syntax of a nested interface declared within a class. Define a class named 'Outer' that contains a nested interface named 'Inner' with a method 'show()'. Then create another class 'Demo' that implements 'Outer.Inner' and provides the implementation of 'show()' to print "Hello from nested interface". Finally, in a main method, instantiate 'Demo' and call 'show()'.
Show answer & explanation
Answer:
class Outer {
    interface Inner {
        void show();
    }
}

class Demo implements Outer.Inner {
    public void show() {
        System.out.println("Hello from nested interface");
    }
}

public class Main {
    public static void main(String[] args) {
        Demo d = new Demo();
        d.show();
    }
}
Explanation: 1. Define a class 'Outer'. 2. Inside 'Outer', declare a nested interface 'Inner' with a method 'show()'. 3. Create a class 'Demo' that implements 'Outer.Inner'. 4. Provide the implementation of 'show()' in 'Demo' to print the message. 5. In the main method, create an object of 'Demo' and call 'show()'.
Q294.Easy
Write a Java program named WordCheck.java. Create four String variables: w1 = "delhi", w2 = "delhi", w3 = "DELHI", w4 = "agra". Print the result of w1.equals(w2), then w1.equals(w3), then w1.equals(w4), each on its own line.
Show answer & explanation
Answer:
public class WordCheck {
    public static void main(String[] args) {
        String w1 = "delhi";
        String w2 = "delhi";
        String w3 = "DELHI";
        String w4 = "agra";
        System.out.println(w1.equals(w2)); // true, same content and case
        System.out.println(w1.equals(w3)); // false, case differs
        System.out.println(w1.equals(w4)); // false, content differs
    }
}
Explanation: Step 1: w1 and w2 are both "delhi", so w1.equals(w2) compares character by character and returns true. Step 2: w3 is "DELHI" in uppercase; equals() is case-sensitive, so w1.equals(w3) returns false. Step 3: w4 is "agra", a different word, so w1.equals(w4) returns false. Step 4: The program prints true, false, false on three separate lines.
Q295.Easy
Write a Java program named CityCompare.java. Create three String variables: c1 = "Mumbai", c2 = "Mumbai", c3 = "mumbai". First print the result of c1.equals(c2). Then use an if-else statement with c1.equals(c3): if they are equal print "cities match", otherwise print "cities differ".
Show answer & explanation
Answer:
public class CityCompare {
    public static void main(String[] args) {
        String c1 = "Mumbai";
        String c2 = "Mumbai";
        String c3 = "mumbai";
        System.out.println(c1.equals(c2)); // true, same content and case
        if (c1.equals(c3)) {
            System.out.println("cities match");
        } else {
            System.out.println("cities differ");
        }
    }
}
Explanation: Step 1: Declare c1 and c2 both as "Mumbai" and c3 as "mumbai". Step 2: c1.equals(c2) compares content and case; both are identical, so it prints true. Step 3: c1.equals(c3) compares "Mumbai" with "mumbai"; equals() is case-sensitive, so the first letter differs and it returns false. Step 4: Since the condition is false, the else branch runs and prints "cities differ".
Q296.Easy
Write a Java program that demonstrates the finally block when no exception occurs. Inside a try block, compute the integer division 36/6 and print the result. Add a catch block for ArithmeticException that prints the exception message (it will not run here). Add a finally block that prints "cleanup done". After the try-catch-finally, print "program continues". Name the class FinallyDemo.
Show answer & explanation
Answer:
public class FinallyDemo {
    public static void main(String[] args) {
        try {
            int result = 36 / 6;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println(e);
        } finally {
            System.out.println("cleanup done");
        }
        System.out.println("program continues");
    }
}
Explanation: 1) The try block computes 36/6 = 6 with no exception, so it prints 6. 2) Since no ArithmeticException is thrown, the catch block is skipped. 3) The finally block always runs, so it prints "cleanup done". 4) Execution continues after the try-catch-finally, printing "program continues". 5) Output: 6, then cleanup done, then program continues.
Q297.Easy
Write a Java program that shows that changing a primitive parameter inside a method does not affect the original variable. Create a class named Counter with an int instance variable count set to 30. Add a method modify(int count) that sets count = count + 70 (only the local copy changes). In main, create a Counter object, print "before modify " followed by its count, call modify(300), then print "after modify " followed by its count.
Show answer & explanation
Answer:
class Counter {
    int count = 30;

    void modify(int count) {
        count = count + 70; // changes will be in the local variable only
    }

    public static void main(String args[]) {
        Counter c = new Counter();

        System.out.println("before modify " + c.count);
        c.modify(300);
        System.out.println("after modify " + c.count);
    }
}
Explanation: 1) Class Counter has instance variable count = 30. 2) main creates object c, so c.count is 30; prints 'before modify 30'. 3) c.modify(300) passes the value 300 into the parameter count (a local copy). 4) Inside modify, count = 300 + 70 = 370, but this only changes the local parameter, not c.count. 5) Back in main, c.count is still 30; prints 'after modify 30'.
Q298.Easy
Write a Java program that demonstrates how passing an object to a method lets the method change the object's instance variable. Create a class named Account with an int instance variable balance set to 2000. Add a method update(Account acc) that adds 500 to acc.balance. In main, create an Account object, print "before update " followed by its balance, call update passing the object, then print "after update " followed by its balance.
Show answer & explanation
Answer:
class Account {
    int balance = 2000;

    void update(Account acc) {
        acc.balance = acc.balance + 500; // changes the instance variable of the passed object
    }

    public static void main(String args[]) {
        Account acc = new Account();

        System.out.println("before update " + acc.balance);
        acc.update(acc); // passing object
        System.out.println("after update " + acc.balance);
    }
}
Explanation: 1) Class Account has instance variable balance = 2000. 2) main creates object acc, so acc.balance is 2000; prints 'before update 2000'. 3) acc.update(acc) passes the reference (by value) to the same object. 4) Inside update, acc.balance = 2000 + 500 = 2500, which modifies the original object's field. 5) Back in main, acc.balance is now 2500; prints 'after update 2500'.
Q299.Easy
Write a Java program that shows what happens when you try to start the same thread twice. Create a class named TwiceStartDemo that extends Thread. Its run method should print "executing...". In the main method, create one instance of TwiceStartDemo, call start() on it, and then call start() again on the same instance. The program should demonstrate that the second start() throws an IllegalThreadStateException.
Show answer & explanation
Answer:
public class TwiceStartDemo extends Thread {
    public void run() {
        System.out.println("executing...");
    }

    public static void main(String[] args) {
        TwiceStartDemo t = new TwiceStartDemo();
        t.start();
        t.start();
    }
}
Explanation: 1. TwiceStartDemo extends Thread and overrides run() to print "executing...". 2. In main(), a single thread object t is created. 3. The first call to t.start() launches the thread; run() executes and prints "executing...". 4. The second call to t.start() on the same thread object is illegal because a thread can be started only once. 5. The JVM throws IllegalThreadStateException on the second start(), so the program terminates with that exception after printing "executing..." once.
Q300.Easy
Write a Java program that uses a for loop to print the numbers 1 to 10, but stops the loop (using the break statement) as soon as the number 7 is reached, so that 7 and later numbers are not printed.
Show answer & explanation
Answer:
public class StopAtSeven {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 7) {
                break;
            }
            System.out.println(i);
        }
    }
}
Explanation: 1) The for loop runs i from 1 to 10. 2) Inside the loop, if i equals 7, the break statement exits the loop immediately. 3) For i = 1 to 6 the condition is false, so each number is printed. 4) When i becomes 7, break runs and the loop ends, so 7,8,9,10 are never printed. 5) Output: 1 2 3 4 5 6 (each on its own line).
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