Coding Questions Questions

Question Bank › Technical › Java › Coding Questions

12345

Other questions

Q101.Easy
Write a Java program that demonstrates the String indexOf(String substring) method. Create a String variable holding the text "Please find the festival date" and use indexOf to find the starting index of the substring "festival", then print the result. FileName: FindSubstringIndex.java
Show answer & explanation
Answer:
public class FindSubstringIndex {
    public static void main(String[] args) {
        String text = "Please find the festival date";
        int index = text.indexOf("festival");
        System.out.println("index of substring " + index);
    }
}
Explanation: Step 1: Create a String text with value "Please find the festival date". Step 2: Call text.indexOf("festival") which searches for the substring and returns the index of its first character. Step 3: Counting from 0: 'P'=0, 'l'=1, 'e'=2, 'a'=3, 's'=4, 'e'=5, ' '=6, 'f'=7, 'i'=8, 'n'=9, 'd'=10, ' '=11, 't'=12, 'h'=13, 'e'=14, ' '=15, 'f'=16. So the substring starts at index 16. Step 4: Print the returned index, giving: index of substring 16.
Q102.Easy
Write a Java program named IndexOfExample3.java that demonstrates the String indexOf(String str, int fromIndex) method. Create a String variable holding the text "Delhi is the capital of India" and find the index of the substring "capital" starting the search from index 5, then again starting from index 20. Print each result on its own line as: index of substring <value>
Show answer & explanation
Answer:
public class IndexOfExample3 {
    public static void main(String[] args) {
        String s1 = "Delhi is the capital of India";
        int index = s1.indexOf("capital", 5);
        System.out.println("index of substring " + index);
        index = s1.indexOf("capital", 20);
        System.out.println("index of substring " + index);
    }
}
Explanation: Step 1: The string is "Delhi is the capital of India". Step 2: Indices: 0 D,1 e,2 l,3 h,4 i,5 space,6 i,7 s,8 space,9 t,10 h,11 e,12 space,13 c,14 a,15 p,16 i,17 t,18 a,19 l,20 space,21 o,22 f,23 space,24 I,25 n,26 d,27 i,28 a. Step 3: "capital" begins at index 13. Searching from index 5 finds it at 13. Step 4: Searching from index 20 starts after 13, so "capital" is not found and indexOf returns -1. Step 5: Output: index of substring 13, then index of substring -1.
Q103.Easy
Write a Java program named IndexOfExample4.java that demonstrates the String indexOf(int ch, int fromIndex) method. Create a String variable holding the text "Mumbai is a coastal city" and find the index of the first occurrence of the character 'a' at or after index 10. Print the result as: index of char <value>
Show answer & explanation
Answer:
public class IndexOfExample4 {
    public static void main(String[] args) {
        String s1 = "Mumbai is a coastal city";
        int index = s1.indexOf('a', 10);
        System.out.println("index of char " + index);
    }
}
Explanation: Step 1: The string is "Mumbai is a coastal city". Step 2: indexOf('a', 10) starts searching from index 10. Step 3: Indices: 0 M,1 u,2 m,3 b,4 a,5 i,6 space,7 i,8 s,9 space,10 a,11 space,12 c,13 o,14 a,15 s,16 t,17 a,18 l,19 space,20 c,21 i,22 t,23 y. Step 4: The first 'a' at or after index 10 is at index 10 itself. Step 5: So the program prints: index of char 10.
Q104.Easy
Write a Java program that creates a StringBuilder containing the text "Ram " and then uses the append() method to add the string "Kumar" to it. Finally, print the resulting StringBuilder to the console.
Show answer & explanation
Answer:
public class AppendDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Ram ");
        sb.append("Kumar");
        System.out.println(sb);
    }
}
Explanation: Step 1: Create a StringBuilder with initial content "Ram " (with a trailing space). Step 2: Call sb.append("Kumar") — this concatenates "Kumar" to the end of the existing content and modifies the same StringBuilder object. Step 3: The content becomes "Ram " + "Kumar" = "Ram Kumar". Step 4: System.out.println(sb) prints: Ram Kumar
Q105.Easy
Write a Java program that creates a StringBuilder containing the text "Namaste " and then uses the insert() method to insert the string "Bharat" at position 2. Finally, print the resulting StringBuilder to the console.
Show answer & explanation
Answer:
public class InsertDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Namaste ");
        sb.insert(2, "Bharat");
        System.out.println(sb);
    }
}
Explanation: Step 1: Create a StringBuilder with initial content "Namaste " (note the trailing space). Step 2: Call sb.insert(2, "Bharat") — this inserts "Bharat" starting at index 2, i.e. after the first two characters "Na". Step 3: The original characters from index 2 onward shift right, giving "Na" + "Bharat" + "maste " = "NaBharatmaste ". Step 4: System.out.println(sb) prints the modified StringBuilder: NaBharatmaste .
Q106.Easy
Write a Java program that creates a StringBuilder with the text "Bharat", uses the replace(beginIndex, endIndex, str) method to replace the characters from index 1 up to (but not including) index 4 with "har", and then prints the resulting string.
Show answer & explanation
Answer:
public class StringBuilderReplaceDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Bharat");
        sb.replace(1, 4, "har");
        System.out.println(sb);
    }
}
Explanation: 1) Create a StringBuilder holding "Bharat" (indices: B=0, h=1, a=2, r=3, a=4, t=5). 2) replace(1,4,"har") removes characters at indices 1,2,3 i.e. 'h','a','r' and inserts "har" in their place. 3) The string becomes B + har + a + t = "Bharat". 4) System.out.println prints Bharat.
Q107.Easy
Write a Java program that creates a StringBuilder with the text "Namaste", uses the delete(beginIndex, endIndex) method to remove characters from index 2 up to (but not including) index 5, and then prints the resulting string.
Show answer & explanation
Answer:
public class StringBuilderDeleteDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Namaste");
        sb.delete(2, 5);
        System.out.println(sb);
    }
}
Explanation: 1) Create a StringBuilder holding "Namaste" (indices: N=0, a=1, m=2, a=3, s=4, t=5, e=6). 2) delete(2,5) removes characters at indices 2,3,4 i.e. 'm','a','s'. 3) The remaining characters are N,a,t,e giving "Nate". 4) System.out.println prints Nate.
Q108.Easy
Write a Java program that uses the reverse() method of the StringBuilder class. Create a StringBuilder with the text "Bharat" and reverse it, then print the reversed string.
Show answer & explanation
Answer:
public class BuilderReverseDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Bharat");
        sb.reverse();
        System.out.println(sb); // prints tarahB
    }
}
Explanation: 1) new StringBuilder("Bharat") stores the characters B,h,a,r,a,t. 2) Calling sb.reverse() reverses the sequence in place to t,a,r,a,h,B. 3) Printing sb outputs "tarahB".
Q109.Easy
Write a Java program that demonstrates the capacity() method of the StringBuilder class. Create an empty StringBuilder, print its default capacity (16). Append the string "Namaste" and print the capacity again. Then append the string "India is a wonderful country" and print the capacity once more, showing that when the content exceeds the current capacity, the new capacity becomes (oldCapacity*2)+2.
Show answer & explanation
Answer:
public class BuilderCapacityDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        System.out.println(sb.capacity()); // default 16
        sb.append("Namaste");
        System.out.println(sb.capacity()); // still 16
        sb.append("India is a wonderful country");
        System.out.println(sb.capacity()); // (16*2)+2 = 34
    }
}
Explanation: 1) new StringBuilder() starts with default capacity 16. 2) Appending "Namaste" (7 chars) keeps length 7 <= 16, so capacity stays 16. 3) Appending "India is a wonderful country" (27 chars) makes total length 34, which exceeds 16. 4) StringBuilder grows capacity as (oldCapacity*2)+2 = (16*2)+2 = 34. 5) So the three printed values are 16, 16, 34.
Q110.Easy
Write a Java program that demonstrates the instanceof operator. Create a class named Student, make an object of it, and use instanceof to check whether the object is an instance of Student, printing the boolean result.
Show answer & explanation
Answer:
class Student {
    public static void main(String args[]) {
        Student s = new Student();
        System.out.println(s instanceof Student);
    }
}
Explanation: 1) Define class Student with a main method. 2) Create an object s of type Student using new Student(). 3) The expression s instanceof Student checks at runtime whether s refers to an object of type Student. 4) Since s is exactly a Student object, the expression evaluates to true. 5) System.out.println prints true.
Q111.Easy
Write a Java program that demonstrates the instanceof operator with inheritance. Create a parent class named Fruit and a child class named Mango that extends Fruit. In main, create a Mango object referenced by a Mango variable and print the result of checking whether it is an instance of Fruit. The program should print true.
Show answer & explanation
Answer:
class Fruit {}

class Mango extends Fruit { // Mango inherits Fruit
    public static void main(String args[]) {
        Mango m = new Mango();
        System.out.println(m instanceof Fruit); // true
    }
}
Explanation: 1. Define parent class Fruit (empty body). 2. Define class Mango that extends Fruit, so a Mango IS-A Fruit. 3. In main, create m = new Mango(). 4. Check m instanceof Fruit: since Mango is a subclass of Fruit, the object is also a Fruit, so it returns true. 5. System.out.println prints true.
Q112.Easy
Write a Java program that demonstrates the instanceof operator applied to a variable holding null. Declare a class named Vehicle, create a Vehicle reference set to null, and print the result of checking whether that null reference is an instance of Vehicle. The program should print false.
Show answer & explanation
Answer:
class Vehicle {
    public static void main(String args[]) {
        Vehicle v = null;
        System.out.println(v instanceof Vehicle); // false
    }
}
Explanation: 1. Define a class Vehicle with a main method. 2. Declare a Vehicle reference v and assign it null. 3. Use the instanceof operator: v instanceof Vehicle. 4. Since v is null, instanceof always returns false (it never throws an exception for null). 5. System.out.println prints false.
Q113.Easy
Write a Java program that demonstrates the problem of variable shadowing when the 'this' keyword is NOT used. Create a class named 'Employee' with instance variables: int empId, String empName, double salary. The constructor should take parameters with the SAME names (empId, empName, salary) but WITHOUT using 'this' keyword, so the assignments fail to set the instance variables. Add a display() method that prints empId, empName and salary. In main, create two Employee objects: one with (201, "Ravi", 45000.0) and another with (202, "Meera", 52000.0), then call display() on both.
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;
    double salary;

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

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

class TestEmployee {
    public static void main(String args[]) {
        Employee e1 = new Employee(201, "Ravi", 45000.0);
        Employee e2 = new Employee(202, "Meera", 52000.0);
        e1.display();
        e2.display();
    }
}
Explanation: 1) The class Employee has instance variables empId, empName, salary. 2) The constructor parameters have the same names, so inside the constructor the parameter names hide (shadow) the instance variables. 3) The statement empId = empId assigns the parameter to itself; the instance variable is never set. 4) Hence the instance variables keep their default values: 0, null, 0.0. 5) display() prints these defaults, showing the ambiguity problem that the 'this' keyword solves.
Q114.Easy
Write a Java program that shows how the this keyword can be used to invoke a method of the current class. Create a class named Greeter with two methods: greet() which prints "Good morning", and welcome() which calls greet() using this.greet() and then prints "Have a nice day". In the main method, create a Greeter object and call welcome().
Show answer & explanation
Answer:
class Greeter {
    void greet() {
        System.out.println("Good morning");
    }
    void welcome() {
        System.out.println("Have a nice day");
        this.greet();
    }
}

class TestGreeter {
    public static void main(String args[]) {
        Greeter g = new Greeter();
        g.welcome();
    }
}
Explanation: 1) greet() simply prints 'Good morning'. 2) welcome() first prints 'Have a nice day', then calls this.greet(), which invokes greet() on the current object. 3) main creates a Greeter object g and calls g.welcome(). 4) welcome() runs: prints 'Have a nice day', then greet() prints 'Good morning'. 5) Output: Have a nice day, then Good morning.
Q115.Easy
Write a Java program that demonstrates constructor chaining using the this() keyword. Create a class named Shop. Its no-argument constructor should print "Welcome to the shop". Its parameterized constructor (taking an int itemCount) should first call the no-argument constructor using this(), then print the item count. In the main method, create an object of Shop using the parameterized constructor with the value 25.
Show answer & explanation
Answer:
class Shop {
    Shop() {
        System.out.println("Welcome to the shop");
    }
    Shop(int itemCount) {
        this();
        System.out.println(itemCount);
    }
}

class TestShop {
    public static void main(String args[]) {
        Shop s = new Shop(25);
    }
}
Explanation: 1) The no-arg constructor Shop() prints the welcome message. 2) The parameterized constructor Shop(int itemCount) calls this() as its first statement, which invokes the no-arg constructor. 3) So 'Welcome to the shop' is printed first, then control returns to the parameterized constructor. 4) It then prints the itemCount value 25. 5) main creates new Shop(25), so output is: Welcome to the shop, then 25.
Q116.Easy
Write a Java program that demonstrates passing the 'this' keyword as an argument in a method. Create a class named 'Payment' with a method 'process(Payment p)' that prints "payment processed". Add another method 'start()' that calls process(this). In main, create a Payment object and call start().
Show answer & explanation
Answer:
class Payment {
    void process(Payment p) {
        System.out.println("payment processed");
    }
    void start() {
        process(this);
    }
    public static void main(String[] args) {
        Payment pay = new Payment();
        pay.start();
    }
}
Explanation: 1) process(Payment p) accepts a Payment reference and prints the message. 2) start() calls process(this); 'this' is the current Payment object, so the object passes itself as the argument. 3) main creates a Payment object pay and calls start(). 4) start() invokes process with the same object, printing "payment processed".
Q117.Easy
Write a Java program that demonstrates the unary ++ and -- operators: start with int count = 6, then print count++ , ++count , count-- , --count each on its own line.
Show answer & explanation
Answer:
public class UnaryDemo {
    public static void main(String[] args) {
        int count = 6;
        System.out.println(count++);
        System.out.println(++count);
        System.out.println(count--);
        System.out.println(--count);
    }
}
Explanation: 1) count starts at 6. 2) count++ prints 6 (post-increment), then count becomes 7. 3) ++count first increments to 8, then prints 8. 4) count-- prints 8 (post-decrement), then count becomes 7. 5) --count first decrements to 6, then prints 6. 6) Output lines: 6, 8, 8, 6.
Q118.Easy
Write a Java program that demonstrates the unary bitwise complement operator (~) and the unary logical NOT operator (!). Use an int variable x = 7, an int variable y = -7, a boolean flag1 = true and a boolean flag2 = false, and print the results of ~x, ~y, !flag1 and !flag2.
Show answer & explanation
Answer:
public class UnaryDemo {
    public static void main(String[] args) {
        int x = 7;
        int y = -7;
        boolean flag1 = true;
        boolean flag2 = false;
        System.out.println(~x);
        System.out.println(~y);
        System.out.println(!flag1);
        System.out.println(!flag2);
    }
}
Explanation: Step 1: ~x flips every bit of 7; in two's complement ~7 = -(7+1) = -8, so it prints -8. Step 2: ~y flips every bit of -7; ~(-7) = -(-7)-1 = 6, so it prints 6. Step 3: !flag1 is the opposite of true, so it prints false. Step 4: !flag2 is the opposite of false, so it prints true. Step 5: The program compiles and runs, printing -8, 6, false, true on separate lines.
Q119.Easy
Write a Java program that uses the ternary operator to find the smaller of two integers: priceA = 7 and priceB = 3. Print the smaller value.
Show answer & explanation
Answer:
public class PriceCompare {
    public static void main(String[] args) {
        int priceA = 7;
        int priceB = 3;
        int min = (priceA < priceB) ? priceA : priceB;
        System.out.println(min);
    }
}
Explanation: 1) Declare two int variables priceA=7 and priceB=3. 2) The ternary operator (priceA < priceB) ? priceA : priceB checks the condition. 3) Since 7 < 3 is false, the expression returns priceB, i.e. 3. 4) Store it in min and print it, so output is 3.
Q120.Easy
Write a Java program that uses the ternary operator to check whether a given integer is even or odd. Use the number 24 and print "even number" if it is even, otherwise print "odd number".
Show answer & explanation
Answer:
public class TernaryEvenOdd {
    public static void main(String[] args) {
        int number = 24;
        String output = (number % 2 == 0) ? "even number" : "odd number";
        System.out.println(output);
    }
}
Explanation: 1. Declare an integer variable number and assign 24. 2. Use the ternary operator: (number % 2 == 0) ? "even number" : "odd number". 3. Since 24 % 2 equals 0, the condition is true, so the expression returns "even number". 4. Store the result in a String variable output. 5. Print output, which displays "even number".
Q121.Easy
Write a Java program that demonstrates the use of compound assignment operators. Declare two integer variables: x = 12 and y = 25. Then apply the following operations: add 8 to x, and subtract 5 from y. Print the final values of x and y.
Show answer & explanation
Answer:
public class AssignmentExample {
    public static void main(String[] args) {
        int x = 12;
        int y = 25;
        x += 8;
        y -= 5;
        System.out.println(x);
        System.out.println(y);
    }
}
Explanation: Initialize x to 12 and y to 25. x += 8 is equivalent to x = x + 8, so x becomes 20. y -= 5 is equivalent to y = y - 5, so y becomes 20. Print x (20) and y (20).
Q122.Easy
Write a Java program that demonstrates compound assignment operators. Start with an integer variable 'num' initialized to 15. Then perform the following operations in order: add 5 to num, subtract 3 from num, multiply num by 2, and finally divide num by 4. After each operation, print the current value of num.
Show answer & explanation
Answer:
public class AssignmentDemo {
    public static void main(String[] args) {
        int num = 15;
        num += 5;
        System.out.println(num);
        num -= 3;
        System.out.println(num);
        num *= 2;
        System.out.println(num);
        num /= 4;
        System.out.println(num);
    }
}
Explanation: Initialize num to 15. num += 5 makes num 20, print 20. num -= 3 makes num 17, print 17. num *= 2 makes num 34, print 34. num /= 4 performs integer division: 34/4 = 8 (since both are int), print 8.
Q123.Easy
Write a Java program that declares two int variables p = 18 and q = 4, then prints the results of p + q, p - q, p * q, p / q, and p % q, each on its own line.
Show answer & explanation
Answer:
public class ArithmeticDemo {
    public static void main(String[] args) {
        int p = 18;
        int q = 4;
        System.out.println(p + q);
        System.out.println(p - q);
        System.out.println(p * q);
        System.out.println(p / q);
        System.out.println(p % q);
    }
}
Explanation: 1) p = 18, q = 4. 2) p + q = 22. 3) p - q = 14. 4) p * q = 72. 5) p / q is integer division: 18/4 = 4 (remainder dropped). 6) p % q = 18 mod 4 = 2. The program prints 22, 14, 72, 4, 2 on separate lines.
Q124.Easy
Write a Java program that demonstrates the left shift operator (<<). Declare an int variable x = 7 and print the results of x << 1, x << 2, x << 3, and x << 4, each on its own line.
Show answer & explanation
Answer:
public class ShiftDemo {
    public static void main(String[] args) {
        int x = 7;
        System.out.println(x << 1);
        System.out.println(x << 2);
        System.out.println(x << 3);
        System.out.println(x << 4);
    }
}
Explanation: 1) Left shift by n multiplies the value by 2^n. 2) x = 7. 3) 7 << 1 = 7*2 = 14. 4) 7 << 2 = 7*4 = 28. 5) 7 << 3 = 7*8 = 56. 6) 7 << 4 = 7*16 = 112. The program prints 14, 28, 56, 112 on separate lines.
Q125.Easy
Write a Java program that demonstrates the difference between the logical && operator and the bitwise & operator. Use variables x = 12, y = 7, z = 25. Print the result of (x < y && x < z) and then the result of (x < y & x < z). The program should show that && short-circuits when the first condition is false, while & always evaluates both conditions.
Show answer & explanation
Answer:
public class AndOperatorDemo {
    public static void main(String[] args) {
        int x = 12;
        int y = 7;
        int z = 25;
        System.out.println(x < y && x < z); // false && true = false
        System.out.println(x < y & x < z);  // false & true = false
    }
}
Explanation: 1) Declare x=12, y=7, z=25. 2) x<y is 12<7 = false; x<z is 12<25 = true. 3) For &&: since the first operand is false, the second is not evaluated (short-circuit) and the result is false. 4) For &: both operands are always evaluated; false & true = false. 5) Both println statements therefore print false, but only && skips the second check.
Q126.Easy
Write a Java program that demonstrates a simple shutdown hook by creating a class CleanupThread that extends Thread and overrides run() to print "shut down hook task completed for Delhi office..". In main, register an instance of CleanupThread as a shutdown hook using Runtime and then print "Application running... press ctrl+c to exit". FileName: CleanupThread.java
Show answer & explanation
Answer:
public class CleanupThread extends Thread {
    public void run() {
        System.out.println("shut down hook task completed for Delhi office..");
    }

    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        rt.addShutdownHook(new CleanupThread());
        System.out.println("Application running... press ctrl+c to exit");
    }
}
Explanation: Step 1: Define class CleanupThread extending Thread and override run() to print the cleanup message. Step 2: In main, get Runtime.getRuntime(). Step 3: Register the hook with rt.addShutdownHook(new CleanupThread()). Step 4: Print the running message; when the JVM terminates, the hook thread's run() executes and prints the cleanup line.
Q127.Easy
Write a Java program that declares two strings: s1 = "" and s2 = "Bengaluru". For each string, check whether its length is zero OR it isEmpty(); if so print that the string is empty, otherwise print the string itself. Name the class EmptyCheckDemo.
Show answer & explanation
Answer:
public class EmptyCheckDemo {
    public static void main(String[] args) {
        String s1 = "";
        String s2 = "Bengaluru";

        if (s1.length() == 0 || s1.isEmpty())
            System.out.println("String s1 is empty");
        else
            System.out.println(s1);

        if (s2.length() == 0 || s2.isEmpty())
            System.out.println("String s2 is empty");
        else
            System.out.println(s2);
    }
}
Explanation: Step 1: s1 is "" so s1.length() is 0; the condition (length==0 || isEmpty()) is true, so we print "String s1 is empty". Step 2: s2 is "Bengaluru" so s2.length() is 9 (not 0) and s2.isEmpty() is false; the condition is false. Step 3: The else branch runs for s2 and prints the string itself, i.e., Bengaluru. Step 4: Output: first line "String s1 is empty", second line "Bengaluru".
Q128.Easy
Write a Java program that demonstrates the difference between an empty string and a null string. Declare one String variable as an empty string ("") and another String variable as null. For the empty string, use the isEmpty() method to check and print whether it is empty. For the null string, show that calling isEmpty() directly on it throws a NullPointerException, so instead check for null first (using == null) and print an appropriate message. Name the class NullEmptyDemo.
Show answer & explanation
Answer:
public class NullEmptyDemo {
    public static void main(String[] args) {
        String emptyStr = "";
        String nullStr = null;

        // Check the empty string using isEmpty()
        if (emptyStr.isEmpty()) {
            System.out.println("emptyStr is an empty string.");
        } else {
            System.out.println("emptyStr is not empty.");
        }

        // isEmpty() cannot be used on a null string; check for null first
        if (nullStr == null) {
            System.out.println("nullStr is a null string.");
        } else if (nullStr.isEmpty()) {
            System.out.println("nullStr is an empty string.");
        } else {
            System.out.println("nullStr is not empty.");
        }
    }
}
Explanation: Step 1: Declare emptyStr = "" (zero characters) and nullStr = null (no value at all). Step 2: For emptyStr, isEmpty() returns true because its length is 0, so we print that it is an empty string. Step 3: Calling isEmpty() on nullStr would throw a NullPointerException, since there is no object to call the method on. Step 4: So we first test nullStr == null; this is true, and we print that it is a null string. Step 5: The else-if branch (isEmpty check) is only reached for non-null strings, which keeps the program safe.
Q129.Easy
Write a Java program that checks whether strings are empty, blank (containing only white spaces), or not blank. First check a string that consists of only spaces (for example "     "), then check a string like "  Welcome to Delhi.  ". Use the length(), trim() and isEmpty() methods. Name the class BlankCheck.
Show answer & explanation
Answer:
public class BlankCheck {
    public static void main(String[] args) {
        String str = "     ";
        int size = str.length();
        if (size == 0) {
            System.out.println("The string is empty.");
        } else if (str.trim().isEmpty()) {
            System.out.println("The string is blank.");
        } else {
            System.out.println("The string is not blank.");
        }

        str = "  Welcome to Delhi.  ";
        size = str.length();
        if (size == 0) {
            System.out.println("The string is empty.");
        } else if (str.trim().isEmpty()) {
            System.out.println("The string is blank.");
        } else {
            System.out.println("The string is not blank.");
        }
    }
}
Explanation: 1. Define class BlankCheck with a main method. 2. Set str = " " (five spaces). length() returns 5, so it is not empty. 3. str.trim() removes the spaces giving "", and isEmpty() returns true, so print "The string is blank.". 4. Reassign str = " Welcome to Delhi. ". Its length is greater than 0, so not empty. 5. trim() gives "Welcome to Delhi." which is not empty, so isEmpty() is false and we print "The string is not blank.".
Q130.Easy
Write a Java program that demonstrates the use of the StringBuffer class. Create a StringBuffer initialized with the text "namaste", then append "bharat" to it, and finally print the resulting buffer contents to the console. Name the class BufferDemo.
Show answer & explanation
Answer:
public class BufferDemo {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("namaste");
        buffer.append("bharat");
        System.out.println(buffer);
    }
}
Explanation: 1. Define a public class named BufferDemo. 2. In main, create a StringBuffer object initialized with the string "namaste". 3. Call append("bharat") on the buffer, which adds the text to the end, making it "namastebharat". 4. Print the buffer using System.out.println, which calls toString() on the StringBuffer and outputs namastebharat.
Q131.Easy
Write a Java program to demonstrate the use of the StringBuilder class. Create a StringBuilder initialized with "namaste", append "duniya" to it, and then print the resulting string.
Show answer & explanation
Answer:
public class BuilderDemo {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder("namaste");
        builder.append("duniya");
        System.out.println(builder);
    }
}
Explanation: 1. Create a StringBuilder object initialized with the string "namaste". 2. Call the append method with "duniya" to add it to the end. 3. Print the StringBuilder, which outputs "namasteduniya".
Q132.Easy
Write a Java program named PrintTask.java that performs a single task using multiple threads. The task is to print "Task done by thread" on the console. Achieve this by extending the Thread class, and start three threads that all execute this same task.
Show answer & explanation
Answer:
public class PrintTask extends Thread {
    public void run() {
        System.out.println("Task done by thread");
    }

    public static void main(String[] args) {
        PrintTask t1 = new PrintTask();
        PrintTask t2 = new PrintTask();
        PrintTask t3 = new PrintTask();
        t1.start();
        t2.start();
        t3.start();
    }
}
Explanation: 1) PrintTask extends Thread, so it inherits thread behaviour and overrides run(). 2) run() holds the single task: printing "Task done by thread". 3) In main, three objects t1, t2, t3 of PrintTask are created. 4) start() on each object begins a new thread that executes the same run() method. 5) Thus one task is performed by three threads.
Q133.Easy
Write a Java program named WorkerDemo.java that creates a thread by extending the Thread class. Override run() to print "background job is running..." and in main create an object and call start() to begin the thread.
Show answer & explanation
Answer:
class WorkerDemo extends Thread {
    public void run() {
        System.out.println("background job is running...");
    }

    public static void main(String args[]) {
        WorkerDemo t1 = new WorkerDemo();
        t1.start();
    }
}
Explanation: 1) WorkerDemo extends Thread, so it inherits thread behaviour. 2) Overriding run() defines what the thread does; here it prints the message. 3) In main, t1 = new WorkerDemo() creates the thread object (New state). 4) t1.start() starts a new thread with a new call stack and moves it to Runnable state. 5) When scheduled, the thread's run() executes and prints "background job is running...".
Q134.Easy
Write a Java program named GreetTask.java that performs a single task using multiple threads. The task is to print "Namaste from thread" on the console. Create the task by implementing the Runnable interface, and start two threads that both run this same task.
Show answer & explanation
Answer:
public class GreetTask implements Runnable {
    public void run() {
        System.out.println("Namaste from thread");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new GreetTask());
        Thread t2 = new Thread(new GreetTask());
        t1.start();
        t2.start();
    }
}
Explanation: 1) The class GreetTask implements Runnable, so it must define run(). 2) run() contains the single task: printing "Namaste from thread". 3) In main, two Thread objects t1 and t2 are created, each wrapping a new GreetTask instance (the Runnable). 4) Calling t1.start() and t2.start() launches both threads, each executing the same run() method once. 5) Hence the same task is performed by two threads.
Q135.Easy
Write a Java program named TaskRunner.java that creates a thread by implementing the Runnable interface. The run() method should print "worker thread is active..." and the main method should start the thread using the Thread(Runnable) constructor.
Show answer & explanation
Answer:
class TaskRunner implements Runnable {
    public void run() {
        System.out.println("worker thread is active...");
    }

    public static void main(String args[]) {
        TaskRunner task = new TaskRunner();
        Thread t1 = new Thread(task); // Using the constructor Thread(Runnable r)
        t1.start();
    }
}
Explanation: 1) TaskRunner implements Runnable, so it must define run(). 2) run() prints the required message when the thread executes. 3) In main, an object task of TaskRunner is created. 4) new Thread(task) passes the Runnable to the Thread constructor. 5) t1.start() creates a new call stack and moves the thread to Runnable state; its run() then executes and prints the message.
Q136.Easy
Write a Java program that performs two different tasks using two threads, where each task is defined in its own class that extends Thread. The first thread's run() should print "Task: counting" and the second thread's run() should print "Task: printing". Name the file TwoTasks.java.
Show answer & explanation
Answer:
class CountTask extends Thread {
    public void run() {
        System.out.println("Task: counting");
    }
}

class PrintTask extends Thread {
    public void run() {
        System.out.println("Task: printing");
    }
}

public class TwoTasks {
    public static void main(String[] args) {
        CountTask t1 = new CountTask();
        PrintTask t2 = new PrintTask();
        t1.start();
        t2.start();
    }
}
Explanation: 1) Create class CountTask extending Thread with run() printing "Task: counting". 2) Create class PrintTask extending Thread with run() printing "Task: printing". 3) In main, instantiate one object of each class. 4) Call start() on both objects; each start() creates a new call stack and invokes its own run(). 5) Both tasks execute concurrently, so output order is not fixed.
Q137.Easy
Write a Java program that performs two different tasks using two threads created via anonymous inner classes that extend the Thread class. The first thread should print "Namaste from Thread A" and the second thread should print "Namaste from Thread B". Name the file GreetThreads.java.
Show answer & explanation
Answer:
public class GreetThreads {
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                System.out.println("Namaste from Thread A");
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                System.out.println("Namaste from Thread B");
            }
        };
        t1.start();
        t2.start();
    }
}
Explanation: 1) Define a public class GreetThreads with a main method. 2) Create thread t1 as an anonymous subclass of Thread, overriding run() to print "Namaste from Thread A". 3) Create thread t2 the same way, printing "Namaste from Thread B". 4) Call t1.start() and t2.start() so each thread runs its own run() in a separate call stack. 5) The two messages may appear in any order because threads run concurrently.
Q138.Easy
Write a Java program that uses the String.join() method to combine the words "namaste", "from", "bharat" using the delimiter "-" and prints the resulting string. Name the file GreetingJoin.java.
Show answer & explanation
Answer:
public class GreetingJoin {
    public static void main(String args[]) {
        String joined = String.join("-", "namaste", "from", "bharat");
        System.out.println(joined);
    }
}
Explanation: Step 1: String.join("-", "namaste", "from", "bharat") joins each word with the delimiter '-' between them. Step 2: The result is "namaste-from-bharat". Step 3: System.out.println prints that string followed by a newline. Step 4: Output: namaste-from-bharat
Q139.Easy
Write a Java program that uses the String.join() method with a delimiter to format a date and a time. Join the day, month and year values "14", "08", "2023" using "/" to form the date, and join the hour, minute and second values "09", "45", "30" using ":" to form the time. Print the date, then a space, then the time on the same line. Name the file DateJoinExample.java.
Show answer & explanation
Answer:
public class DateJoinExample {
    public static void main(String[] args) {
        String date = String.join("/", "14", "08", "2023");
        System.out.print(date);
        String time = String.join(":", "09", "45", "30");
        System.out.println(" " + time);
    }
}
Explanation: Step 1: String.join("/", "14", "08", "2023") joins the three parts with '/' giving "14/08/2023". Step 2: System.out.print prints the date without a newline. Step 3: String.join(":", "09", "45", "30") joins the parts with ':' giving "09:45:30". Step 4: System.out.println(" " + time) prints a space followed by the time and then a newline. Step 5: Final output is: 14/08/2023 09:45:30
Q140.Easy
Write a Java program that calls String.join() with a null delimiter and the elements "red", "green", "blue". The program should demonstrate that using null as the delimiter throws a NullPointerException. Name the class JoinNullDelimiter.
Show answer & explanation
Answer:
public class JoinNullDelimiter
{
    public static void main(String[] args)
    {
        String result = null;
        result = String.join(null, "red", "green", "blue");
        System.out.println(result);
    }
}
Explanation: 1) String.join(delimiter, elements...) requires a non-null delimiter. 2) Internally it calls Objects.requireNonNull(delimiter), which throws NullPointerException when the delimiter is null. 3) So String.join(null, "red", "green", "blue") throws a NullPointerException at runtime. 4) The println line is never reached; the program terminates with the exception.
Q141.Easy
Write a Java program that uses String.join() with a delimiter "|" and a list of elements where the first element is null, followed by " chai ", " samosa ", " study Java ", " samosa ", " sleep ". The null element should be treated as a normal string (no exception). Print the joined result. Name the class JoinDemo.
Show answer & explanation
Answer:
public class JoinDemo
{
    public static void main(String[] args)
    {
        String result = null;
        result = String.join("|", null, " chai ", " samosa ", " study Java ", " samosa ", " sleep ");
        System.out.println(result);
    }
}
Explanation: 1) String.join(delimiter, elements...) joins the given CharSequence elements using the delimiter. 2) Here the delimiter is "|" and the first element passed is null. 3) String.join converts each element with String.valueOf(), so null becomes the literal text "null" instead of throwing an exception. 4) The elements are concatenated in order: null + "|" + " chai " + "|" + " samosa " + "|" + " study Java " + "|" + " samosa " + "|" + " sleep ". 5) Output: null| chai | samosa | study Java | samosa | sleep
Q142.Easy
Write a Java program that creates an immutable class named 'Citizen' having one final data member 'aadhaarNumber', a parameterized constructor to set it, and a getter method. Then in a main method create a Citizen object with Aadhaar number "9876 5432 1098" and print it as "Aadhaar Number: ...".
Show answer & explanation
Answer:
final class Citizen {
    final String aadhaarNumber;
    public Citizen(String aadhaarNumber) {
        this.aadhaarNumber = aadhaarNumber;
    }
    public String getAadhaarNumber() {
        return aadhaarNumber;
    }
}

public class ImmutableDemo {
    public static void main(String ar[]) {
        Citizen c = new Citizen("9876 5432 1098");
        String s1 = c.getAadhaarNumber();
        System.out.println("Aadhaar Number: " + s1);
    }
}
Explanation: 1) Declare the class Citizen as final so it cannot be subclassed and its behaviour cannot be altered. 2) Make the data member aadhaarNumber final so it can be assigned only once, in the constructor. 3) Provide only a getter (no setter) so the value cannot be changed after construction. 4) In main, create a Citizen with the given Aadhaar number and read it via the getter. 5) Print "Aadhaar Number: " followed by the value, giving the immutable-class demonstration.
Q143.Easy
Write a Java program that demonstrates garbage collection: create a class named 'Courier' whose finalize() method prints "courier object is garbage collected". In main, create two Courier objects, set both references to null, and then request garbage collection using System.gc().
Show answer & explanation
Answer:
public class Courier {
    public void finalize() {
        System.out.println("courier object is garbage collected");
    }
    public static void main(String args[]) {
        Courier c1 = new Courier();
        Courier c2 = new Courier();
        c1 = null;
        c2 = null;
        System.gc();
    }
}
Explanation: 1) Define class Courier with a finalize() method that prints the message; the GC calls finalize() before reclaiming an object. 2) In main, create two Courier objects c1 and c2. 3) Set c1 = null and c2 = null so no live reference points to them, making them eligible for garbage collection. 4) Call System.gc() to request the JVM's garbage collector (a daemon thread) to run. 5) When GC collects the objects, finalize() runs and prints the message (timing may vary).
Q144.Easy
Write a Java program that stores the string "delhi is capital of india" in a variable and prints the last index of the character 'i' in that string. File name: LastIndexExample.java
Show answer & explanation
Answer:
public class LastIndexExample {
    public static void main(String[] args) {
        String s1 = "delhi is capital of india";
        int index1 = s1.lastIndexOf('i');
        System.out.println(index1);
    }
}
Explanation: 1) The string is "delhi is capital of india". 2) lastIndexOf('i') returns the position of the last occurrence of 'i'. 3) Counting indices: d(0)e(1)l(2)h(3)i(4) (5)i(6)s(7) (8)c(9)a(10)p(11)i(12)t(13)a(14)l(15) (16)o(17)f(18) (19)i(20)n(21)d(22)i(23)a(24). 4) The last 'i' is at index 23. 5) So the program prints 23.
Q145.Easy
Write a Java program named LastIndexOfExample3.java that demonstrates the String lastIndexOf(String substring) method. Use the string "Delhi is the last stop of journey" and print the index returned by lastIndexOf("of").
Show answer & explanation
Answer:
public class LastIndexOfExample3 {
    public static void main(String[] args) {
        String str = "Delhi is the last stop of journey";
        int index = str.lastIndexOf("of");
        System.out.println(index);
    }
}
Explanation: 1) Create the string "Delhi is the last stop of journey". 2) lastIndexOf("of") finds the last occurrence of the substring "of". 3) Counting from 0, the substring "of" starts at index 25. 4) The program prints 25.
Q146.Easy
Write a Java program that stores the string "Mumbai is the city of dreams" in a variable and finds the last index of the character 'i' searching backwards starting from index 7 (i.e., using lastIndexOf('i', 7)). Print the resulting index. File name: LastIndexFromExample.java
Show answer & explanation
Answer:
public class LastIndexFromExample {
    public static void main(String[] args) {
        String str = "Mumbai is the city of dreams";
        int index = str.lastIndexOf('i', 7);
        System.out.println(index);
    }
}
Explanation: 1) The string is "Mumbai is the city of dreams". 2) lastIndexOf('i', 7) searches for 'i' from index 7 backwards towards index 0. 3) Indices: 0=M,1=u,2=m,3=b,4=a,5=i,6=' ',7=i. 4) The first 'i' found scanning backwards from 7 is at index 7 itself. 5) So the program prints 7.
Q147.Easy
Write a Java program named LastIndexOfExample4.java that demonstrates the String lastIndexOf(String substring, int fromIndex) method. Use the string "Mumbai is the last stop of journey" and print the result of lastIndexOf("of", 30) and then lastIndexOf("of", 12).
Show answer & explanation
Answer:
public class LastIndexOfExample4 {
    public static void main(String[] args) {
        String str = "Mumbai is the last stop of journey";
        int index = str.lastIndexOf("of", 30);
        System.out.println(index);
        index = str.lastIndexOf("of", 12);
        System.out.println(index); // -1, if not found
    }
}
Explanation: 1) Create the string "Mumbai is the last stop of journey". 2) lastIndexOf("of", 30) searches backwards starting at index 30; the substring "of" occurs at index 26, so it prints 26. 3) lastIndexOf("of", 12) searches backwards from index 12; "of" does not occur at or before index 12, so it prints -1. 4) The program prints 26 on the first line and -1 on the second line.
Q148.Easy
Write a Java program that reverses a given string without using any built-in reverse method. Use the string "Java Programming". The program should print the original string and then its reverse.
Show answer & explanation
Answer:
public class StringReverser {
    public static void main(String[] args) {
        String str = "Java Programming";
        int len = str.length();
        System.out.println("Original string: '" + str + "'");
        System.out.print("Reverse: ");
        for (int i = 0; i < len; i++) {
            System.out.print(str.charAt(len - i - 1));
        }
        System.out.println();
    }
}
Explanation: 1. Store the string "Java Programming" in a variable. 2. Get its length using length() (16 characters). 3. Loop from i = 0 to length-1. 4. In each iteration, print the character at index (length - i - 1), which starts from the last character and moves backwards. 5. This prints the string in reverse order: "gnimmargorP avaJ".
Q149.Easy
Write a Java program that counts the number of whitespace characters in a given string. Use the string "  Hello World  " (with two leading and two trailing spaces). The program should print the original string, then compute and print the total number of whitespace characters. Use the length() method and remove spaces to find the count.
Show answer & explanation
Answer:
public class WhitespaceCounter {
    public static void main(String[] args) {
        String str = "  Hello World  ";
        int sizeWithSpaces = str.length();
        System.out.println("Original string: '" + str + "'");
        String noSpaces = str.replace(" ", "");
        int sizeWithoutSpaces = noSpaces.length();
        int whitespaceCount = sizeWithSpaces - sizeWithoutSpaces;
        System.out.println("Total whitespace characters: " + whitespaceCount);
    }
}
Explanation: 1. Initialize the string with two leading and two trailing spaces: " Hello World ". 2. Find the total length using str.length(). The string has 2 + 5 (Hello) + 1 (space) + 5 (World) + 2 = 15 characters. 3. Remove all spaces using replace(" ", "") to get "HelloWorld". 4. Find the length of the new string: 10 characters. 5. Subtract the two lengths: 15 - 10 = 5 whitespace characters. 6. Print the original string and the count.
Q150.Easy
Write a Java program that shows what happens when the toString() method is NOT overridden. Create a class Customer with fields custId (int), custName (String) and custCity (String) and a constructor that initialises them. In main, create Customer(301, "Ravi", "Nagpur") and Customer(302, "Sneha", "Indore") and print each object directly using System.out.println(). Explain why the output is not the field values.
Show answer & explanation
Answer:
class Customer {
    int custId;
    String custName;
    String custCity;

    Customer(int custId, String custName, String custCity) {
        this.custId = custId;
        this.custName = custName;
        this.custCity = custCity;
    }

    public static void main(String args[]) {
        Customer c1 = new Customer(301, "Ravi", "Nagpur");
        Customer c2 = new Customer(302, "Sneha", "Indore");

        System.out.println(c1); // compiler calls c1.toString()
        System.out.println(c2); // compiler calls c2.toString()
    }
}
Explanation: 1) Define class Customer with fields custId, custName, custCity and a constructor that sets them. 2) toString() is NOT overridden, so the inherited Object.toString() is used. 3) Object.toString() returns ClassName@hexHashCode, e.g. Customer@1a2b3c. 4) In main, c1 and c2 are created and printed. 5) System.out.println(c1) calls c1.toString() which gives something like Customer@hashcode, not the field values. 6) To print field values we must override toString() as in the previous program.
Q151.Easy
Write a Java program that demonstrates overriding the toString() method. Create a class Employee with fields empId (int), empName (String) and empCity (String). The constructor should initialise these fields, and the toString() method should return the three values separated by spaces. In main, create two Employee objects — Employee(201, "Anil", "Pune") and Employee(202, "Meera", "Jaipur") — and print each object directly using System.out.println().
Show answer & explanation
Answer:
class Employee {
    int empId;
    String empName;
    String empCity;

    Employee(int empId, String empName, String empCity) {
        this.empId = empId;
        this.empName = empName;
        this.empCity = empCity;
    }

    public String toString() { // overriding the toString() method
        return empId + " " + empName + " " + empCity;
    }

    public static void main(String args[]) {
        Employee e1 = new Employee(201, "Anil", "Pune");
        Employee e2 = new Employee(202, "Meera", "Jaipur");

        System.out.println(e1); // compiler calls e1.toString()
        System.out.println(e2); // compiler calls e2.toString()
    }
}
Explanation: 1) Define class Employee with fields empId, empName, empCity. 2) The constructor assigns the passed values to the fields using this. 3) Override toString() so it returns empId + " " + empName + " " + empCity. 4) In main, create e1 = (201, Anil, Pune) and e2 = (202, Meera, Jaipur). 5) System.out.println(e1) automatically calls e1.toString(), so it prints: 201 Anil Pune. 6) Similarly e2 prints: 202 Meera Jaipur.
Q152.Easy
Write a Java program named ReplaceExample1.java that creates the string "delhi is a very big city", replaces every occurrence of the character 'i' with 'e' using the String replace(char, char) method, and prints the resulting string.
Show answer & explanation
Answer:
public class ReplaceExample1{
public static void main(String args[]){
String s1="delhi is a very big city";
String replaceString=s1.replace('i','e');
System.out.println(replaceString);
}}
Explanation: Step 1: The class ReplaceExample1 contains the main method. Step 2: s1 holds "delhi is a very big city". Step 3: s1.replace('i','e') replaces every character 'i' with 'e'. Step 4: The 'i' in delhi, is, big and city all become 'e'. Step 5: The program prints: delhe es a very beg cety.
Q153.Easy
Write a Java program named ReplaceExample2.java that creates the string "my city is Pune my city is clean", replaces every occurrence of the sequence "is" with "was" using the String replace(CharSequence, CharSequence) method, and prints the resulting string.
Show answer & explanation
Answer:
public class ReplaceExample2{
public static void main(String args[]){
String s1="my city is Pune my city is clean";
String replaceString=s1.replace("is","was");
System.out.println(replaceString);
}}
Explanation: Step 1: The class ReplaceExample2 contains the main method. Step 2: s1 holds "my city is Pune my city is clean". Step 3: s1.replace("is","was") replaces every occurrence of the CharSequence "is" with "was". Step 4: The word "is" appears twice, so both become "was". Step 5: The program prints: my city was Pune my city was clean.
Q154.Easy
Write a Java program that starts with the string "aaaaaa-bbbb-aaaaaa". First replace every 'b' with 'c' and print the result. Then, on that new string, replace every 'c' back with 'b' and print the result again.
Show answer & explanation
Answer:
public class ReplaceChainDemo {
    public static void main(String[] args) {
        String str = "aaaaaa-bbbb-aaaaaa";
        String rs = str.replace("b", "c"); // Replace 'b' with 'c'
        System.out.println(rs);
        rs = rs.replace("c", "b"); // Replace 'c' with 'b'
        System.out.println(rs);
    }
}
Explanation: 1. str = "aaaaaa-bbbb-aaaaaa". 2. str.replace("b","c") changes all 'b' characters to 'c', giving "aaaaaa-cccc-aaaaaa", which is printed. 3. On that result, replace("c","b") changes all 'c' characters back to 'b', giving "aaaaaa-bbbb-aaaaaa", which is printed. 4. replace() returns a new String each time; the original str is unchanged unless reassigned.
Q155.Easy
Write a Java program that demonstrates that the String replace() method throws a NullPointerException when the target (the string to be replaced) is null. Use the string "Ravi is learning Java at Pune Institute." and try to replace a null target with "Mumbai". Print the original string first, then perform the replace and print the result.
Show answer & explanation
Answer:
public class ReplaceNullDemo
{
    public static void main(String[] args)
    {
        String text = "Ravi is learning Java at Pune Institute.";
        System.out.println(text);

        String target = null;

        // Replacing a null target raises NullPointerException
        text = text.replace(target, "Mumbai");

        System.out.println(text);
    }
}
Explanation: 1. Create a String text with the given sentence and print it. 2. Declare String target = null. 3. Call text.replace(target, "Mumbai"). Since the target is null, the replace() method throws a NullPointerException at runtime. 4. Because the exception is not caught, the program terminates and the second println never executes. 5. This demonstrates that replace() requires a non-null target (and replacement).
Q156.Easy
Write a Java program that uses the StringTokenizer class to tokenize the string "java is very easy" on the basis of whitespace and print each token on a new line. Name the class TokenDemo.
Show answer & explanation
Answer:
import java.util.StringTokenizer;
public class TokenDemo{
 public static void main(String args[]){
   StringTokenizer st = new StringTokenizer("java is very easy"," ");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }
   }
}
Explanation: 1) Import java.util.StringTokenizer. 2) Create a StringTokenizer with the string "java is very easy" and delimiter " " (space). 3) hasMoreTokens() returns true while tokens remain. 4) nextToken() returns each word in order: java, is, very, easy, each printed on its own line.
Q157.Easy
Write a Java program that demonstrates the nextToken(String delim) method of the StringTokenizer class. Create a class named Demo and tokenize the string "red;green;blue;yellow" using the delimiter ";", then print the first token with the message "First token is : ".
Show answer & explanation
Answer:
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        StringTokenizer st = new StringTokenizer("red;green;blue;yellow");

        // printing next token using the given delimiter
        System.out.println("First token is : " + st.nextToken(";"));
    }
}
Explanation: 1) Import java.util.* to get StringTokenizer. 2) Create a StringTokenizer over "red;green;blue;yellow" (default constructor, no delimiters set). 3) Call nextToken(";") which overrides the default delimiters and returns the substring up to the first ";". 4) That substring is "red", so the program prints: First token is : red.
Q158.Easy
Write a Java program that demonstrates the hasMoreTokens() method of the StringTokenizer class. Tokenize the string "Learning Java is fun" using a space delimiter and print each token on a new line using a while loop with hasMoreTokens() and nextToken(). Name the class TokenCheckDemo.
Show answer & explanation
Answer:
import java.util.StringTokenizer;

public class TokenCheckDemo
{
    public static void main(String args[])
    {
        StringTokenizer st = new StringTokenizer("Learning Java is fun", " ");
        while (st.hasMoreTokens())
        {
            System.out.println(st.nextToken());
        }
    }
}
Explanation: 1) Import java.util.StringTokenizer. 2) Build a StringTokenizer over "Learning Java is fun" with " " as the delimiter. 3) hasMoreTokens() returns true while more tokens are available, false when exhausted. 4) The while loop calls nextToken() to fetch and print each token on its own line. 5) Output: Learning, Java, is, fun each on a separate line.
Q159.Easy
Write a Java program that demonstrates the hasMoreElements() method of the StringTokenizer class. Use the string "Ravi is learning Java programming" with a space delimiter, and print each token on its own line by looping with hasMoreElements() and calling nextToken(). Name the class TokenEnumDemo.
Show answer & explanation
Answer:
import java.util.StringTokenizer;

public class TokenEnumDemo
{
    public static void main(String args[])
    {
        StringTokenizer st = new StringTokenizer("Ravi is learning Java programming", " ");
        while (st.hasMoreElements())
        {
            System.out.println(st.nextToken());
        }
    }
}
Explanation: 1) Import java.util.StringTokenizer. 2) Create a StringTokenizer on "Ravi is learning Java programming" with delimiter " ". 3) hasMoreElements() returns true while tokens remain (it behaves like hasMoreTokens() via the Enumeration interface). 4) Inside the loop, nextToken() returns the next token and println prints it on its own line. 5) Output: Ravi, is, learning, Java, programming each on a separate line.
Q160.Easy
Write a Java program that uses the nextElement() method of the StringTokenizer class to print each token of the string "Mumbai Pune Nagpur Nashik" (tokens separated by spaces) one per line. Name the class TokenPrinter.
Show answer & explanation
Answer:
import java.util.StringTokenizer;

public class TokenPrinter {
    public static void main(String[] args) {
        StringTokenizer st = new StringTokenizer("Mumbai Pune Nagpur Nashik", " ");
        while (st.hasMoreTokens()) {
            System.out.println(st.nextElement());
        }
    }
}
Explanation: 1. Import java.util.StringTokenizer. 2. Create a StringTokenizer on "Mumbai Pune Nagpur Nashik" with space as delimiter. 3. hasMoreTokens() is true while tokens remain; inside the loop nextElement() returns the next token as an Object and println prints it. 4. The loop prints Mumbai, Pune, Nagpur, Nashik each on its own line, then stops.
Q161.Easy
Write a Java program that uses the countTokens() method of the StringTokenizer class to count how many tokens are present in the string "Ravi is going to Delhi tomorrow" (tokens separated by spaces), and prints the total number of tokens. Name the class TokenCounter.
Show answer & explanation
Answer:
import java.util.StringTokenizer;

public class TokenCounter {
    public static void main(String[] args) {
        StringTokenizer st = new StringTokenizer("Ravi is going to Delhi tomorrow", " ");
        System.out.println("Total number of Tokens: " + st.countTokens());
    }
}
Explanation: 1. Import java.util.StringTokenizer. 2. Create a StringTokenizer on the string "Ravi is going to Delhi tomorrow" with space as the delimiter. 3. countTokens() returns the number of tokens not yet read; since none have been read, it counts all 6 words: Ravi, is, going, to, Delhi, tomorrow. 4. Print the result, which is 6.
Q162.Easy
Write a Java program that takes the sentence "java is a very good language" and uses the String replaceAll() method to replace every occurrence of the character 'a' with 'e', then prints the result. Name the file ReplaceCharDemo.java.
Show answer & explanation
Answer:
public class ReplaceCharDemo {
    public static void main(String[] args) {
        String s1 = "java is a very good language";
        String replaced = s1.replaceAll("a", "e");
        System.out.println(replaced);
    }
}
Explanation: 1. Store the sentence in a String variable s1. 2. Call s1.replaceAll("a", "e"); internally this compiles the regex "a" and replaces every match with "e". 3. The returned string is stored in replaced. 4. Print replaced, giving: "jeve is e very good lenguege".
Q163.Easy
Write a Java program that takes the sentence "Ravi is a cricketer. Ravi is a singer. Ravi is a dancer." and uses the String replaceAll() method to replace every occurrence of the word "is" with "was", then prints the resulting sentence. Name the file ReplaceWordDemo.java.
Show answer & explanation
Answer:
public class ReplaceWordDemo {
    public static void main(String[] args) {
        String s1 = "Ravi is a cricketer. Ravi is a singer. Ravi is a dancer.";
        String replaced = s1.replaceAll("is", "was");
        System.out.println(replaced);
    }
}
Explanation: 1. Store the original sentence in a String variable s1. 2. Call s1.replaceAll("is", "was") which uses a regex to find every occurrence of "is" and replaces it with "was". 3. Store the returned new string in replaced (String is immutable, so s1 is unchanged). 4. Print replaced, giving: "Ravi was a cricketer. Ravi was a singer. Ravi was a dancer.".
Q164.Easy
Write a Java program that removes all white spaces from the string "Amit Sharma is from Pune. Amit Sharma is a teacher. Amit Sharma is happy." using the String replaceAll() method with the regular expression \s, and prints the resulting string.
Show answer & explanation
Answer:
public class ReplaceAllDemo
{
    public static void main(String[] args)
    {
        String s1 = "Amit Sharma is from Pune. Amit Sharma is a teacher. Amit Sharma is happy.";
        String replaceString = s1.replaceAll("\\s", "");
        System.out.println(replaceString);
    }
}
Explanation: Step 1: Store the sentence in s1. Step 2: Call s1.replaceAll("\\s", "") — the regex \s matches every whitespace character (spaces here) and replaces each with the empty string. Step 3: All spaces are deleted, so the words get joined together. Step 4: The output is: AmitSharmaisfromPune.AmitSharmaisateacher.AmitSharmaishappy.
Q165.Easy
Write a Java program that demonstrates that the replaceAll() method of the String class does not accept a null regular expression. Create a string "BharatBazaar", print it, then call replaceAll() with a null regex and a replacement of " ", and print the result. The program should show that a NullPointerException is raised. Name the file ReplaceAllNullDemo.java and the class ReplaceAllNullDemo.
Show answer & explanation
Answer:
public class ReplaceAllNullDemo
{
    // main method
    public static void main(String[] args)
    {
        // input string
        String shop = "BharatBazaar";
        System.out.println(shop);

        String regex = null; // regular expression is null

        // this line throws NullPointerException
        shop = shop.replaceAll(regex, " ");

        System.out.println(shop);
    }
}
Explanation: Step 1: Declare a String variable shop with value "BharatBazaar" and print it. Step 2: Declare String regex = null, meaning no regular expression is supplied. Step 3: Call shop.replaceAll(regex, " "). Inside replaceAll(), the method tries to use the regex (e.g. Pattern.compile(regex)), and since it is null a NullPointerException is thrown. Step 4: Because the exception is not caught, the program terminates at that line and the second println is never executed. Step 5: So the output is the first line "BharatBazaar" followed by a NullPointerException stack trace, proving that replaceAll() does not accept a null regex.
Q166.Easy
Write a Java program that declares a Writer variable referring to a FileWriter for a file named diary.txt, writes the string "India is my homeland" to it, closes the writer, and prints "Finished" to the console. Use a try-catch block to handle IOException.
Show answer & explanation
Answer:
import java.io.*;
public class DiaryWriter {
    public static void main(String[] args) {
        try {
            Writer w = new FileWriter("diary.txt");
            String content = "India is my homeland";
            w.write(content);
            w.close();
            System.out.println("Finished");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Explanation: 1) Import java.io.* to get Writer, FileWriter and IOException. 2) Inside try, create a Writer reference w = new FileWriter("diary.txt"). 3) Store the text "India is my homeland" in a String variable. 4) Call w.write(content) to write the string to the file. 5) Call w.close() to flush and close the stream. 6) Print "Finished"; catch IOException and print its stack trace if anything fails.
Q167.Easy
Write a Java program that uses the FileWriter class to write the text "Namaste from Mumbai" into a file named notes.txt, then closes the writer and prints "Saved" to the console. Handle any exception using try-catch.
Show answer & explanation
Answer:
import java.io.FileWriter;
public class NotesWriter {
    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter("notes.txt");
            fw.write("Namaste from Mumbai");
            fw.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("Saved");
    }
}
Explanation: 1) Import java.io.FileWriter. 2) Create a FileWriter object pointing to notes.txt inside a try block. 3) Call fw.write("Namaste from Mumbai") to write the string to the file. 4) Call fw.close() to flush and release the file. 5) Catch any exception (e.g., IOException) and print it. 6) After the try-catch, print "Saved".
Q168.Easy
Write a Java program that shows the String.startsWith() method is case-sensitive. Create a String variable holding the value "mumbai local train timetable by indianrail". Print the result of startsWith("mu"), startsWith("mumbai local"), and startsWith("Mumbai local"). Name the class StartsWithCaseDemo.
Show answer & explanation
Answer:
public class StartsWithCaseDemo {
    public static void main(String[] args) {
        String s1 = "mumbai local train timetable by indianrail";
        System.out.println(s1.startsWith("mu"));            // true
        System.out.println(s1.startsWith("mumbai local"));  // true
        System.out.println(s1.startsWith("Mumbai local"));  // false, 'm' and 'M' differ
    }
}
Explanation: 1. Declare s1 = "mumbai local train timetable by indianrail". 2. s1.startsWith("mu") compares the first two characters 'm','u' with 'm','u' -> true. 3. s1.startsWith("mumbai local") matches the beginning exactly -> true. 4. s1.startsWith("Mumbai local") compares 'M' with the actual first character 'm'; since Java is case-sensitive these differ -> false. 5. Hence the method respects case, printing true, true, false.
Q169.Easy
Write a Java program that demonstrates the overloaded String.startsWith(String prefix, int offset) method. Create a String variable holding the value "Bengaluru". Print the result of checking whether it starts with "B" (no offset), whether it starts with "e" (no offset), and whether it starts with "e" starting from offset 1. Name the class StartsWithOffsetDemo.
Show answer & explanation
Answer:
public class StartsWithOffsetDemo {
    public static void main(String[] args) {
        String city = "Bengaluru";
        // no offset given, so offset is 0
        System.out.println(city.startsWith("B")); // true
        // no offset given, so offset is 0
        System.out.println(city.startsWith("e")); // false
        // offset is 1
        System.out.println(city.startsWith("e", 1)); // true
    }
}
Explanation: 1. Declare a String city = "Bengaluru". 2. city.startsWith("B") uses offset 0, and the first character is 'B', so it prints true. 3. city.startsWith("e") also uses offset 0; the first character is 'B', not 'e', so it prints false. 4. city.startsWith("e", 1) begins checking at index 1, where the character is 'e', so it prints true. 5. The overloaded method simply compares the prefix starting from the given offset.
Q170.Easy
Write a Java program that demonstrates an abstract class for banks. Create an abstract class Bank with an abstract method getRateOfInterest() returning int. Create two subclasses, HDFC (returns 6) and ICICI (returns 9), each overriding the method. In the main method of class TestBank, create one object of each subclass and print their rates of interest.
Show answer & explanation
Answer:
abstract class Bank {
    abstract int getRateOfInterest();
}

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

class ICICI extends Bank {
    int getRateOfInterest() { return 9; }
}

public class TestBank {
    public static void main(String[] args) {
        Bank b1 = new HDFC();
        Bank b2 = new ICICI();
        System.out.println("HDFC rate of interest: " + b1.getRateOfInterest());
        System.out.println("ICICI rate of interest: " + b2.getRateOfInterest());
    }
}
Explanation: 1) Bank is declared abstract with an abstract method getRateOfInterest(), so it cannot be instantiated directly. 2) HDFC and ICICI extend Bank and provide their own implementations returning 6 and 9. 3) In main, references of type Bank point to HDFC and ICICI objects. 4) Calling getRateOfInterest() invokes the subclass version (runtime polymorphism). 5) Output: HDFC rate of interest: 6 and ICICI rate of interest: 9.
Q171.Easy
Write a Java program to demonstrate inheritance. Create a superclass Teacher with a field salary = 35000 (float). Create a subclass Lecturer that extends Teacher and adds a field allowance = 8000 (int). In the main method of Lecturer, create a Lecturer object and print "Lecturer salary is:" followed by the salary, then print "Allowance of Lecturer is:" followed by the allowance.
Show answer & explanation
Answer:
class Teacher {
    float salary = 35000;
}

class Lecturer extends Teacher {
    int allowance = 8000;

    public static void main(String args[]) {
        Lecturer l = new Lecturer();
        System.out.println("Lecturer salary is:" + l.salary);
        System.out.println("Allowance of Lecturer is:" + l.allowance);
    }
}
Explanation: 1. Teacher is the superclass holding the field salary = 35000. 2. Lecturer extends Teacher, so it inherits the salary field and adds allowance = 8000. 3. In main, a Lecturer object l is created. 4. l.salary accesses the inherited field and prints "Lecturer salary is:35000.0". 5. l.allowance accesses its own field and prints "Allowance of Lecturer is:8000". 6. The extends keyword establishes the IS-A relationship (Lecturer IS-A Teacher).
Q172.Easy
Write a Java program that demonstrates single inheritance. Create a class Vehicle with a method move() that prints "moving...". Create a class Car that extends Vehicle and adds a method honk() that prints "honking...". In a main method (in a class TestInheritance), create a Car object, call honk() and then call move().
Show answer & explanation
Answer:
class Vehicle {
    void move() {
        System.out.println("moving...");
    }
}

class Car extends Vehicle {
    void honk() {
        System.out.println("honking...");
    }
}

class TestInheritance {
    public static void main(String args[]) {
        Car c = new Car();
        c.honk();
        c.move();
    }
}
Explanation: 1. Vehicle is the superclass with method move(). 2. Car extends Vehicle, so it inherits move() and adds its own method honk(). 3. In main, a Car object c is created. 4. c.honk() prints "honking...". 5. c.move() is inherited from Vehicle and prints "moving...". 6. This is single inheritance: Car inherits from exactly one class, Vehicle.
Q173.Easy
Write a Java program that demonstrates multilevel inheritance. Create a class LivingThing with a method breathe() that prints "breathing...". Create a class Bird extending LivingThing with a method fly() that prints "flying...". Create a class Parrot extending Bird with a method speak() that prints "speaking...". In the main method, create a Parrot object and call speak(), fly() and breathe() in that order. Name the main class TestChain.
Show answer & explanation
Answer:
class LivingThing {
    void breathe() { System.out.println("breathing..."); }
}

class Bird extends LivingThing {
    void fly() { System.out.println("flying..."); }
}

class Parrot extends Bird {
    void speak() { System.out.println("speaking..."); }
}

class TestChain {
    public static void main(String args[]) {
        Parrot p = new Parrot();
        p.speak();
        p.fly();
        p.breathe();
    }
}
Explanation: 1) LivingThing is the top class with breathe(). 2) Bird extends LivingThing and adds fly(). 3) Parrot extends Bird and adds speak() — this forms a chain LivingThing -> Bird -> Parrot, i.e. multilevel inheritance. 4) A Parrot object inherits methods from both Bird and LivingThing, so it can call speak(), fly() and breathe(). 5) Output order: speaking..., flying..., breathing...
Q174.Easy
Write a Java program that demonstrates hierarchical inheritance. Create a parent class Vehicle with a method move() that prints "moving...". Create two child classes Car (with method honk() printing "honking...") and Bike (with method ring() printing "ringing..."), both extending Vehicle. In the main method, create a Bike object, call ring() and move() on it. (Calling honk() on the Bike object should not compile, so do not call it.) Name the main class TestHierarchy.
Show answer & explanation
Answer:
class Vehicle {
    void move() { System.out.println("moving..."); }
}

class Car extends Vehicle {
    void honk() { System.out.println("honking..."); }
}

class Bike extends Vehicle {
    void ring() { System.out.println("ringing..."); }
}

class TestHierarchy {
    public static void main(String args[]) {
        Bike b = new Bike();
        b.ring();
        b.move();
        // b.honk(); // Compile-time error: Bike has no honk()
    }
}
Explanation: 1) Vehicle is the parent class with method move(). 2) Car and Bike both extend Vehicle, so two classes inherit one parent — this is hierarchical inheritance. 3) Car adds honk(); Bike adds ring(). 4) In main, a Bike object b can call its own method ring() and the inherited method move(). 5) b.honk() would be a compile-time error because honk() belongs to Car, not Bike.
Q175.Easy
Write a Java program that prints 'Namaste India' to the console. The program should have a class named Greet with a main method.
Show answer & explanation
Answer:
public class Greet {
    public static void main(String[] args) {
        System.out.println("Namaste India");
    }
}
Explanation: 1. Define a public class named Greet. 2. Inside the class, define the main method with signature public static void main(String[] args). 3. In the main method, use System.out.println to print the string "Namaste India". 4. The program will output: Namaste India
Q176.Easy
Write a Java program that declares two integer variables a = 14 and b = 9. Using a simple if statement, check whether the sum of a and b is greater than 20, and if so print the message "a + b is greater than 20".
Show answer & explanation
Answer:
public class SumCheck {
    public static void main(String[] args) {
        int a = 14;
        int b = 9;
        if (a + b > 20) {
            System.out.println("a + b is greater than 20");
        }
    }
}
Explanation: 1) Two integers are declared: a = 14 and b = 9. 2) The if statement evaluates the Boolean expression a + b > 20. 3) a + b = 14 + 9 = 23, and 23 > 20 is true. 4) Since the condition is true, the block executes and prints "a + b is greater than 20". 5) If the sum had been 20 or less, the block would be skipped and nothing would print.
Q177.Easy
Write a Java program that uses a for loop to print the numbers from 0 to 15, but stops (breaks out of the loop) as soon as the number 9 is printed. Use the break statement inside the loop.
Show answer & explanation
Answer:
public class BreakDemo {
    public static void main(String[] args) {
        for (int i = 0; i <= 15; i++) {
            System.out.println(i);
            if (i == 9) {
                break;
            }
        }
    }
}
Explanation: 1) The for loop runs i from 0 up to 15. 2) Inside the loop, each value of i is printed first. 3) The if condition checks whether i equals 9. 4) When i becomes 9, the break statement executes and immediately exits the loop. 5) So the program prints 0 through 9 and then stops, never printing 10 to 15.
Q178.Easy
Write a Java program that uses a while loop to print the numbers 1, 2, 3, 4 and then exits the loop using the break statement when the counter reaches 5.
Show answer & explanation
Answer:
public class BreakWhileDemo {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            if (i == 5) {
                i++;
                break;
            }
            System.out.println(i);
            i++;
        }
    }
}
Explanation: 1. Initialise counter i = 1 and start a while loop that runs while i <= 10. 2. Inside the loop, check if i == 5; if so, increment i and execute break, which immediately terminates the loop. 3. Otherwise print the current value of i. 4. Increment i and repeat. 5. Output is 1, 2, 3, 4 — the loop stops before printing 5.
Q179.Easy
Write a Java program that demonstrates the if-else statement. Declare two int variables: marks = 35 and bonus = 8. If the sum of marks and bonus is less than 40, print "Total is below 40"; otherwise print "Total is 40 or above". Use an if-else block.
Show answer & explanation
Answer:
public class Result {
    public static void main(String[] args) {
        int marks = 35;
        int bonus = 8;
        if (marks + bonus < 40) {
            System.out.println("Total is below 40");
        } else {
            System.out.println("Total is 40 or above");
        }
    }
}
Explanation: 1) Declare marks = 35 and bonus = 8. 2) Compute marks + bonus = 43. 3) Check the condition 43 < 40, which is false. 4) Since the if condition is false, the else block runs. 5) Output: Total is 40 or above.
Q180.Easy
Write a Java program that demonstrates an if-else-if ladder. Declare a String variable named 'place' with the value "Jaipur". Compare it with "Indore", then with "Bhopal", then with "Surat" using else-if; if none match, print the value of 'place' itself.
Show answer & explanation
Answer:
public class Student {
public static void main(String[] args) {
String place = "Jaipur";
if(place == "Indore") {
System.out.println("place is indore");
}else if (place == "Bhopal") {
System.out.println("place is bhopal");
}else if(place == "Surat") {
System.out.println("place is surat");
}else {
System.out.println(place);
}
}
}
Explanation: 1) 'place' is set to "Jaipur". 2) The ladder checks place == "Indore" (false), then place == "Bhopal" (false), then place == "Surat" (false). 3) Since all conditions are false, the final else executes and prints the value of place. 4) Output: Jaipur
Q181.Easy
Write a Java program that uses an if-else-if ladder to check the value of a String variable named 'state' set to "Kerala". If state equals "Punjab", print "state is Punjab"; else if state equals "Gujarat", print "state is Gujarat"; else if state equals "Kerala", print "state is Kerala"; otherwise print the value of state.
Show answer & explanation
Answer:
public class Citizen {
    public static void main(String[] args) {
        String state = "Kerala";
        if (state.equals("Punjab")) {
            System.out.println("state is Punjab");
        } else if (state.equals("Gujarat")) {
            System.out.println("state is Gujarat");
        } else if (state.equals("Kerala")) {
            System.out.println("state is Kerala");
        } else {
            System.out.println(state);
        }
    }
}
Explanation: 1) Declare a String variable 'state' and assign "Kerala". 2) The first if checks state == "Punjab": false, so skip. 3) The else-if checks state == "Gujarat": false, so skip. 4) The next else-if checks state == "Kerala": true, so its block runs and prints "state is Kerala". 5) The final else is skipped because a condition already matched.
Q182.Easy
Write a Java program that demonstrates a nested if-statement. Declare a String variable named 'location' with the value "Pune, India". First check whether the location ends with "India". If it does, then inside that block check: if the location contains "Nagpur" print "Your city is Nagpur"; else if it contains "Nashik" print "Your city is Nashik"; otherwise print only the part of the location before the comma (i.e., the city name). If the location does not end with "India", print "You are not living in India".
Show answer & explanation
Answer:
public class Student {
public static void main(String[] args) {
String location = "Pune, India";

if(location.endsWith("India")) {
if(location.contains("Nagpur")) {
System.out.println("Your city is Nagpur");
}else if(location.contains("Nashik")) {
System.out.println("Your city is Nashik");
}else {
System.out.println(location.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Explanation: 1) The String 'location' is set to "Pune, India". 2) The outer if checks location.endsWith("India") — true, so we enter the block. 3) Inside, location.contains("Nagpur") is false, and location.contains("Nashik") is false. 4) So the inner else runs: location.split(",")[0] gives "Pune", which is printed. 5) Output: Pune
Q183.Easy
Write a Java program that stores the integer 3 in a variable and uses a switch statement with cases 0, 1, and a default case. For case 0 print "number is 0", for case 1 print "number is 1", and for the default case print the value of the variable. Each case must end with break (except default).
Show answer & explanation
Answer:
public class NumberSwitch {
    public static void main(String[] args) {
        int num = 3;
        switch (num) {
            case 0:
                System.out.println("number is 0");
                break;
            case 1:
                System.out.println("number is 1");
                break;
            default:
                System.out.println(num);
        }
    }
}
Explanation: 1) Declare int num = 3. 2) The switch evaluates num and compares it with case 0 (no match) and case 1 (no match). 3) Since no case matches, control jumps to the default block. 4) The default block prints the value of num, so the output is 3.
Q184.Easy
Write a Java program that uses a for loop to compute the sum of the first 15 natural numbers (1 to 15) and prints the result.
Show answer & explanation
Answer:
public class SumNatural {
    public static void main(String[] args) {
        int total = 0;
        for (int k = 1; k <= 15; k++) {
            total = total + k;
        }
        System.out.println("The sum of first 15 natural numbers is " + total);
    }
}
Explanation: 1) Declare an integer variable total and set it to 0 to hold the running sum. 2) Start a for loop with k = 1, condition k <= 15, and increment k++ each iteration. 3) Inside the loop add k to total, so total becomes 1, then 3, then 6, ... up to 120. 4) After the loop ends (k becomes 16), print the message with total, which is 120.
Q185.Easy
Write a Java program that uses an enhanced for loop (for-each loop) to iterate over an array of Indian city names: {"Delhi", "Mumbai", "Kolkata", "Chennai", "Bengaluru"} and prints each city on a new line. Use a class named CityList.
Show answer & explanation
Answer:
public class CityList {
    public static void main(String[] args) {
        String[] cities = {"Delhi", "Mumbai", "Kolkata", "Chennai", "Bengaluru"};
        System.out.println("List of cities:");
        for (String city : cities) {
            System.out.println(city);
        }
    }
}
Explanation: 1. Declare and initialize a String array cities with the five city names. 2. Print a header message. 3. Use a for-each loop: for (String city : cities) to iterate over each element. 4. Inside the loop, print the current city. 5. The loop automatically goes through all elements without needing an index or update statement.
Q186.Easy
Write a Java program that uses a while loop to print the first 10 positive even numbers (starting from 2) and then prints "Done" after the loop. Use a class named EvenNumbers.
Show answer & explanation
Answer:
public class EvenNumbers {
    public static void main(String[] args) {
        int num = 2;
        int count = 0;
        System.out.println("First 10 even numbers:");
        while (count < 10) {
            System.out.println(num);
            num = num + 2;
            count++;
        }
        System.out.println("Done");
    }
}
Explanation: 1. Initialize num = 2 (first even number) and count = 0 (numbers printed so far). 2. Use a while loop with condition count < 10. 3. Inside the loop, print num, then increase num by 2 to get the next even number, and increment count by 1. 4. After the loop, print "Done". 5. The loop runs exactly 10 times, printing 2, 4, 6, ..., 20.
Q187.Easy
Write a Java program using a while loop that prints the integers from 1 to 8, each on its own line. Initialize the loop variable before the loop and increment it inside the loop body so the loop does not run infinitely. Name the class WhileDemo.
Show answer & explanation
Answer:
public class WhileDemo {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 8) {
            System.out.println(i);
            i++;
        }
    }
}
Explanation: 1) Initialize i = 1 before the loop. 2) The condition i <= 8 is checked; while true, the body runs. 3) The body prints i and then increments i by 1. 4) When i becomes 9, the condition is false and the loop stops. 5) Output is the numbers 1 through 8, one per line.
Q188.Easy
Write a Java program using a do-while loop that prints the first 8 multiples of 3 starting from 3 (i.e., 3, 6, 9, ..., 24). Use a variable starting at 3 and increase it by 3 each iteration, continuing while the value is less than or equal to 24.
Show answer & explanation
Answer:
public class Multiples {
    public static void main(String[] args) {
        int i = 3;
        System.out.println("First 8 multiples of 3:");
        do {
            System.out.println(i);
            i = i + 3;
        } while (i <= 24);
    }
}
Explanation: Step 1: Initialize i = 3, the first multiple of 3. Step 2: The do block runs at least once, printing the current value of i. Step 3: After printing, add 3 to i to get the next multiple. Step 4: The while condition (i <= 24) is checked at the end; if true, the loop repeats. Step 5: Values printed are 3, 6, 9, 12, 15, 18, 21, 24 — exactly 8 multiples. When i becomes 27, the condition fails and the loop exits.
Q189.Easy
Write a Java program that uses a do-while loop to print the integers from 1 to 7, one per line. Initialize the counter before the loop and increment it inside the loop body so the loop terminates correctly.
Show answer & explanation
Answer:
public class DoWhileDemo {
    public static void main(String[] args) {
        int n = 1;
        do {
            System.out.println(n);
            n++;
        } while (n <= 7);
    }
}
Explanation: 1) Declare and initialize the counter n = 1 before the loop, since a do-while loop does not initialize variables itself. 2) Enter the do block: it always runs at least once, so it prints 1 first. 3) After printing, increment n by 1 (n++). 4) Check the condition n <= 7 at the end of each iteration; while true, repeat the body. 5) The loop prints 1,2,3,4,5,6,7 and stops when n becomes 8, because 8 <= 7 is false.
Q190.Easy
Write a Java program that demonstrates creating and using a user-defined package. Create a package named 'shop' and inside it define a public class 'Greeter' whose main method prints the message "Namaste from shop package". Save the file as Greeter.java inside the shop package.
Show answer & explanation
Answer:
package shop;

public class Greeter {
    public static void main(String[] args) {
        System.out.println("Namaste from shop package");
    }
}
Explanation: Step 1: The first line 'package shop;' declares that this class belongs to the package named shop. Step 2: The file must be saved as Greeter.java inside a folder named shop. Step 3: The class Greeter is declared public so it can be accessed from other packages. Step 4: The main method is the entry point and prints the required message using System.out.println. Step 5: Compile with 'javac shop/Greeter.java' and run with 'java shop.Greeter' using the fully qualified name.
Q191.Easy
Write a Java program that demonstrates importing all classes of a package using the form import packagename.*. Create a package named utilities containing two classes: Printer with a public method show() that prints "Printed from utilities" and Counter with a public method count() that prints "Counting in utilities". Then create a class WildcardImportDemo (in the default package) that uses import utilities.*; and calls both show() and count() from its main method. Save the package classes in Printer.java and Counter.java, and the demo in WildcardImportDemo.java.
Show answer & explanation
Answer:
// File: Printer.java
package utilities;

public class Printer {
    public void show() {
        System.out.println("Printed from utilities");
    }
}

// File: Counter.java
package utilities;

public class Counter {
    public void count() {
        System.out.println("Counting in utilities");
    }
}

// File: WildcardImportDemo.java
import utilities.*;

public class WildcardImportDemo {
    public static void main(String[] args) {
        Printer p = new Printer();
        p.show();
        Counter c = new Counter();
        c.count();
    }
}
Explanation: Step 1: Both Printer.java and Counter.java declare 'package utilities;' so they belong to the same package; their methods are public so they are usable outside the package. Step 2: Compile them with: javac -d . Printer.java Counter.java — this creates folder utilities with both .class files. Step 3: WildcardImportDemo.java uses 'import utilities.*;' which makes all classes of package utilities accessible (but not subpackages). Step 4: In main, objects of Printer and Counter are created and their methods called, printing 'Printed from utilities' and 'Counting in utilities'. Step 5: Compile and run with: javac WildcardImportDemo.java and java WildcardImportDemo.
Q192.Easy
Write a Java program that demonstrates importing a single class from a package using the form import package.classname. Create a package named mypack containing a class Greeter with a public method greet() that prints "Namaste from mypack". Then, in a separate file (default package), create a class SingleImportDemo that imports only mypack.Greeter (using import mypack.Greeter;) and calls greet() from its main method. Save the package class in Greeter.java and the demo class in SingleImportDemo.java.
Show answer & explanation
Answer:
// File: Greeter.java
package mypack;

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

// File: SingleImportDemo.java
import mypack.Greeter;

public class SingleImportDemo {
    public static void main(String[] args) {
        Greeter g = new Greeter();
        g.greet();
    }
}
Explanation: Step 1: Greeter.java declares 'package mypack;' so the class belongs to package mypack; the method greet() is public so it can be used outside the package. Step 2: Compile the package class with: javac -d . Greeter.java — this creates folder mypack containing Greeter.class. Step 3: SingleImportDemo.java uses 'import mypack.Greeter;' which makes only the Greeter class accessible (not other classes of mypack). Step 4: In main, an object of Greeter is created and greet() is called, printing 'Namaste from mypack'. Step 5: Compile and run with: javac SingleImportDemo.java and java SingleImportDemo.
Q193.Easy
Write a Java program that demonstrates how to place a class file into a specific directory using packages. Create a class named 'Greeting' in package 'mypack' that prints 'Hello from package'. Save the source file as Greeting.java. After compilation, the class file should be placed in a directory structure corresponding to the package name.
Show answer & explanation
Answer:
package mypack;

public class Greeting {
    public static void main(String[] args) {
        System.out.println("Hello from package");
    }
}
Explanation: 1. The package declaration 'package mypack;' must be the first line. 2. The public class name Greeting must match the file name Greeting.java. 3. Compile with 'javac -d . Greeting.java' to create the mypack directory and place Greeting.class inside it. 4. Run with 'java mypack.Greeting' to see the output.
Q194.Easy
Write a Java program that demonstrates the rule: there can be only one public class in a Java source file, and the file must be saved with the same name as the public class. Otherwise, it causes a compile-time error. Your program should include a public class named 'Main' and another non-public class named 'Helper'. Save the file as Main.java.
Show answer & explanation
Answer:
class Helper {
    void display() {
        System.out.println("Helper class");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Main class");
        Helper h = new Helper();
        h.display();
    }
}
Explanation: 1. The file must be named Main.java because the public class is Main. 2. Helper is a non-public class, so it can be in the same file. 3. The main method creates an instance of Helper and calls its display method. 4. Output: Main class followed by Helper class.
Q195.Easy
Write Java code to show how two public classes can be placed in the same package. Create two source files, each containing one public class, both declaring the same package name "myshop". The first file Shop.java should define public class Shop with an empty body, and the second file Item.java should define public class Item with an empty body.
Show answer & explanation
Answer:
//save as Shop.java
package myshop;
public class Shop{}

//save as Item.java
package myshop;
public class Item{}
Explanation: 1) A Java source file can contain only one public class, and the file name must match that class name. 2) So put the first public class Shop in its own file Shop.java. 3) Put the second public class Item in its own file Item.java. 4) Give both files the same package declaration `package myshop;` so both classes belong to the same package. 5) Compiling both files places Shop.class and Item.class in the myshop package, allowing two public classes in one package.
Q196.Easy
Write a Java program named StringDemo.java that creates three strings: one using a string literal "mango", one by converting a char array {'b','a','n','a','n','a'} into a String, and one using the new keyword with the text "apple". Print all three strings, each on its own line.
Show answer & explanation
Answer:
public class StringDemo{
public static void main(String args[]){
String s1="mango";//string created using a string literal
char ch[]={'b','a','n','a','n','a'};
String s2=new String(ch);//converting char array to string
String s3=new String("apple");//string created using the new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Explanation: 1) Declare s1 as a string literal "mango"; it goes into the string constant pool. 2) Declare a char array ch with the letters of "banana". 3) Create s2 using new String(ch), which converts the char array into a String object in heap memory. 4) Create s3 using new String("apple"), which makes a new String object in heap memory while the literal "apple" sits in the constant pool. 5) Print s1, s2 and s3 one per line, giving output: mango, banana, apple.
Q197.Easy
Write a Java program that demonstrates method overloading by changing the number of arguments. Create a class Sum with two static methods named add: the first add method takes two int arguments and returns their sum, and the second add method takes three int arguments and returns their sum. In the main method, print the result of add(6, 9) and the result of add(6, 9, 12).
Show answer & explanation
Answer:
class Sum {
    static int add(int a, int b) {
        return a + b;
    }
    static int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class TestOverloading {
    public static void main(String[] args) {
        System.out.println(Sum.add(6, 9));
        System.out.println(Sum.add(6, 9, 12));
    }
}
Explanation: 1) The two add methods differ only in the number of parameters, which is valid overloading. 2) add(6, 9) matches the two-argument version and returns 15, printed as 15. 3) add(6, 9, 12) matches the three-argument version and returns 27, printed as 27. 4) Because the methods are static, they are called using the class name without creating an object.
Q198.Easy
Write a Java program that demonstrates method overloading by changing the data type of arguments. Create a class Calculator with two static methods named add: the first add method takes two int arguments and returns their sum as an int, and the second add method takes two double arguments and returns their sum as a double. In the main method, print the result of add(7, 8) and the result of add(4.5, 5.25).
Show answer & explanation
Answer:
class Calculator {
    static int add(int a, int b) {
        return a + b;
    }
    static double add(double a, double b) {
        return a + b;
    }
}

public class TestOverloading {
    public static void main(String[] args) {
        System.out.println(Calculator.add(7, 8));
        System.out.println(Calculator.add(4.5, 5.25));
    }
}
Explanation: 1) Two methods share the name add but differ in parameter types (int vs double), which is valid overloading. 2) add(7, 8) matches the int version and returns 15, printed as 15. 3) add(4.5, 5.25) matches the double version and returns 9.75, printed as 9.75. 4) The compiler picks the correct method based on the argument types at compile time.
Q199.Easy
Write a Java program that counts how many times the character 'a' appears in the string "Welcome to Mumbai portal" using the charAt() method, and prints the frequency. Name the class FrequencyCounter.
Show answer & explanation
Answer:
public class FrequencyCounter {
    public static void main(String[] args) {
        String str = "Welcome to Mumbai portal";
        int count = 0;
        for (int i = 0; i <= str.length() - 1; i++) {
            if (str.charAt(i) == 'a') {
                count++;
            }
        }
        System.out.println("Frequency of a is: " + count);
    }
}
Explanation: 1) Store the text in str. 2) Start count at 0. 3) Loop i from 0 to str.length()-1 and read each character with str.charAt(i). 4) Each time the character equals 'a', increment count. 5) In "Welcome to Mumbai portal" the letter 'a' occurs in "Mumbai" (once) and in "portal" (once), so count = 2. 6) Print "Frequency of a is: 2".
Q200.Easy
Write a Java program that reads the contents of a text file named "sample.txt" using the FileReader class and prints the characters to the console. Assume the file exists in the current directory.
Show answer & explanation
Answer:
import java.io.FileReader;

public class FileReaderExample {
    public static void main(String[] args) throws Exception {
        FileReader fr = new FileReader("sample.txt");
        int i;
        while ((i = fr.read()) != -1) {
            System.out.print((char) i);
        }
        fr.close();
    }
}
Explanation: 1. Import java.io.FileReader. 2. Define a class FileReaderExample with a main method that throws Exception. 3. Create a FileReader object fr for the file "sample.txt". 4. Declare an integer variable i to hold each character read. 5. Use a while loop: read a character with fr.read(); if it returns -1, stop; otherwise cast i to char and print it. 6. After the loop, close the FileReader using fr.close().
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